#!/usr/bin/env bash
set -e
set -x

STACK_NAME=dkregistry
SERVICE_NAME=registry
APP_NAME=${STACK_NAME}_${SERVICE_NAME}

LOG=$(mktemp)

export DOCKER_HOST=${DOCKER_HOST:-'dkhost:2376'}

###
function deploy() {
  docker stack deploy \
    --with-registry-auth \
    -c docker-compose.yml \
    ${STACK_NAME}

  sleep 2
  docker stack ps ${STACK_NAME}

#  wait_for_completed
}

wait_for_completed() {
  #states supported: "rollback_completed", "updating", "completed"
  state=$(docker service inspect ${APP_NAME} | jq -r .[0].UpdateStatus.State)
  while [ "completed" != "$state" ]; do
    echo "$state"
    sleep 3
    state=$(docker service inspect ${APP_NAME} | jq -r .[0].UpdateStatus.State)
  done
  sleep 5
}

function deploy_test() {
  docker ps | grep ${APP_NAME}

  assertOK https dkregistry.xai-corp.net
}

function deploy_save() {
  echo "No image to save"
}

dc() {
  # shellcheck disable=SC2068
  docker-compose \
    -f docker-compose.yml \
    $@
}

function assertOK() {
  proto=$1
  domain=$2
  set -e
  echo -e "\033[94m${proto}://${domain}\033[39m"
  curl -IskH "Host: ${domain}" "${proto}://dkhost.xai-corp.net:5000" |
    tee "$LOG" | grep -P "HTTP\/2 200|200 OK|302 Found|403 Forbidden"
}

function trap_exit() {
  code=$?
  docker service ls | grep "${APP_NAME}" || echo "service not found"
  if [ $code -gt 0 ]; then
    echo
    cat "$LOG"
    rm "$LOG"
    echo -e "\033[31mFailed to deploy ${REMOTE_IMAGE} \033[39m"
    exit $code
  fi

  rm "$LOG"
  echo -e "\033[32mSuccess:\033[39m ${REMOTE_IMAGE} successfully deployed"
}
trap trap_exit EXIT

print_usage() {
  printf "Usage: %s: [-b] [-t] [-s] \n" "$0"
  echo -d deploy
  echo -t smoke tests
  echo -s tag as latest
  echo -h help
  exit 0
}

######
if [ -z "$1" ]; then
  deploy && deploy_test && deploy_save
  exit
fi

while getopts tdhs name; do
  case $name in
  d) deploy ;;
  t) deploy_test ;;
  s) deploy_save ;;
  *) print_usage ;;
  esac
done
