#!/bin/sh
set -eu

_docker_compose() {
    docker-compose "$@" 2>&1 | sed '/^  File /,+1d'
}

_check() {
    containers="$(until _docker_compose ps -q; do true; done)"
    # shellcheck disable=SC2086
    docker 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" >&2
    localsocket="$HOME/.ssh/docker_$host.sock"
    forward "$host" "$localsocket:/var/run/docker.sock"
    export DOCKER_HOST="unix://$localsocket"
    export RUNNER_NAME="$host"
    until _docker_compose up --detach --remove-orphans ; do true; done
    # shellcheck disable=SC2034
    for i in $(seq 12)
    do
        # shellcheck disable=SC2046
        _check || break
        sleep 10
    done
    # shellcheck disable=SC2046
    ! _check
    unset DOCKER_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.shore.co.il
            ;;
        kodi) export REGISTER_RUN_UNTAGGED="false"
            unset BUILDS
            _deploy kodi.shore.co.il
            ;;
        host01) export REGISTER_RUN_UNTAGGED="false"
            unset BUILDS
            _deploy host01.shore.co.il
            ;;
        all) "$0" ns4 host01 kodi ;;
        *) echo 'Unknown host.' >&2; exit 1;;
    esac
done