#!/bin/bash

set -eu
set -o pipefail

_base_file=$(basename $0)

if [[ ! -d ~/.dino/logs ]] || [[ ! -d ~/.dino/tokens ]]; then
  mkdir -vp ~/.dino/{logs,tokens}
else
  chmod 700 ~/.dino/{logs,tokens}
  chmod 600 ~/.dino/*/*
fi

_handle_task() {
  _env=''
  _brand=''
  _supported_brands=('bluehost')
  _region=''
  _supported_regions=('us-ashburn-1' 'us-phoenix-1')
  _task=''
  _purpose=''
  _job_id=''
  _verbose=''
  _DINO_URL=''

  # Use getopts to parse options.
  while getopts "e:b:t:j:r:dv" opt; do
    case "$opt" in
      d)
        set -x
	;;
      t)
        _task="$OPTARG"
        if [[ "${_task}" != 'instance-create' ]] && [[ "${_task}" != 'instance-status' ]]; then
          _help
        fi
        ;;
      j)
        _job_id="$OPTARG"
        ;;
      e)
        _mode="$OPTARG"
	if [[ "${_mode}" == 'dev' ]]; then
          if [[ -f ~/.dino/tokens/dev_jwt ]]; then
            source ~/.dino/tokens/dev_jwt
          else
  	    echo "Missing token ~/.dino/tokens/dev_jwt"
	    exit 1
	  fi
	  _DINO_URL='https://beta-dino.apps.provo1.endurancemb.com/jobs'
        elif [[ "${_mode}" == 'prod' ]]; then
          if [[ -f ~/.dino/tokens/prod_jwt ]]; then
            source ~/.dino/tokens/prod_jwt
          else
            echo "Missing token ~/.dino/tokens/dev_jwt"
	    exit 1
	  fi
          _DINO_URL='https://prod-dino.apps.provo1.endurancemb.com/jobs'
	  _purpose='userbox'
        else
          echo "Invalid env "${_mode}". Valid options are: (dev|prod)"
	  exit 1
        fi
        ;;
      b)
        _brand="$OPTARG"
	local _match=''
	for _b in "${_supported_brands[@]}"; do
          if [[ "${_brand}" == "${_b}" ]]; then
            _match=1
	    break
	  fi
        done
	if [[ "${_match}" -ne 1 ]]; then
          echo "Invalid brand ${_brand}. Supported brands: '${_supported_brands[@]}'"
	  exit 1
        fi
        ;;
      r)
        _region="$OPTARG"
        local _match=''
        for _r in "${_supported_regions[@]}"; do
          if [[ "${_region}" == "${_r}" ]]; then
            _match=1
            break
          fi
        done
        if [[ "${_match}" -ne 1 ]]; then
          echo "Invalid region ${_region}. Supported regions: '${_supported_regions[@]}'"
          exit 1
        fi
	;;
      v)
        _verbose=1
        ;;
     \?)
        echo "Invalid option: -$OPTARG" >&2
	_help
        ;;
      :)
        echo "Option -$OPTARG requires an argument." >&2
	_help
        ;;
    esac
  done

  if [[ -z "${_task}" ]] || [[ -z "${_mode}" ]]; then
    _help
  fi
  
  if [[ -z "${_DINO_JWT}" ]]; then
    echo "_DINO_JWT doesn't appear to be set, did you forget to export _DINO_JWT=<token> ?"
    exit 1
  fi

  # Perform the action based on the selected mode.  
  if [[ "${_task}" == 'instance-create' ]]; then
    if [[ -z "${_brand}" ]] || [[ -z "${_region}" ]]; then
      _help
    else
      _log_message "command: ${_base_file} $@"
      _instance_create
    fi
  else
    if [[ -z "${_job_id}" ]]; then
      _help
    fi
    _log_message "command: ${_base_file} $@" 
    _instance_status
  fi

  echo "Operation completed."
}

_log_message() {
    local _message="$@"
    local _timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    local _log_file=${_base_file}.log
    echo "[${_timestamp}] ${_message}" >> ~/.dino/logs/${_log_file}
}

_help() {
  echo "Usage: $0 -e <dev|prod> -b <brand> -r <region> -t <instance-create|instance-status> -j (required if task instance-status)" >&2
  echo "  -e: Environment (dev or prod)."
  echo "  -b: Brand to operate on. '${_supported_brands[@]}'"
  echo "  -r: Region to operate on. '${_supported_regions[@]}'"
  echo "  -t: Task to run."
  echo "  -j: Job ID for the task to check."
  exit 1
}

_instance_create() {
  _args="\"brand\":\"${_brand}\",\"region\":\"${_region}\",\"owner\":\"$(whoami)\",\"purpose\":\"${_purpose}\",\"final_port_timeout\":3600"
  if [[ "${_mode}" == 'dev' ]]; then
    _args+=",\"instance_config\":\"default\",\"auto_delete\":\"1h\""
  else
    _args+=",\"instance_config\":\"prod\",\"hal_watermark_enabled\":false"
  fi

  _job_output=$(curl -s -H "content-type:application/json" -H "authorization: bearer ${_DINO_JWT}" --data "{\"action\":\"oci.create_instance\",\"args\":{${_args}}}" "${_DINO_URL}")
  echo ${_job_output}
  _log_message "command_output: ${_job_output}"
}

_instance_status(){
  _job_data=$(curl -s -H "content-type:application/json" -H "authorization: bearer ${_DINO_JWT}" "${_DINO_URL}/${_job_id}")
  echo ${_job_data} | jq -r
  if [[ $(echo ${_job_data} | jq -r '.status') == 'errored' ]]; then
    echo "Provisioning failed"
    exit 1
  fi
  while [[ $(echo ${_job_data} | jq -r '.status') != 'completed' ]]; do
    if [[ ! -z ${_verbose} ]]; then
      clear
      echo ${_job_data} | jq -r
    else
      echo "Current stage: $(echo ${_job_data} | jq -r '.stage')"
    fi
    sleep 5
    _job_data=$(curl -s -H "content-type:application/json" -H "authorization: bearer ${_DINO_JWT}" "${_DINO_URL}/${_job_id}")
  done
}

_handle_task "$@"
