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

usage() {
	echo "Usage: $0 -s <S3 bucket> -a <Lambda alias>" 1>&2
	exit 1
}

while getopts ":s:a:" o; do
	case "${o}" in
		s)
			BUCKET=${OPTARG}
			;;
    a) ALIAS=${OPTARG}
      ;;
		*)
			usage
			;;
	esac
done

if [ -z "${BUCKET}" ] || [ -z "${ALIAS}" ]; then
	usage
fi

LAMBDA_NAME=channelViewer

STATIC_CACHE_VALUE='public, max-age=1296000'

# Sources
JS_SOURCE=dist/static/javascript
CSS_SOURCE=dist/static/css
IMAGE_SOURCE=static/images
LAMBDA_SOURCE=fileb://dist/lambda/lambda.zip
NOT_FOUND_SOURCE=dist/static/404.html
INTERNAL_ERROR_SOURCE=dist/static/500.html

# Destinations
JS_DESTINATION=static/javascript
CSS_DESTINATION=static/css
IMAGE_DESTINATION=static/images
NOT_FOUND_DESTINATION=static/404.html
INTERNAL_ERROR_DESTINATION=static/500.html

# Upload the JS
aws s3 sync "$JS_SOURCE/" "s3://${BUCKET}/${JS_DESTINATION}" --no-follow-symlinks --cache-control "${STATIC_CACHE_VALUE}"
# Upload the CSS - Commented out since we don't actually need this at the moment
# aws s3 sync "$CSS_SOURCE/" "s3://$BUCKET/$CSS_DESTINATION" --no-follow-symlinks --cache-control $STATIC_CACHE_VALUE
# Upload the images
aws s3 sync "$IMAGE_SOURCE/" "s3://${BUCKET}/${IMAGE_DESTINATION}" --no-follow-symlinks --cache-control "${STATIC_CACHE_VALUE}"
# Upload the static 404 & 500
aws s3 cp "${NOT_FOUND_SOURCE}" "s3://${BUCKET}/${NOT_FOUND_DESTINATION}" --cache-control "${STATIC_CACHE_VALUE}"
aws s3 cp "${INTERNAL_ERROR_SOURCE}" "s3://${BUCKET}/${INTERNAL_ERROR_DESTINATION}" --cache-control "${STATIC_CACHE_VALUE}"

# Upload the lambda
# Create new version of lambda based on branch name
SHA=$(aws lambda update-function-code --output text --query CodeSha256 --function-name ${LAMBDA_NAME} --zip-file ${LAMBDA_SOURCE})
echo SHA is $SHA
VERSION=$(aws lambda publish-version --output text --query Version --function-name ${LAMBDA_NAME} --code-sha-256 ${SHA})
echo VERSION is $VERSION
aws lambda update-alias --function-name ${LAMBDA_NAME} --name ${ALIAS} --function-version $VERSION
echo $LAMBDA_NAME ${ALIAS} alias updated
