#!/bin/sh
# pstsrv
# Written in 2020 by Lucas
# CC0 1.0 Universal/Public domain - No rights reserved
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty. You should have received a copy of the CC0 Public Domain
# Dedication along with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

usage()
{
	printf "Usage: %s [-T] service [files...]\n" "${0##*/}" >&2
	exit 1
}

err()
{
	printf "%s: %s\n" "${0##*/}" "$*" >&2
	exit 1
}

check_prog()
{
	if ! command -v "$1" >/dev/null 2>&1; then
		printf "%s: missing required program %s\n" \
		    "${0##*/}" "$1" >&2
		return 1
	fi
	return 0
}

check_runtime()
{
	rc=0
	for prog; do
		check_prog "$prog" || rc=1
	done
	return $rc
}

pst_catbox_moe()
{
	$torsocks curl -F "reqtype=fileupload" -F "fileToUpload=@$1" \
	    https://catbox.moe/user/api.php
}

pst_ix_io()
{
	$torsocks curl -F "f:1=@$1" http://ix.io/
}

do_upload()
{
	uploader=$1
	shift

	rc=0
	if [ $# -eq 0 ]; then
		$uploader - || rc=1
	else
		for arg; do
			$uploader "$arg" || rc=1
		done
	fi

	return $rc
}

torsocks=torsocks
while getopts T flag; do
	case $flag in
	T)	torsocks= ;;
	*)	usage ;;
	esac
done
shift $((OPTIND - 1))

if [ $# -eq 0 ]; then
	usage
fi
srv=$1
shift

check_runtime curl $torsocks

[ $# -eq 0 ] && set -- -
case $srv in
catbox.moe)
	do_upload pst_catbox_moe "$@"
	;;
ix.io)
	do_upload pst_ix_io "$@"
	;;
*)
	err "unknown service $srv"
	;;
esac
