#!/usr/bin/env bash
#
# HELPER PURPOSE
#
# Uploads the compressed assets generated by apps using Page kit to S3
#
# This helper will be executed in place of the current deploy-hashed-assets
# command in n-heroku-tools for all apps that are using Page Kit.
#
# It uploads JavaScipt, CSS, sourcemaps and compressed files to the EU and US
# regions, making the assets available to our CDN layer.
#

# Set error handling
set -eu -o pipefail

# HELPER COMMANDS


SOURCE_FOLDER=${1:-"public"}
DESTINATION_FOLDER=${2:-"hashed-assets/uploads"}
DESTINATION_BUCKET_EU="ft-next-hashed-assets-prod"
DESTINATION_BUCKET_US="ft-next-hashed-assets-prod-us"

upload_file() {
	local FILE="$1"
	local BASENAME=$(basename $FILE)
	local DESTINATION_BUCKET="$2"
	local ENCODING="identity"
	local TYPE

	if [[ "$FILE" == *".gz" ]]; then
		ENCODING="gzip"
	elif [[ "$FILE" == *".br" ]]; then
		ENCODING="br"
	fi

	# the AWS CLI can guess content types but not the original type of compressed files
	# <https://github.com/aws/aws-cli/issues/3817>
	case "$FILE" in
		*".js"|*".js.gz"|*".js.br")
			TYPE="application/javascript"
			;;
		*".css"|*".css.gz"|*".css.br")
			TYPE="text/css"
			;;
		*".map")
			TYPE="application/octet-stream"
			;;
	esac

	aws s3 cp $FILE "s3://$DESTINATION_BUCKET/$DESTINATION_FOLDER/$BASENAME" \
		--cache-control=31536000 \
		--content-type="$TYPE; charset=utf-8" \
		--content-encoding="$ENCODING" \
		--acl="public-read"
}

upload_files() {
	local SOURCE_FILES=($(find $SOURCE_FOLDER/*.{js,css,gz,br,map} 2>/dev/null))

	for FILE in ${SOURCE_FILES[@]}; do
		# Uploading to both regions to remove the dependency on our AWS poller
		upload_file "$FILE" $DESTINATION_BUCKET_EU
		upload_file "$FILE" $DESTINATION_BUCKET_US
	done
}

upload_files
