#!/bin/bash

# Dependencies:
#    curl
# 	 xclip

TARGET=http://stuff.krakonos.org

function die() {
	echo $@
	exit 1
}

function do_upload() {
	FILE=$1

	[[ -f "$FILE" ]] || die "File not found."

	MAXSIZE=$( curl -s ${TARGET}/query.php?q=max_filesize )
	FILESIZE=$( stat -c "%s" "$FILE" )

	[[ $MAXSIZE -ge $FILESIZE ]] || die "File too big. Maximal allowed size is $MAXSIZE."

	LINK=$( curl -F file=@"$FILE" ${TARGET}/upload.php )

	if echo $LINK | grep -q "^error"; then
		echo "Error reported by server:"
	else
		echo -n $LINK | xclip -i
	fi
	echo $LINK
}

while [[ $# -gt 0 ]]; do
	do_upload "$1"
	shift 1
done
