#!/bin/ksh
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/pkg/bin:/usr/pkg/sbin"
export TOKEN="token"
export HOST="host"
export VISIBILITY="public"
alias randline="perl -we 'srand ; rand(\$.) < 1 && (\$line = \$_) while <STDIN>; chomp(\$line); print \"\$line\\n\";'"
RETRY="--retry 5 --retry-delay 0 --retry-max-time 1"
post(){
	curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d@- $RETRY https://$HOST/api/v1/statuses
}
escape(){
	sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | perl -pe 's/\n/\\n/g'
}
if [ "$1" = "post" ]; then
	echo -n '{"status": "<code>' > output.json
	escape >> output.json
	echo -n '</code>", "content_type": "text/html"}' >> output.json
	cat output.json | post
	rm -f output.json
elif [ "$1" = "escape" ]; then
	escape
elif [ "$1" = "meiling" ]; then
	URL=`curl -s "https://danbooru.donmai.us/posts.json?tags=hong_meiling%20rating:s%20order:random&limit=10&page=1" | jq -c '. - map(select(.is_banned)) | .[] | .file_url + " " + .source' | randline | sed -E 's/^"|"$//g'`
	IMAGE_URL="`echo $URL | cut -d" " -f1`"
	SRC_URL="`echo $URL | sed -E 's/^[^ ]+ //g'`"
	EXT=`echo "$IMAGE_URL" | grep -oE '\.[^\.]+$' | sed -E 's/^\.//g'`
	curl $IMAGE_URL > output.$EXT
	ID=`curl -X POST -H "Content-Type: multipart/form-data" -H "Authorization: Bearer $TOKEN" -F "file=@output.$EXT" $RETRY https://$HOST/api/v1/media | jq '.id' | sed -E 's/^"|"$//g'`
	echo -n '{"status": "Meiling pics!!!\nSource: '"$SRC_URL"'", "content_type": "text/html", "media_ids": ["'$ID'"], "sensitive": true, "visibility": "'$VISIBILITY'"}' >> output-meiling.json
	cat output-meiling.json | post
	rm -f output-meiling.json output.$EXT
else
	echo "Usage: $0 post|escape|meiling"
fi
