#!/bin/sh
set -eu

_check() {
    host="$1"
    containers="$(until docker --context "$host" compose ps -q; do true; done)"
    # shellcheck disable=SC2086
    docker --context "$host" container inspect --format '{{ .State.Health.Status }}' $containers | grep -v '^healthy$'
}

_deploy() {
    host="$1"
    printf '\n\e[1;94m=== %s ====\e[0m\n\n' "Deploying to ${host}.shore.co.il" >&2
    export RUNNER_NAME="${host}.shore.co.il"
    until docker --context "$host" compose up --detach --remove-orphans ; do true; done
    for i in $(seq 12)
    do
        _check "$host" || break
        sleep 10
    done
    # shellcheck disable=SC2251
    ! _check "$host"
    unset RUNNER_NAME
}

if [ -z "${GITLAB_REGISTRATION_TOKEN:-}" ]
then
    GITLAB_REGISTRATION_TOKEN="$(ph show --field Password 'shore.co.il/GitLab runner registration token')" || \
        { echo "Failed to get the registration token from the Keepass database." >&2;
          echo "You can set the GITLAB_REGISTRATION_TOKEN environment variable instead." >&2;
          exit 1; }
fi


[ "$#" -eq '0' ] && "$0" ns4 host01 kodi

for i in "$@"
do
    case "$i" in
        ns4) export REGISTER_RUN_UNTAGGED="true"
            export BUILDS='/builds'
            _deploy ns4
            ;;
        kodi) export REGISTER_RUN_UNTAGGED="false"
            unset BUILDS
            _deploy kodi
            ;;
        host01) export REGISTER_RUN_UNTAGGED="false"
            unset BUILDS
            _deploy host01
            ;;
        all) "$0" ns4 host01 kodi ;;
        *) echo 'Unknown host.' >&2; exit 1;;
    esac
done
