#!/bin/bash
set -o pipefail

CMD=${1}
SUB=${2}
OPTS=${3:-""}

function usage() {
	local err=${1}
	echo "Error: ${err}"
	echo "Usage: ${0} <cmd> <sub cmd> [opts]"
	echo ""
	echo "Commands: "
	echo "	list <sub cmd>"
	echo "		regions - lists regions"
	echo "		elb - lists elbs"
	echo "		instances <appname>/<componentname>"
	echo "		asg"
	exit 1
}

if [ -z ${SUB} ]; then
	usage "no sub cmd provided"
fi

AWSFILTER=""

if [ ${CMD} = "list" ]; then
	case ${2} in
		regions)
			AWSCMD="ec2 describe-regions"
			AWSQRY="Regions[*].[RegionName]"
			;;
		elb)
			AWSCMD="elb describe-load-balancers"
			AWSQRY="LoadBalancerDescriptions[*].[DNSName]"
			;;
		instances)
			if [ -z ${OPTS} ]; then
				# maintain the old output format not possible without dropping jq
				aws ec2 describe-instances | jq '.Reservations[].Instances[] | select (.State.Name == "running") | select (.InstanceId != null) | select (.Tags != null) | [.InstanceId, .Tags[].Value] | join(", ")' | sed -e 's/"//g'
				exit $?
			fi

			app=$(echo ${OPTS} | cut -d '/' -f1 )
			component=$(echo ${OPTS} | cut -d '/' -f2)

			if [ -z ${app} -o -z ${component} ]; then
				usage "invalid opts passed to list instances: app(${app}) component(${component})"
			fi

			AWSCMD="ec2 describe-instances"
			AWSQRY="Reservations[*].Instances[*].[InstanceId]"
			AWSFILTER="Name=instance-state-name,Values=running Name=tag:twitch:ds:app:name,Values=${app} Name=tag:twitch:ds:app:component_name,Values=${component}"
			;;
		asg)
			AWSCMD="autoscaling describe-auto-scaling-groups"
			AWSQRY="AutoScalingGroups[*].[AutoScalingGroupName]"
			;;
		versions)
			aws autoscaling describe-auto-scaling-groups | \
				jq '.AutoScalingGroups[] |
					select(.DesiredCapacity > 0) | 
					[ (.Tags | from_entries | .["twitch:ds:app:name"], .["twitch:ds:app:component_name"], .["twitch:ds:git_version"]), .AutoScalingGroupName ] | 
					join (" ")' | \
				sed -e 's/"//g' | \
				sort
			exit $?
			;;

	esac
fi

if [ -z "${AWSCMD}" ]; then
	usage "Unknown cmd (${CMD}) or subcmd (${SUB})"
fi

if [ ! -z "${AWSFILTER}" ]; then
	AWSFILTER="--filters ${AWSFILTER}"
fi

aws ${AWSCMD} --query ${AWSQRY} ${AWSFILTER} --output text
