#!/bin/bash
# v0.2 - written by seba (http://seba-geek.de)
# Licensed under the beer- || pizzaware license ;)

first=$(ls -1|grep "^[0-9]\+_.\+\.\(png\|jpg\)"|grep -o "^[0-9]\+"|grep -o "[1-9]\+[0-9]*"|sort -n|tail -n 1)
if [[ $first == "" ]]; then
	first=0;
fi 
lastnum=$(wget http://xkcd.com/ -O- 2>/dev/null|grep  -i permanent |sed -n -e 's/.*http:\/\/xkcd.com\/\([0-9]\+\).*/\1/p')
if [[ $lastnum == $first ]]; then
	echo 'You got all comics, no downloading will be done ;)'
	exit 0
fi
num=$(expr $lastnum - $first)
echo -e "$num comic$(if [[ $num != 1 ]]; then echo -n "s"; fi) will be downloaded\n"
first=$(expr $first + 1)
for i in $(seq $first $(wget http://xkcd.com/ -O- 2>/dev/null|grep  -i permanent |sed -n -e 's/.*http:\/\/xkcd.com\/\([0-9]\+\).*/\1/p')); do
	echo Downloading $i;
	srclink=$(wget -O- http://xkcd.com/$i 2>/dev/null|grep "img src=\"http://imgs.xkcd.com/comic")
	link=$(echo $srclink|sed -n -e 's/.*src="\([^"]*\)".*/\1/p')
	haslarge=$(echo $srclink|sed -n -e 's/^<a href="\([^"]\+\)">.*/\1/p')
	if [[ "$haslarge" != "" ]] && [[ "$haslarge"  ]]; then
		tmplink=$(wget -O- $haslarge 2>/dev/null|grep -o "http://imgs.xkcd.com/comics/[^\"]\+")
		if [[ $tmplink != "" ]]; then link=$tmplink; fi
	fi
	alttxt=$(echo $srclink|sed -n -e 's/.*title="\([^"]*\)".*/\1/p')
	for p in $(echo $alttxt|grep "&#[0-9]\{2,3\};" -o); do alttxt=$(echo $alttxt|sed "s/$p/"$(printf \\$(printf %03o $(echo $p|grep -o '[0-9]\+')))"/g"); done
	img=$(printf %03d $i)_$(echo $link|sed -e 's/http:\/\/imgs.xkcd.com\/comics\///')
	wget $link -O $img;
	echo Appending alttext...
	width=$(identify -format %w $img)
	height=$(echo "($(echo $alttxt|wc -m)*6.6666*100/$width+99)/100*15+17"|bc)
	convert -background 'white' -fill black -gravity center -pointsize 14 -size ${width}x$height caption:"$alttxt" $img +swap -gravity south -append $img
	echo Saved to $img
	if [[ $i != $lastnum ]]; then
		tim=5
		while [[ $tim -ge 0 ]]; do
			echo -en "\rWaiting ${tim}s for 'not dossing the server'";
			if [[ $tim -gt 0 ]]; then sleep 1s; fi;
			tim=$(expr $tim - 1);
		done;
		echo -e '\n';
	fi
done
