#!/bin/bash

export TZ="UTC"

usage() {
  echo "$0 - script to stop the specified EC2 instance ID

Usage:

  $0 <instance_id>

Supported OPTIONS:

  --help                    display this help text
  --instance-id <ID>        operate on specified instance ID
  --region <REGION>         specify region that should be used
                            (if unset defaults to the eu-west-1 zone)
  --terminate               terminate instead of just stopping the instance
"
}

CMDLINE_OPTS=help,instance-id:,region:,terminate

_opt_temp=$(getopt --name "$0" -o +bch --long ${CMDLINE_OPTS} -- "$@")
if [ $? -ne 0 ]; then
  echo "Try '$0 --help' for more information." >& 2
  exit 1
fi
eval set -- "${_opt_temp}"

_opt_terminate=false

while :; do
  case "$1" in
  --help)
    usage ; exit 0;
    ;;
  --instance-id)
    shift; INSTANCE_ID="$1"
    ;;
  --region)
    shift; AWS_REGION="$1"
    ;;
  --terminate)
    _opt_terminate=true
    ;;
  --)
    shift; break
    ;;
  *)
    echo "Internal getopt error! $1" >&2
    exit 1
    ;;
  esac
  shift
done

# if unset set sane defaults
[ -n "${AWS_REGION}" ] || AWS_REGION="eu-west-1"

check4progs(){
  local RC=''
  for arg in "$@" ; do
    which "${arg}" >/dev/null 2>&1 || RC="${arg}"
  done
  if [ -n "${RC}" ] ; then
    echo "${RC} not found/executable" >&2
    return 1
  fi
}

if ! check4progs aws ; then
  echo "Required tool aws not found, forgot to install awscli?" >&2
  exit 1
fi

if [ -z "${INSTANCE_ID}" ] ; then
  usage >&2
  exit 1
fi

if ${_opt_terminate} ; then
  echo "Terminating instance ID ${INSTANCE_ID} (as requested via --terminate)"
  aws ec2 terminate-instances --region "${AWS_REGION}" --instance-ids "${INSTANCE_ID}"
  if [ $? -ne 0 ] ; then
    echo "Noticed problem when trying to terminate instance with ID ${INSTANCE_ID}" >&2
    exit 1
  fi
else
  echo "Stopping Instance ID ${INSTANCE_ID}"
  aws ec2 stop-instances --region "${AWS_REGION}" --instance-ids "${INSTANCE_ID}"
  if [ $? -ne 0 ] ; then
    echo "Noticed problem when trying to stop instance with ID ${INSTANCE_ID}" >&2
    exit 1
  fi
fi