#!/bin/sh

TMP1=$(mktemp)
TMP2=$(mktemp)

E=0  # exit status
URL="$1"
D=0; test "$1" = "-d" && D=1 && URL="$2"  # debugging mode

clean_exit () {
	test $D -gt 0 && echo "debug: exit status $E"
	if [[ $D -gt 0 && $E -gt 0 ]]
		then echo "debug: not deleting temp files $TMP1 $TMP2"
		exit $E
	fi
	rm -f $TMP1 $TMP2
	exit $E
}


if ! echo "$URL" | grep -q '://www.fakku.net/'
	then
	echo -e "\nBad FAKKU! URL given.\n"
	echo -e "Usage: $0 http://www.fakku.net/manga/blah-blah-blah/read\n"
	echo "Copy and paste the 'information' link from a FAKKU! manga to this script."
	echo "Do not use the 'Read Online' link; it will be found automatically."
	echo -e "Series and title will automatically be detected for you.\n"
	E=1; clean_exit
fi

test "$D" = "1" && echo "debug: wget -O $TMP1 $URL"
! wget -O $TMP1 "$URL" && echo "Error downloading main link" && E=1 && clean_exit
test "$D" = "1" && echo "debug: wget -O $TMP2 $URL/read"
! wget -O $TMP2 "$URL/read" && echo "Error downloading read link" && E=1 && clean_exit

A="$(grep -m1 '<a href="/artists/' $TMP1 | sed 's/[^>]*>[^>]*>\([^<]*\)<.*/\1/')"
T="$(grep -m1 '^<h1 itemprop="name">' $TMP1 | sed 's/[^>]*>\([^<]*\)<.*/\1/')"
U="$(grep "return '[htps:]*//[^.]*.fakku.net" $TMP2 | sed 's#[^/]*//##')"
CNT=$(grep 'window.params.thumbs = ' $TMP2 | sed 's/\.png/\.jpg/g;s/\.gif/\.jpg/g;s/\.jpg"]}.*//;s/\.jpg/\n/g' | grep fakku | wc -l)
test "$D" = "1" && echo "debug: A='$A' T='$T' U='$U' CNT='$CNT'"

grep -q 'title="English Hentai"' $TMP2 && T="$T (English)"

DIR="$(echo "$A - $T" | tr -d '?')"

test -z "$A" && echo "Empty Author. Aborting." && E=1 && clean_exit
test -z "$T" && echo "Empty Title. Aborting." && E=1 && clean_exit
test $CNT -lt 2 && echo "Page count too low. Aborting." && E=1 && clean_exit
! mkdir "$DIR" && echo "'$DIR' already exists. Aborting." && E=1 && clean_exit

echo "$DIR, $CNT pages"

X=1
while [ $X -le $CNT ]
	do
	wget -nc -nd -P "$DIR/" "$(echo "$U" | sed "s/' + x + '/$(printf "%03d" "$X")/;s/';$//")"
	X=$((X + 1))
done

clean_exit
