#!/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

PROJECT_DIR=$1
IMG_VERSION=$2
DEPLOY_ENV=$3


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=(
        ["admin_gateway"]="dispatch_admin_gateway"
        ["robot_gateway"]="maestro_robot_gateway"
        ["mobile_gateway"]="maestro_mobile_gateway"
        ["dispatch_planner"]="dispatch_planner"
        ["stale_mission"]="stale_mission_daemon"
        ["robot"]="maestro_robot"
        ["robot_sims"]="maestro_robot_sims"
        ["robot_pairing"]="maestro_robot_pairing"
        ["trip"]="dispatch_trip"
        ["user"]="zoox_dispatch_user"
        ["session"]="zoox_dispatch_session"
        ["vitals"]="zoox_dispatch_vitals"
        ["geo"]="maestro_geo"
        ["mission_service"]="mission_service"
        ["route_smoother"]="route_smoother"
        ["predetermined_route"]="predetermined_route"
        ["vitals_daemon"]="robot_vitals_daemon"
        ["mission_assignment_daemon"]="mission_assignment_daemon"
        ["maestro_pairing_manager"]="maestro_pairing_manager"
        )

SVC_DEF=${dir_to_service["$PROJECT_DIR"]}
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/${PROJECT_DIR}
    docker push "$ecs_docker_registry:$IMG_VERSION"
}

bazel run "//infra/terraform/dispatch/tools:deploy" -- "${SVC_DEF}" --version "${IMG_VERSION}" "${DEPLOY_ENV}"
