#!/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: bootstrap_setup.sh [-y] [-h]'
  echo 'This script sets up 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 set up as a Bootstrap 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

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

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

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

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

echo 'Launching Docker container for the bootstrap service ...'
CMD="$sudo docker run -d -p <%= node['dcos-grid']['bootstrap']['port'] %>:80 -v $PWD/genconf/serve:/usr/share/nginx/html:ro nginx"
echo "- Command: $CMD"
$CMD
