#!/usr/bin/env bash

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

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

echo '[WARN] DC/OS does NOT support uninstall yet!'
echo 'See https://dcos.io/docs/1.8/administration/installing/custom/uninstall/'

usage() {
  echo 'Usage: uninstall.sh [-y] [-h]'
  echo 'This script uninstalls DC/OS.'
  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 'DC/OS on this node will be uninstalled.'
while true; do
  if [ "$always_yes" = 1 ]; then
    break
  fi
  echo -n 'Continue the uninstall? [y/N]: '
  read answer
  case $answer in
    'y' | 'yes' )
      break
      ;;
    '' | 'n' | 'no' )
      echo 'Uninstall was aborted by user.'
      exit 0
      ;;
    * )
      ;;
  esac
done

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

install_dir=<%= File.dirname(node['dcos-grid']['bootstrap']['genconf_dir']) %>

# for Bootstrap node
if ls $install_dir | grep 'dcos-genconf.*.tar'; then
  CMD="$sudo rm ${install_dir}/dcos-genconf.*.tar"
  echo "Command: $CMD"
  $CMD
fi

if ls $install_dir | grep dcos_generate_config.sh; then
  CMD="$sudo rm ${install_dir}/dcos_generate_config.sh"
  echo "Command: $CMD"
  $CMD
fi

# for Master and Agent nodes
pkgpanda=/opt/mesosphere/bin/pkgpanda
if [ -e "$pkgpanda" ]; then
  echo 'Uninstalling DC/OS packages...'
  CMD="$sudo -i $pkgpanda uninstall"
  echo "Command: $CMD"
  $CMD
fi

if [ -e /opt/mesosphere ]; then
  echo 'Remove /opt/mesosphere and /etc/mesosphere ...'
  CMD="$sudo rm -rf /opt/mesosphere /etc/mesosphere"
  echo "Command: $CMD"
  $CMD
fi

if [ -e /tmp/dcos ]; then
  echo 'Remove /tmp/dcos ...'
  CMD="$sudo rm -rf /tmp/dcos"
  echo "Command: $CMD"
  $CMD
fi

echo 'Uninstalled DC/OS successfully.'
