#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  tmp FILE...
		  tmp -d
		  tmp -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -d            delete the remote "tmp/" folder
		  -h, --help    show this message

		  FILE          path to files to be copied


		Copies a file to the public server.


		Examples:

		  Copy f.txt:

		    $ tmp f.txt


		  Cleanup the $REMOTE:

		    $ tmp -d
	EOF
}

for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

REMOTE='euandre.org'
DIR='/srv/www/tmp'
while getopts 'dh' flag; do
	case "$flag" in
		(d)
			printf 'Deleting %s:%s...\n' "$REMOTE" "$DIR/" >&2
			ssh "$REMOTE" rm -rf "$DIR"/*
			exit
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))
FILE="${1:-}"

if [ -z "$FILE" ]; then
	printf 'Missing FILE.\n\n' >&2
	usage >&2
	exit 2
fi

for f in "$@"; do
	FILENAME="$(basename "$f")"
	ssh "$REMOTE" dd of="$DIR/$FILENAME" < "$f"

	LINK="$(printf 'https://%s/tmp/%s' "$REMOTE" "$FILENAME")"
	open "$LINK"
	if [ $# = 1 ]; then
		printf '%s' "$LINK" | copy
		printf 'Copied %s to the clipboard!\n' "$LINK" >&2
	fi
done
