#!/usr/bin/env bash

# https://dcos.io/docs/1.8/administration/installing/custom/advanced/
# https://dcos.io/docs/1.7/administration/installing/custom/advanced/

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

exhibitor_storage_backend=<%= node['dcos-grid']['bootstrap']['config']['exhibitor_storage_backend'] %>

usage() {
  echo 'Usage: node_upgrade.sh [-y] [-h] {master,agent,slave,agent_public,slave_public}'
  echo 'This script upgrades DC/OS master or agent 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))

if [ $# != 1 ]; then
  usage
  exit 1
else
  ROLE=$1
fi

case "$ROLE" in
  'master' | 'slave' | 'slave_public' )
    ;;
  # aliases
  'agent' | 'agent_public' )
    ROLE=${ROLE//agent/slave}
    ;;
  'public_agent' | 'public-agent' )
    ROLE='slave_public'
    ;;
  * )
    usage
    exit 1
    ;;
esac
echo "Node Role: $ROLE"

echo "This node will be upgraded as a $ROLE 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

if [ $ROLE = 'master' ]; then
  zk_mode=`echo stat | /opt/mesosphere/bin/toybox nc localhost 2181 | grep "Mode:"`
  echo "Zookeeper $zk_mode"

  if echo $zk_mode | grep 'leader'; then
    echo 'This node is Zookeeper leader. You should upgrade Zookeeper leader node at the end.'
    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
  fi
fi

# Upgrade
if [ ! -d /tmp/dcos ]; then
  CMD='mkdir /tmp/dcos'
  echo "Command: $CMD"
  $CMD
fi
CMD='cd /tmp/dcos'
echo "Command: $CMD"
$CMD

echo 'Downloading new dcos_install.sh ...'
CMD="$sudo curl -O <%= node['dcos-grid']['bootstrap']['config']['bootstrap_url'] %>/dcos_install.sh"
echo "Command: $CMD"
$CMD

echo 'Uninstalling pkgpanda ...'
CMD="$sudo -i /opt/mesosphere/bin/pkgpanda uninstall"
echo "Command: $CMD"
$CMD

echo 'Removing data directory ...'
CMD="$sudo rm -rf /opt/mesosphere /etc/mesosphere"
echo "Command: $CMD"
$CMD

case "$ROLE" in
  'master' )
    if [ $exhibitor_storage_backend != 'static' ]; then
      CMD="$sudo useradd --system --home-dir /opt/mesosphere --shell /sbin/nologin -c 'DCOS System User' dcos_exhibitor; $sudo chown -R dcos_exhibitor /var/lib/zookeeper"
      echo "Command: $CMD"
      $CMD
    fi
    ;;
  'slave' | 'slave_public' )
<< "#__CO__"
    # ???: If you have not made explicit disk size reservations, you must create
    #  a placeholder for the disk reservation file. This prevents the installer
    #  from building a new disk reservation file that might conflict with your
    #  stored agent metadata:
    #    $ sudo mkdir -p /var/lib/dcos
    #    $ sudo touch /var/lib/dcos/mesos-resources
    CMD="$sudo mkdir -p /var/lib/dcos; $sudo touch /var/lib/dcos/mesos-resources"
    echo "Command: $CMD"
    $CMD
#__CO__
    ;;
  * )
    ;;
esac

echo 'Waiting for releasing of service ports ...'
sleep 60s

echo "Installing DC/OS $ROLE node ..."
CMD="$sudo bash dcos_install.sh $ROLE"
echo "Command: $CMD"
$CMD

case "$ROLE" in
  'master' )
    cat << EOM
Validate the upgrade
  - Monitor the Exhibitor UI to confirm that the Master rejoins the ZooKeeper
    quorum successfully (the status indicator will turn green). The Exhibitor
    UI is available at http://<dcos_master>:8181/.
  - Verify that curl http://<dcos_master_private_ip>:5050/metrics/snapshot has
    the metric registrar/log/recovered with a value of 1.
  - Verify that http://<dcos_master>/mesos indicates that the upgraded master
    is running Mesos upgraded version.
EOM
    ;;
  'slave' | 'slave_public' )
    cat << EOM
Validate the upgrade
  - Verify that curl http://<dcos_agent_private_ip>:5051/metrics/snapshot has
    the metric slave/registered with a value of 1.
  - Monitor the Mesos UI to verify that the upgraded node rejoins the DC/OS
    cluster and that tasks are reconciled (http://<dcos_master>/mesos).
EOM
    ;;
  * )
    ;;
esac
