#!/usr/bin/env bash

# https://dcos.io/docs/1.8/administration/upgrading/
# https://dcos.io/docs/1.7/administration/upgrading/

PATH=.:/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:`dirname $0`

usage() {
  echo 'Usage: bootstrap_upgrade.sh [-y] [-h]'
  echo 'This script upgrades DC/OS bootstrap node.'
  echo
  echo "Options:"
  echo "  -h: this help."
  echo "  -y: always yes."
  echo
}

ARGS="$@"
# Validation
while getopts 'yh' OPT; do
  case $OPT in
    'y' )
      always_yes=1
      ;;
    'h' )
      usage
      exit 0
      ;;
    '?' )
      usage
      exit 1
      ;;
  esac
done

shift $((OPTIND - 1))

echo 'This node will be upgraded as a Bootstrap node.'
while true; do
  if [ "$always_yes" = 1 ]; then
    break
  fi
  echo -n 'Continue the upgrade? [y/N]: '
  read answer
  case $answer in
    'y' | 'yes' )
      break
      ;;
    '' | 'n' | 'no' )
      echo 'Upgrade was aborted by user.'
      exit 0
      ;;
    * )
      ;;
  esac
done

user=`whoami`
sudo='sudo'
if [ $user = 'root' ]; then
  sudo=''
fi

# Upgrade
CMD='cd <%= File.dirname(node['dcos-grid']['bootstrap']['genconf_dir']) %>'
echo "- Command: $CMD"
$CMD

echo 'Back up the current installation script ...'
CMD="$sudo mv ./genconf/serve ./genconf/serve-`date '+%Y%m%d_%H%M%S'`"
echo "- Command: $CMD"
$CMD

echo 'Downloading new DC/OS release ...'
CMD="$sudo curl -O <%= node['dcos-grid']['dcos_release_url'] %>"
echo "- Command: $CMD"
$CMD

echo 'Generating new DC/OS configurations ...'
CMD="$sudo bash dcos_generate_config.sh"
echo "- Command: $CMD"
$CMD

echo 'Back up the generated dcos_install.sh script ...'
CMD="$sudo cp ./genconf/serve/dcos_install.sh ./genconf/serve/dcos_install.sh.pkg-dist"
echo "- Command: $CMD"
$CMD

echo 'Disable Docker restarts in dcos_install.sh'
CMD="$sudo sed -i -e 's/systemctl restart systemd-journald//g' -e 's/systemctl restart docker//g' genconf/serve/dcos_install.sh"
echo "- Command: $CMD"
eval $CMD

port=<%= node['dcos-grid']['bootstrap']['port'] %>
if $sudo docker ps | grep "${port}->80"; then
  echo 'Docker container for the bootstrap service is already running.'
else
  echo 'Launching Docker container for the bootstrap service ...'
  CMD="$sudo docker run -d -p ${port}:80 -v $PWD/genconf/serve:/usr/share/nginx/html:ro nginx"
  echo "- Command: $CMD"
  $CMD
fi

cat << EOM
Please execute the following command in preparation to get new node in on the cluster
after the cluster upgrade finished.
  $ cd <%= File.dirname(node['dcos-grid']['bootstrap']['genconf_dir']) %>
  $ sudo mv ./genconf/serve/dcos_install{,4upgrade}.sh
  $ sudo mv ./genconf/serve/dcos_install.sh{.pkg-dist,}
EOM
