#!/bin/bash

# Default Values
AMI_ID="ami-0526fc892fc43ac33"
USERNAME="$(aws-whoami)"
INSTANCE_NAME="${USERNAME}-dock"
INSTANCE_TYPE="m5.xlarge"
SUBNET_ID="subnet-0cf3c97675ecb8e82"
MONIKER=

GREEN='\033[0;32m'
NO_COLOR='\033[0m'

ensure_dependencies () {
    if [ -z $(which register-dock) ]; then
        echo -e "Unable to find required dependencies from docker-utils, something is amiss in your dockerutils installation. Consider updating:"
        echo -e "  pip install -U dockerutils"
        exit 1
    fi
}

confirm_create () {
    if [ -z "$1" ]; then
        echo -e "Create dock with the following values?"
        echo -e "Instance type: ${GREEN}${INSTANCE_TYPE}${NO_COLOR}"
        echo -e "Name: ${GREEN}${INSTANCE_NAME}${NO_COLOR}"
        read -e -p "Type enter to Cancel, h for Help, y to Create: " RESPONSE
    fi

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

print_help () {
    echo "Create dock - Help"
    echo "Description"
    echo "  This script uses the aws cli to create a new ec2 dock instance from the latest AMI."
    echo "  If no options are passed into the script, it will prompt with defaults."
    echo "  The register-dock script is run automatically after the instance is ready."
    echo
    echo "Usage"
    echo "  $ aws-create-dock [options]"
    echo
    echo "Options"
    echo -e "\n -n dock-name\n    Specify a name for this dock with this format: my-dock-name"
    echo "    If dock-name is not specified, the name defaults to \"${INSTANCE_NAME}\""
    echo -e "\n -m moniker\n    The 'dock' name to use when connecting to the instance. (default is unset, use IP address)"
    echo -e "\n -i instance-type\n    The default instance type is m5.xlarge (no GPU).\n    Other options include p2.xlarge (GPU), m5.2xlarge, etc."
    echo -e "\n -a ami-id\n    The ami to use for the instance (default is ami-0526fc892fc43ac33)"
    echo -e "\n -s subnet-id\n    The subnet-id to use for the instance (default is subnet-0cf3c97675ecb8e82)"
    echo -e "\n -h help\n    This help"
    exit 0
}

get_private_ip() {
    aws ec2 describe-instances \
        --filters Name=instance-id,Values="$1" \
        --query 'Reservations[*].Instances[*].PrivateIpAddress' --output text
}


# Parse command line arguments in any order
nflag=''    # dock name flag
iflag=''    # instance type
aflag=''    # ami flag
sflag=''    # subnet flag
mflag=''    # moniker flag
while getopts 'hn:i:' flag; do    # if a character is followed by a colon, that argument is expected to have an argument.
  case "${flag}" in
    h) hflag='true';;
    n) nflag='true'; INSTANCE_NAME="${OPTARG}" ;;
    i) iflag='true'; INSTANCE_TYPE="${OPTARG}" ;;
    a) aflag='true'; AMI_ID="${OPTARG}" ;;
    s) sflag='true'; SUBNET_ID="${OPTARG}" ;;
    m) mflag='true'; MONIKER="${OPTARG}" ;;
    *) error "Unexpected option ${flag}" ;;
  esac
done

# ensure required dependencies met
ensure_dependencies

# Help
if [ ! -z "$hflag" ] || [ "$RESPONSE" == "h" ]; then
    print_help
fi


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


# Create dock
INSTANCE_ID=$(aws ec2 run-instances \
    --subnet-id ${SUBNET_ID} \
    --image-id $AMI_ID \
    --instance-type "${INSTANCE_TYPE}" \
    --block-device-mappings "DeviceName='/dev/sda1',Ebs={VolumeSize=100,VolumeType='gp2'}" \
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${INSTANCE_NAME}},\
        {Key=os,Value=Ubuntu},{Key=os_version,Value=16.04.3},{Key=app_type,Value=model},\
        {Key=business_unit,Value=\"Archiving & Governance\"},{Key=component,Value=\"ec2 instance\"},\
        {Key=product,Value=\"Resero Development\"},{Key=support_level,Value=dev},\
        {Key=created_by,Value=${USERNAME}}]" \
    --iam-instance-profile Name=lanista-app \
    --key-name resero-staging \
    --security-group-ids "sg-b93e0dc2" "sg-1bd90461" "sg-213eb35a" "sg-a5ac61de" \
    | grep InstanceId | awk -F '"' '{print $4}' \
    )

if [ ! -z "$INSTANCE_ID" ]; then
    echo "Creating instance id: $INSTANCE_ID"
    echo "Waiting for instance to start..."
    aws ec2 wait instance-running --instance-ids $INSTANCE_ID

    IP_ADDRESS=$(get_private_ip $INSTANCE_ID)

    if [ $(echo $IP_ADDRESS | grep -c -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}') == 1 ]; then
        echo 'Registering secure remote docker api'
        register-dock ubuntu $IP_ADDRESS
    fi

    echo "New EC2 instance available to dock at $IP_ADDRESS"
    echo "try these commands:"
    echo " $ source dock $IP_ADDRESS"
    echo " $ castoff"
    echo " $ ssh-add -K ~/.ssh/private-key-name"
    echo " $ ssh ubuntu@$IP_ADDRESS"
else
    echo "Failed to create instance."
fi