#!/usr/bin/env bash
set -euo pipefail

USAGE="\
Usage:
  ./img_build.sh (--local_build) (-e|--env <environment>)
  Options:
    --local_build           Build from local instead of develop/sim branch. *Only allowed for local|dev builds.
    -e|--env <environment>  Set build environment. Default: dev (local|dev|test|prod|all)"

main_branch_name="develop/sim"
all_env=("local" "dev" "prod")

# local_build builds images from local git instead of develop/sim
local_build=false
env_config="dev"

while (( "$#" )); do
    case $1 in
        -h|--help)
            echo "$USAGE"
            exit 1
            ;;
        --local_build)
            local_build=true
            shift
            ;;
        -e=*|--env=*)
            env_config="${i#*=}"
            shift
            ;;
        -e|--env)
            if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
                env_config="$2"
                shift 2
            else
                echo "Error: Argument for $1 is missing" >&2
                exit 1
            fi
            ;;
        *) # Unkown option
            echo "Error Unsupported flag $1" >&2
            exit 1
            ;;
    esac
done

# Map 'test' env to 'prod'
if [ "$env_config" == "test" ]; then
    env_config="prod"
fi

if [ "$env_config" == "all" ]; then
    envs_to_build=all_env
else
    envs_to_build=("$env_config")
fi

if [ "$local_build" == true ]
then
    # Dirty, non-local builds are only allowed for the dev server.
    if [ "$env_config" == "dev" ]
    then
        echo -e "You are not on the main develop/sim branch and/or you have uncommitted changes."
        read -p "Are you sure you want to create a non-local build? y/[n]" yn
        case $yn in
            [Yy]* ) break;;
            [Nn]* ) exit 1;;
            * ) exit 1;;
        esac
    elif [ "$env_config" != "local" ]
    then
        echo "You cannot create a $env_config build while not on the main branch and/or with uncommitted changes."
        exit 1
    fi
else
    # Make sure, you are on the main branch
    current_branch=`git rev-parse --abbrev-ref HEAD`
    if [ $current_branch != "${main_branch_name}" ]
    then
        echo "Error:: Not on ${main_branch_name}, branch is $current_branch"
        exit 1
    fi

    # Update the branch
    git pull origin ${main_branch_name}

    # Make sure there are no uncommitted changes
    if [ -n "$(git status -s -uall)" ]
    then
        echo "Error:: You have uncommited changes"
        echo
        git status -uall
        exit 1
    fi
fi

# Build the current Version of this service image locally

version_next=$(git rev-parse --short HEAD)

for env in "${envs_to_build[@]}"; do
    image_tag="marvel2-frontend:$env-$version_next"
    image_tag_latest="marvel2-frontend:$env-latest"

    echo "..... Building $image_tag"

    # Build Docker image
    (
      set -x
      docker build ./ --tag "$image_tag" --tag "$image_tag_latest" --build-arg "env=$env"
    )
done
