#!/usr/bin/env bash

# NAME
#    build_and_deploy_service

#DESCRIPTION
#    build service locally, push to remote docker registry, and deploy to ECS

#PARAMS
#    PROJECT_DIR: project directory name                    e.g,. mobile_gateway
#    DEPLOY_ENV:  deployment env                            e.g,. alpha
#    IMG_VERSION: deployment version                        e.g,. 1.0.0

#    If deployment version is not specified, use the SHA of current git commit as deployment version.
set -e

IMG_VERSION=$1
DEPLOY_ENV=$2

GIT_SHA=$(git rev-parse HEAD)

# validate env
declare -A DEPLOY_ENVS=(
 ['dev']='dev'  ['alpha']='alpha'  ['stage']='stage'  ['beta']='beta' ['zip']='zip'
)
if [ -z ${DEPLOY_ENVS["$DEPLOY_ENV"]} ]
    then
        echo "invalid env"
        exit 1
fi

if [ -z ${IMG_VERSION} ]
    then
        IMG_VERSION=$GIT_SHA
fi

declare -a dir_to_service
dir_to_service+=("dispatch_planner|dispatch_planner")
dir_to_service+=("stale_mission|stale_mission_daemon")
dir_to_service+=("robot|maestro_robot")
dir_to_service+=("robot_sims|maestro_robot_sims")
dir_to_service+=("robot_pairing|maestro_robot_pairing")
dir_to_service+=("trip|dispatch_trip")
dir_to_service+=("user|zoox_dispatch_user")
dir_to_service+=("session|zoox_dispatch_session")
dir_to_service+=("vitals|zoox_dispatch_vitals")
dir_to_service+=("geo|maestro_geo")
dir_to_service+=("mission_service|mission_service")
dir_to_service+=("route_smoother|route_smoother")
dir_to_service+=("predetermined_route|predetermined_route")
dir_to_service+=("vitals_daemon|robot_vitals_daemon")
dir_to_service+=("mission_assignment_daemon|mission_assignment_daemon")
dir_to_service+=("maestro_pairing_manager|maestro_pairing_manager")
dir_to_service+=("admin_gateway|dispatch_admin_gateway")
dir_to_service+=("robot_gateway|maestro_robot_gateway")
dir_to_service+=("mobile_gateway|maestro_mobile_gateway")


for i in "${dir_to_service[@]}"
do
  SVC_DIR=${i%|*}
  SVC_DEF=${i#*|}
  eks_docker_registry="maestro.docker.zooxlabs.com/$SVC_DEF"
  ecs_docker_registry="docker-registry.zooxlabs.com/$SVC_DEF"

  docker pull "$ecs_docker_registry:$IMG_VERSION" || {
    echo "Unable to find docker image in remote registry, building from local directory"
    docker build -t "$eks_docker_registry:$IMG_VERSION" -t "$ecs_docker_registry:$IMG_VERSION" ${ZOOX_WORKSPACE_ROOT}/dispatch/${SVC_DIR}
    docker push "$ecs_docker_registry:$IMG_VERSION"
  }
  bazel run "//infra/terraform/dispatch/tools:deploy" -- "${SVC_DEF}" --version "${IMG_VERSION}" "${DEPLOY_ENV}" --auto-approve &
done




