#!/bin/sh
# pstsrv
# Written in 2020-2021,2023 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 [-x proxy] service file [file ...]\n" "${0##*/}" >&2
	exit 1
}

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

check_runtime()
{
	_s=

	for _prog; do
		command -v "$_prog" >/dev/null 2>&1 || _s=${_s:+"$_s "}$_prog
	done

	if [ -n "$_s" ]; then
		err "missing required programs: $_s"
	fi
}

_curl()
{
	curl ${proxy:+-x "$proxy"} -Ss "$@"
}

impl_catbox_moe()
{
	check_runtime curl

	_curl -F "reqtype=fileupload" -F "fileToUpload=@$1" \
	    https://catbox.moe/user/api.php
}

impl_pst_moe()
{
	check_runtime curl

	_curl -F "content=<$1" -F "expire_after=86400" https://pst.moe/paste
}

impl_uguu()
{
	check_runtime curl jq

	_jq_prog='
if .success then
  (.files[] | [.url, .name] | @tsv)
else
  "Error \(.errorcode): \(.description)"
end
'

	for _f; do
		shift
		set -- "$@" -F "files[]=@$_f"
	done
	_curl "$@" "https://$uguu_host/upload.php" | jq -r "$_jq_prog"
}

proxy=
while getopts x: flag; do
	case $flag in
	x)	proxy=$OPTARG ;;
	*)	usage ;;
	esac
done
shift $((OPTIND - 1))

if [ $# -lt 2 ]; then
	usage
fi
srv=$1
shift

case $srv in
catbox.moe)
	impl=impl_catbox_moe
	;;
pst.moe)
	impl=impl_pst_moe
	;;
uguu.se|cockfile.com)
	impl=impl_uguu uguu_host=$srv
	;;
*)
	err "unknown service $srv"
	;;
esac
$impl "$@"
