#!/usr/bin/env bash
set -e

# Default Values
MONIKER=${1:-"$DOCKER_IP"}
shift
GREEN='\033[0;32m'
NO_COLOR='\033[0m'

confirm_destroy() {
    echo -e "Destroy dock with the following values?"
    echo -e "Instance ID: ${GREEN}${2:-none}${NO_COLOR}"
    echo -e "Config Dir: ${GREEN}${1:-none}${NO_COLOR}"
    read -e -p "Type enter to Cancel, h for Help, y to Destroy: " RESPONSE

    if [ "$RESPONSE" == "h" ]; then print_help; fi

}

print_help() {
    echo "Destroy dock - Help"
    echo
    echo "Description"
    echo "  This script uses the aws cli to terminate an existing ec2 dock instance."
    echo "  Either the dock ip or the moniker must be provided"
    echo ""
    echo "  Options:"
    echo "    -f   Disable termination protection and then terminate" 
    echo
    echo "Usage"
    echo "  $ destroy-dock moniker|ip <-f>"
    echo

    exit 0
}

# Parse command line arguments in any order
disable_terminate_protection=false
while getopts 'hf' flag; do    # if a character is followed by a colon, that argument is expected to have an argument.
  case "${flag}" in
    h) hflag='true';;
    f) disable_terminate_protection=true;;
    *) error "Unexpected option ${flag}" ;;
  esac
done

# Look up IP from moniker
FOUND_MONIKER=false
for f in $HOME/.docker/*; do
    if [ -d $f ] && [ -f $f/connection_config.txt ]; then
      while read -r line; do declare $line; done < "$f/connection_config.txt"
      if [[ $DOCK_MONIKER = $MONIKER || $DOCK_IP = $MONIKER ]]; then
        FOUND_MONIKER=true
        break
      fi
    fi
done

if [ $FOUND_MONIKER = false ]; then
  echo "Can't find dock configuration for $MONIKER"
  exit -1
fi


get_instance_id() {
    aws ec2 describe-instances \
        --filters Name=private-ip-address,Values="$1" \
        --query 'Reservations[*].Instances[*].InstanceId' --output text
}

# destroy dock
INSTANCE_ID=$(get_instance_id $DOCK_IP)

# Confirmation
confirm_destroy "$f" "$INSTANCE_ID"
if [ "$RESPONSE" != "y" ] && [ "$RESPONSE" != "h" ]; then
    echo "Canceled"
    exit 0
fi

if [ -n "$INSTANCE_ID" ]; then
  if ${disable_terminate_protection}; then
    for I in $INSTANCE_ID; do
      aws ec2 modify-instance-attribute --no-disable-api-termination --instance-id "$I"
    done
  fi
  aws ec2 terminate-instances --instance-ids "${INSTANCE_ID}" --output text
fi

if [ -n "$f" ]; then
    rm -rf $f
fi

