#!/bin/zsh

if [ ! -x "$(which mc)" ]; then
	echo "Please install the minio client first"
	exit 1
fi

if [ ! -x "$(which python3)" ]; then
	echo "WARNING: Please install python3 to use '-e none'"
else
	urlescape() {
		python3 -c 'import urllib.parse; import sys; print(urllib.parse.quote(sys.argv[1]))' "$1"
	}
fi

SHASUM="sha256sum"
if [ ! -x "$(which $SHASUM)" ]; then
	SHASUM="shasum"
fi

case "$SHARE_PROFILE" in
	minio1)
		HOST_ALIAS=minio1
		BUCKET=share
		BUCKET_URL=https://minio1.makerforce.io/share
		BUCKET_PUBLIC=pub
		BUCKET_PUBLIC_URL=https://minio1.makerforce.io/pub
	;;
	b|*)
		HOST_ALIAS=b
		BUCKET=serverwentdown
		BUCKET_URL=https://serverwentdown.s3.us-west-000.backblazeb2.com
		BUCKET_PUBLIC=serverwentdown-pub
		BUCKET_PUBLIC_URL=https://serverwentdown-pub.s3.us-west-000.backblazeb2.com
	;;
esac

FILES=()
NAMES=()
EXPIRES=()

read_fileopts() {
	if [ ! -z "$FILE" ]; then
		FILES+=("$FILE")
		NAMES+=("$NAME")
		EXPIRES+=("$EXPIRE")
		FILE=""
		NAME=""
		EXPIRE="168h"
	fi
}
read_fileopts

OPTIND=1
while getopts "hn:e:f:p" opt; do
	case "$opt" in
	h)
		echo "NAME:"
		echo "   share - Shares files to $HOST_URL"
		echo ""
		echo "USAGE:"
		echo "   share -f FILE [-n NAME] [-e EXPIRES] [-f FILE ...]"
		echo ""
		echo "FLAGS:"
		echo "  -f FILE     Share FILE"
		echo "  -n NAME     Share at NAME instead of SHASUM/FILENAME"
		echo "  -e EXPIRES  Link expiry (default: 168h)"
		echo "  -p          Link never expires"
		echo ""
		exit 0
		;;
	n)
		NAME="$OPTARG"
		;;
	e)
		EXPIRE="$OPTARG"
		;;
	p)
		EXPIRE="never"
		;;
	f)
		read_fileopts
		FILE="$OPTARG"
		;;
	esac
done
read_fileopts

for i in {1..$#FILES}; do
	FILE="${FILES[$i]}"
	NAME="${NAMES[$i]}"
	EXPIRE="${EXPIRES[$i]}"
	if [ -z "$NAME" ]; then
		HASH=$($SHASUM $FILE | awk '{ print $1 }')
		FILENAME="$(basename $FILE)"
		NAME="$HASH/$FILENAME"
	fi

	TARGET="$HOST_ALIAS/$BUCKET/$NAME"
	if [[ "$EXPIRE" == "never" ]]; then
		TARGET="$HOST_ALIAS/$BUCKET_PUBLIC/$NAME"
	fi

	mc cp "$FILE" "$TARGET" >&2
	if [[ "$EXPIRE" == "never" ]]; then
		echo "$BUCKET_PUBLIC_URL/$(urlescape "$NAME")"
	else
		mc share download \
			--expire="$EXPIRE" \
			"$TARGET" \
			| sed '3q;d' | cut -d ' ' -f 2
	fi
done

