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

LOCAL_IMAGE=xaicorp/nextcloud
TAG=${NC_VERSION}.0-${BUILD_NUMBER:-dev}
REMOTE_IMAGE=dkregistry.xai-corp.net:5000/${LOCAL_IMAGE}:${TAG}
STACK_NAME=xaibox
SERVICE_NAME=app
APP_NAME=${STACK_NAME}_${SERVICE_NAME}

LOG=$(mktemp)

#export LOCAL_IMAGE
export REMOTE_IMAGE
#export TAG

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

###

function rollback() {
#  docker service inspect ${APP_NAME}
  docker service update --rollback "${APP_NAME}"

  wait_for_completed
#  docker service scale "${APP_NAME}=2"
}

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

function rollback_test() {
  docker service ps --filter "desired-state=Healthy" ${APP_NAME}

  docker ps | grep "${APP_NAME}"
}

function rollback_save() {
  echo TODO
}


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

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

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

######
if [ -z "$1" ]; then
  rollback && rollback_test && rollback_save
  exit
fi

while getopts tdhs name
do
    case $name in
    d)    rollback;;
    t)    rollback_test;;
    s)    rollback_save;;
    *)    print_usage;;
    esac
done
