#!/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] [-W] [-h]'
  echo 'This script sets up DC/OS bootstrap node.'
  echo
  echo "Options:"
  echo "  -h: this help."
  echo "  -y: always yes."
  echo "  -W: why-run mode."
  echo
}

execute() {
  CMD=$1
  echo "  - Command: $CMD"
  [ "$why_run" = 1 ] || eval $CMD
}

ARGS="$@"
# Validation
while getopts 'yWh' OPT; do
  case $OPT in
    'y' )
      always_yes=1
      ;;
    'W' )
      why_run=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
  [ "$always_yes" = 1 ] && break

  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

sudo='sudo'
[ `whoami` = 'root' ] && sudo=''

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

execute "cd $install_dir" 

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

echo 'Generating DC/OS configurations ...'
execute "$sudo bash dcos_generate_config.sh"

echo 'Launching Docker container for the bootstrap service ...'
execute "$sudo docker run -d -p ${port}:80 -v $PWD/genconf/serve:/usr/share/nginx/html:ro nginx"
