#!/bin/bash


# This script takes care of uploading all artifacts in the public/ directory
# To neocities via its API, This script is meant to be used in  CI only
# however it may occasionally be tested elsewhere


upload_file() {
	set -e
	file_path="$1"
	uri_path="${file_path:6}"

	if [ -z "$file_path" ];then
		echo ERROR: upload_file Received an empty parameter exiting now >&2
		return 1
	fi

	# Curl gives us the exit code for this sub-routine's exit code
	curl -s \
		-H "Authorization: Bearer ${API_KEY}" \
		-F "${uri_path}=@${file_path}" \
		'https://neocities.org/api/upload'

	return $!
}

feed_files() {
	# 2 seconds between API hits to ease up on Neocities
	SLEEP_TIME=2

	if [ ! -z "$CUSTOM_SLEEP_TIME" ]; then
		SLEEP_TIME=$CUSTOM_SLEEP_TIME
	fi

	# Main uploading section
	while read -r line; do
		if upload_file "$line"; then
			echo "Pass $line"
		else
			echo "Failed $line" > /dev/stderr
		fi
		sleep $SLEEP_TIME
	done < /dev/stdin
}

verify_api_key() {
	if [ -z "$API_KEY" ];then
		echo '$API_KEY env var is not set' > /dev/stderr
		exit 1
	fi
}
verify_public_dir() {
	# Check that the public directory is present
	if [ ! -d public/ ];then
		echo 'No public directory found!' > /dev/stderr
		exit 1
	fi
}

# Pre flight checks to make sure we don't try uploading without
# the required keys/files in place
verify_public_dir; verify_api_key

# Only upload items that have an extension(files) in the case
# of data generated by hugo
find public/ -type f | \
	grep '\.[a-z]*' | \
	feed_files
