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

USAGE="\
Pushes latest built image to the registry.
Usage:
  ./img_push.sh (-e|--env <environment>)
  Options:
    -e|--env <environment>  Build environment image to push. Default: dev (dev|test|prod|all)"

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

env_config="dev"

while (( "$#" )); do
    case $1 in
        -h|--help)
            echo "$USAGE"
            exit 1
            ;;
        -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

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"
  remote="sim.docker.zooxlabs.com"

  echo Pushing frontend version $version_next

  # Tag and push Docker image
  # Prerequisite: docker login sim.docker.zooxlabs.com
  (
    set -x
    docker tag $image_tag "$remote/$image_tag"
    docker tag $image_tag "$remote/$image_tag_latest"
    docker push "$remote/$image_tag"
    docker push "$remote/$image_tag_latest"
  )
  echo Pushed frontend image, version $version_next
done
