#!/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`

usage() {
  echo 'Usage: node_setup.sh [-y] [-h] {master,agent,slave,agent_public,slave_public}'
  echo 'This script sets up 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 set up as a $ROLE node."
while true; do
  if [ "$always_yes" = 1 ]; then
    break
  fi
  echo -n 'Continue the setup? [y/N]: '
  read answer
  case $answer in
    'y' | 'yes' )
      break
      ;;
    '' | 'n' | 'no' )
      echo 'Setup was aborted by user.'
      exit 0
      ;;
    * )
      ;;
  esac
done

# Setup
if [ -d /opt/mesosphere ]; then
  echo -e '[ERROR] DC/OS is already installed.'
  exit 1
fi

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

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

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

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