#!/bin/sh

# simple shell script for uploading images on imgur
# Author: John Tsiombikas <nuclear@member.fsf.org>
# No copyright, public domain
# 
# Usage: imgur [-t title] [-c caption] <filename>
# requires curl: http://curl.haxx.se/

imgur_devkey=85af32ab5461a67e2aa28d2d250bc25b
logfile=/tmp/imgur_reply.log

get_xml_cdata() {
	echo $1 | sed "s/.*<$2>\(.*\)<\/$2>.*/\1/"
}

# TODO needs more foo
url_encode() {
	echo $1 | sed 's/ /+/g'
}

while [ $# -gt 0 ]; do
	case $1 in
	-t)
		if [ $# -lt 2 ]; then
			echo '-t must be followed by the title' >&2
			exit 1
		fi
		title=$2
		shift
		;;

	-c)
		if [ $# -lt 2 ]; then
			echo '-c must be followed by the caption' >&2
			exit 1
		fi
		caption=$2
		shift
		;;

	*)
		if [ -z "$imgfile" ]; then
			imgfile=$1
		else
			echo "unexpected argument: $1" >&2
		fi
		;;
	esac
	shift
done

if [ -z "$imgfile" ]; then
	echo "you didn't specify a file to upload" >&2
	exit 1
fi
if [ ! -f "$imgfile" ]; then
	echo "file $imgfile does not exist or is not a file" >&2
	exit 1
fi

echo "uploading file: $imgfile"
if [ -n "$title" ]; then
	echo "title: $title"
	utitle=`url_encode "$title"`
fi
if [ -n "$caption" ]; then
	echo "caption: $caption"
	ucaption=`url_encode "$caption"`
fi

xml=`curl -# -T "$imgfile" "http://api.imgur.com/2/upload?key=$imgur_devkey&title=$utitle&caption=$ucaption"`
if [ $? != 0 ]; then
	echo "failed miserably" >&2
	exit 1
fi
echo "$xml" >$logfile

if echo "$xml" | grep '<error>' >/dev/null; then
	echo error: `get_xml_cdata "$xml" message` >&2
	exit 1
fi

echo done.
echo - imgur link: `get_xml_cdata "$xml" imgur_page`
echo - delete link: `get_xml_cdata "$xml" delete_page`
