#!/bin/bash

# Note: This script is designed to be run inside CI builds

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$DIR/.common.sh"

echo -e "${BLUE}❯ ${CYAN}Uploading docs in: ${YELLOW}$1${RESET}"

cd "$1" || exit 1
ALL_FILES=$(find . -follow)

for FILE in $ALL_FILES
do
	# remove preceeding ./
	FILE=$(echo "$FILE" | sed -E "s/\.\///g")
	echo '======================================='
	echo "FILE: $FILE"

	if [[ -d $FILE ]]; then
		echo "Skipping $FILE because it's a directory"
	elif [[ -f $FILE ]]; then
		PARAM_STRING="--guess-mime-type"
		EXT="${FILE##*.}"
		if [ "$EXT" == "css" ]; then
			PARAM_STRING="-mtext/css"
		elif [ "$EXT" == "js" ]; then
			PARAM_STRING="-mapplication/javascript"
		elif [[ "$EXT" == "html" ]]; then
			PARAM_STRING="-mtext/html"
		elif [[ "$EXT" == "png" ]]; then
			PARAM_STRING="-mimage/png"
		elif [[ "$EXT" == "jpg" ]]; then
			PARAM_STRING="-mimage/jpg"
		elif [[ "$EXT" == "svg" ]]; then
			PARAM_STRING="-mimage/svg+xml"
		fi

		DEST_FOLDER=$(dirname "$FILE")
		if [ "$DEST_FOLDER" == "." ]; then
			DEST_FOLDER=
		else
			DEST_FOLDER="${DEST_FOLDER}/"
		fi

		echo s3cmd -v -f -P "$PARAM_STRING" --add-header="Cache-Control:public,max-age=604800" sync "$FILE" "s3://$S3_BUCKET/$DEST_FOLDER"
		s3cmd -v -f -P "$PARAM_STRING" --add-header="Cache-Control:public,max-age=604800" sync "$FILE" "s3://$S3_BUCKET/$DEST_FOLDER"
		rc=$?; if [ $rc != 0 ]; then exit $rc; fi
	fi
done

echo -e "${BLUE}❯ ${GREEN}Upload Complete${RESET}"
