#!/bin/bash

set -e

REPO=spotify/helios-solo
HELIOS_IMAGE=$REPO:latest

function get_helios_version() {
  docker run --rm --entrypoint bash $HELIOS_IMAGE \
    -c "ls *.jar | cut -d- -f3"
}

function get_cli_version() {
  if type -p helios >/dev/null; then
    helios --version | grep 'Helios CLI' | grep -oe '[0-9\.]\+'
  fi
}

orig_version=$(get_helios_version)
echo "Currently using Helios v$orig_version"
echo

if [ ! -z "$1" ]; then
  requested_version="$1"
  if [ "$orig_version" == "$requested_version" ]; then
    echo "Already at v$requested_version"
    exit 0
  fi

  echo "Switching to $requested_version"
  docker pull "$REPO:$requested_version"

  client_version=$(docker version --format '{{.Client.Version}}')
  cv_arr=( ${client_version//./ } )  # replace periods and split into array
  # Docker 1.12+ doesn't have the -f switch
  if [ "${cv_arr[1]}" -ge "12" ]; then
      docker tag "$REPO:$requested_version" "$REPO:latest"
  else
      docker tag -f "$REPO:$requested_version" "$REPO:latest"
  fi
  echo

  new_version=$(get_helios_version)

  if [ "$requested_version" == "latest" ] && [ "$new_version" == "$orig_version" ]; then
    echo "Already at latest version (v$new_version)."
    exit 0
  fi

  echo "Switched to v$new_version. To use it, please restart helios-solo:"
  echo
  echo '    helios-restart'
  echo
  echo 'Note that this will destroy all Helios jobs on helios-solo.'

  cli_version=$(get_cli_version)
  if [ ! -z "$cli_version" ] && [ "$cli_version" != "$new_version" ]; then
    echo
    echo "WARNING: Your Helios CLI version is different (v$cli_version)."
    echo 'Upgrade or downgrade to the correct CLI version if you have issues.'
    echo 'This is usually accomplished with `brew` or `apt-get`.'
  fi
else
  echo 'Upgrade to the latest version with:'
  echo
  echo '    helios-use latest'
  echo
  echo 'You can also switch to a specific version with:'
  echo
  echo '    helios-use <version>'
  echo

  set +e
  echo 'Fetching list of available versions...'
  echo
  versions=$(curl -sSL https://index.docker.io/v1/repositories/$REPO/tags \
    | jq  --raw-output '.[].name')
  versions_ok=$?
  set -e

    if [[ ! "$versions" =~ 'latest' ]]; then
        # if "latest" isn't an available version, something went wrong
        versions_ok=1
    fi

  if [ $versions_ok -ne 0 ]; then
    echo 'Error fetching available versions.'
  else
    echo 'Available versions:'
    for v in $versions; do
      echo "* $v"
    done
  fi
  echo
fi
