#!/bin/bash

TAIL_MAX=7
ITER_MAX=5

function _proxify {
	"$@"
}

function _change_proxy {
	:
}

# getmap <base> <q> <r> <s> <t>
function getgmap {
	local base=$1
	shift

	if [ ${#@} -gt $TAIL_MAX ]; then
		return 0
	fi

	local tail=""
	for i in "$@"; do
		tail="${tail}${i}"
	done

	dir="${base}/$(echo "./$tail" | sed 's![qrst]\{2\}!&/!g;s!/[qrst]*$!!')"
	mkdir -p "$dir"

	local file="${dir}/${base}${tail}.jpeg"
	local srv=$(( $RANDOM % 4 ))
	local url="http://kh${srv}.google.com/kh?n=404&v=20&t=${base}${tail}"
	local tempfile="${base}-$RANDOM.jpeg"
	local do_deep=true
	if [ ! -r "$file" ]; then
		for ((iter=0; $iter < $ITER_MAX; iter++)); do
			local line=$(echo $(_proxify wget -nv -O "$tempfile" "$url" 2>&1))
			local ts=$(date '+%h %_d %H:%M:%S')
			echo "$ts $line" >> debug.log
			if [[ "$line" = [0-9][0-9]:[0-9][0-9]:[0-9][0-9]" URL:${url} "* ]]; then
				# ok
				echo -n '+'
				mv "$tempfile" "$file"
				break
			elif [[ "$line" = "${url}: "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" ERROR 404:"* ]]; then
				# not found, don't go deeper
				echo -n '-'
				do_deep=false
				break
			elif 
				[[ "$line" = "${url}: "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" ERROR 403:"* ]] ||
				[[ "$line" = *"http://www.google.com/sorry/?continue=http://kh"[0123]".google.com/kh"* ]] ;
			then
				# change proxy and retry
				echo -n '.'
				_change_proxy
				echo "$ts getgoogle: changing proxy" >> warn.log
				sleep 3
			else
				# don't know what to do
				echo -n '!'
				echo "$ts wget: $line" >> error.log
			fi
		done
	fi
	rm -f "$tempfile"

	if [ "$iter" = $ITER_MAX ]; then
		echo "$ts getgoogle: ERROR: ${base}${tail} was broken $ITER_MAX times" >> warn.log
	fi

	if $do_deep; then
		for i in q r s t; do
			getgmap "${base}" "$@" "$i" || return 1
		done
	fi
	return 0
}

for i in qrrssr qrrsss rqqtst rqqttq rqqtts rqqttt rqtqqq rqtqqr rqtqqs rqtqqt rqtqrq rqtqrt; do
        getgmap "trtrsq$i" &
done

wait

# vim:set tabstop=4 softtabstop=4 shiftwidth=4:
# vim:set foldmethod=marker foldlevel=32 foldmarker={,}:
