#!/bin/bash
# -*- mode: sh; -*-
# vim: filetype=sh
set -eo pipefail

# This tool relies on the python package called `awslogs` (installed with `pip3 install awslogs`).

function usage {
	echo ${1}
	cat <<EOF
Usage: ${0} <app>/<comonent>
Usage: ${0} lambda <app>/<component>
EOF
	exit 1
}

if [ -z ${1} ]; then
	usage "Error: no app/component specified"
fi

if [ -z $(which awslogs) ]; then
	echo "Error: please install the python awslogs package with \`pip3 install awslogs\`"
	exit 1
fi

if [ ${1} == "lambda" ]; then
	if [ -z ${2} ]; then
		usage "Error: no app/component specified"
	fi

	fields=(${2//\// })

	if [ ${#fields[@]} -ne 2 ]; then
		usage "Error: wrong number of fields in the <app>/<component> part of the command"
	fi

	lambda_function_name=${fields[0]}-${fields[1]}
	
	exec awslogs get /aws/lambda/${lambda_function_name} ALL --watch
else
	files=$( awslogs groups | grep ${1} | grep 'docker' )
	for i in $files; do
		awslogs get ${i} ALL --watch &
	done
	
	trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT
	
	while [ 1 ]; do
		sleep 1
	done
fi
