#!/bin/bash
#set -x
set -e

function error_handler
{
	echo "error_handler:" "$?" args: "$@" 
	export;
}
trap error_handler ERR

function dprint
{
	[ -z "$DEBUG" ] || echo "$@"
	true;
}
function drun
{
	#"$@"
	true
}

#TEST=true
TEST=false

dprint -----------------------------------------------------------------
dprint finding current map release date...
#VERVAR="$(wget -q -O - http://garmin.na1400.info/routable.php | grep '^var version = ')"
#<input type="hidden" name="version" value="13-04-2011">
#VERVAR="$(wget -q -O - http://garmin.openstreetmap.nl/ | grep '<input.*name=.version.' || true)"
#VERVAR="$(echo $VERVAR | grep -o 'value=.*')" 
#VERVAR="$(echo $VERVAR | awk -F= '{print $2}')" 
#VERVAR="$(echo $VERVAR | perl -pe "s/[>\"'\s;]//g")"

VERURL="http://osm.pleiades.uni-wuppertal.de/garmin/versions.js.php";
VERSTR="$(wget -q -O - "$VERURL" | perl -pe 's/.*{//' | awk -F, '{print $1}')"
# 'generic':'20-06-2012'
VERSTR="$(echo $VERSTR | perl -pe "s#'##g")"
VERVAR="$(echo $VERSTR | awk -F: '{print $2}')" 
ORIGVER="$VERVAR"
VERTYPE="$(echo $VERSTR | awk -F: '{print $1}')" 
dprint version type: $VERTYPE
dprint orig version: $ORIGVER
if [ -z "$VERVAR" ]; then
	echo unable to determine version
	exit 1;
fi
if [ "$VERVAR" == "09-10-2012" ]; then
	exit 0;
fi
dprint released: $VERVAR;
#http://osm.pleiades.uni-wuppertal.de/garmin/generic/20-06-2012/63242086.img
#BASE=http://planetosm.oxilion.nl/~lambertus/garmin/routable/$VERVAR
BASE=http://osm.pleiades.uni-wuppertal.de/garmin/$VERTYPE/$VERVAR


VERVAR="$(echo $VERVAR | awk -F- '{print $3"-"$2"-"$1}')"
WORKDIR=$HOME/routable/$VERVAR
OUTDIR=$HOME/www/garmin/Lambertus/$VERVAR
if $TEST; then
	OUTDIR=$HOME/www/garmin/Lambertus/.test/$VERVAR
fi;
KMLDIR=$OUTDIR/kml

mkdir -p $OUTDIR $WORKDIR $KMLDIR

touch --reference=$OUTDIR $WORKDIR/start_stamp

dprint workdir: "'$WORKDIR'"
# This lists all the areas in the world in KML format
WORLD="$WORKDIR/world.php"
if ! [ -s "$WORLD" ]; then
	echo empty world file: "$WORLD", removing
	rm -f "$WORLD"
fi
if ! [ -e "$WORLD" ]; then
	echo downloading world kml file...
	#wget -nv -O "$WORLD" http://garmin.na1400.info/world.php
	#wget -nv -O "$WORLD" http://planetosm.oxilion.nl/~lambertus/garmin/routable/world.php
	wget -nv -O "$WORLD" "http://garmin.openstreetmap.nl/transport.php?url=http://osm.pleiades.uni-wuppertal.de/garmin/$VERTYPE/$ORIGVER/world.kml"
	#http://garmin.openstreetmap.nl/transport.php?url=http://osm.pleiades.uni-wuppertal.de/garmin/generic/20-06-2012/world.kml

else
	dprint world file: "$WORLD" exists
fi

drun ls --time-style=full-iso -ld $OUTDIR $WORKDIR/start_stamp
AA="$WORKDIR/all-areas"
dprint "all-areas file: $AA"
if [ -e "$AA" ] && ! [ -s "$AA" ]; then
	echo empty all-areas file: $AA, removing
	rm "$AA"
fi
if ! [ -e "$AA" ]; then
	echo creating area list: $AA
	# list all the state polygons
	for i in state-polys/*.poly; do
		cat $i;
		echo;
	done | time perl readpoly.pl "$WORLD" > "$AA"
	# and filter the world's areas through that list
	# output any intersecting areas into all-areas
fi

drun ls --time-style=full-iso -ld $OUTDIR $WORKDIR/start_stamp
# get the images listed in all areas
TOTAL=`cat "$AA" | wc -l`
NR=0
HAVE_NR=0
for img in `cat "$AA"`; do
	NR=$((NR+1))
	F="$WORKDIR/$img.img"
	dprint "checking img ($NR/$TOTAL): $F"
	if [ -e "$F" ]; then
		if ! [ -s "$F" ]; then
			echo "$F" has zero size, rming
			rm "$F"
		else
			HAVE_NR=$((HAVE_NR+1))
			dprint already have "$F"
			continue;
		fi
	fi
	printf 'fetching %d/%d\n' $NR $TOTAL
	wget -nv $BASE/$img.img -O "$F" \
	|| echo unable to fetch $img.img
	if [ -e "$F" ]; then
		HAVE_NR=$((HAVE_NR+1))
	fi
done
dprint "have $HAVE_NR/$TOTAL images"
if [ "$HAVE_NR" == 0 ]; then
	echo $VERVAR: did not fetch any images, but have $HAVE_NR/$TOTAL
	exit 1;
fi
if [ $HAVE_NR -ne "$TOTAL" ]; then
	echo $VERVAR: have $HAVE_NR but need $TOTAL
	exit 2;	
fi
#echo auto exit
#exit 3

# mkgmap pukes on empty image files.  But, on 404 and other
# errors wget creates 0-length files.  Find and kill them:
find $WORKDIR -name '*.img' -size 0b -exec rm '{}' \;

# create gmapsupp files broken up into various sizes
drun ls --time-style=full-iso -ld $OUTDIR $WORKDIR/start_stamp
for i in 500 1000 2000 4000; do
	perl partials.pl "$VERVAR" "$WORKDIR" "$OUTDIR" $i
done

# partials.pl generates these kml files
cd $KMLDIR
{	
	echo 'kml = ['
	for i in `ls *.kml | sort -n`; do
		echo "\"$i\",";
	done
	echo '];';
} > kml.js;
rm -f kml.html
ln -s ~/www/garmin/visual/kml.html kml.html

cd $OUTDIR
for i in $OUTDIR/*.img; do 
	if [ ! -e "$i" ]; then
		echo error, can not find image: "$i"
		break;
	fi
	$TEST && break;
	TORRENT="${i}.torrent"
	#ls -l "$TORRENT";
	[ -e "$TORRENT" ] && continue;
	dprint making torrent: "$TORRENT"
	IMG="$(basename "$i")"
	URL="http://daveh.dev.openstreetmap.org/garmin/Lambertus/$VERVAR/$IMG"
	TRACKER="udp://tracker.openbittorrent.com:80/announce,udp://tracker.publicbt.com:80,udp://tracker.ccc.de:80"
	~/mktorrent-1.0/mktorrent -c "$VERVAR" -w "$URL" -a "$TRACKER" -v "$i"
done

cp ~/routable/README $OUTDIR/
drun ls --time-style=full-iso -ld $OUTDIR $WORKDIR/start_stamp
drun ls -ld  $OUTDIR $WORKDIR/start_stamp 
if [ $OUTDIR -nt $WORKDIR/start_stamp ]; then
	$TEST && exit 0;
	
	rm -f $HOME/www/garmin/Lambertus/latest
	ln -s $OUTDIR $HOME/www/garmin/Lambertus/latest

	echo sending mail;
if $TEST; then
	echo "map script is in testing mode
	        http://daveh.dev.openstreetmap.org/garmin/Lambertus/.test/$VERVAR
        	http://daveh.dev.openstreetmap.org/garmin/Lambertus/.test/$VERVAR/kml/kml.html
	" | mail -s "garmin map test" dave@sr71.net
fi


TO="dave@sr71.net"
PRESUBJ=""
if ! [ -e "$WORKDIR/sent_email" ]; then
	TO="$TO talk-us@openstreetmap.org"
	date > "$WORKDIR/sent_email"
else
	PRESUBJ="[PRIVATE DUP] ";
fi;
cat << _EOF | mail \
	-a "From: Dave Hansen <dave@sr71.net>"	\
	-s "${PRESUBJ}Whole-US Garmin Map update - $VERVAR" \
	$TO
These are based off of Lambertus's work here:

	http://garmin.openstreetmap.nl

If you have questions or comments about these maps, please feel
free to ask.  However, please do not send me private mail.  The
odds are, someone else will have the same questions, and by
asking on the talk-us@ list, others can benefit.

Downloads:

	http://daveh.dev.openstreetmap.org/garmin/Lambertus/$VERVAR

Map to visualize what each file contains:

	http://daveh.dev.openstreetmap.org/garmin/Lambertus/$VERVAR/kml/kml.html
----

FAQ

----

Why did you do this?

	I wrote scripts to joined them myself to lessen the impact
	of doing a large join on Lambertus's server.  I've also
	cut them in large longitude swaths that should fit conveniently
	on removable media.  

	http://daveh.dev.openstreetmap.org/garmin/Lambertus/$VERVAR

Can or should I seed the torrents?

	Yes!!  If you use the .torrent files, please seed.  That web
	server is in the UK, and it helps to have some peers on this
	side of the Atlantic.

Why is my map missing small rectangular areas?

	There have been some missing tiles from Lambertus's map (the
	red rectangles),  I don't see any at the moment, so you may
	want to update if you had issues with the last set.

Why can I not copy the large files to my new SD card?

	If you buy a new card (especially SDHC), some are FAT16 from
	the factory.  I had to reformat it to let me create a >2GB
	file.

Does your map cover Mexico/Canada?

	Yes!!  I have, for the purposes of this map, annexed Ontario
	in to the USA.  Some areas of North America that are close
	to the US also just happen to get pulled in to these maps.
	This might not happen forever, and if you would like your
	non-US area to get included, let me know. 

-- Dave

_EOF

fi

rm $WORKDIR/start_stamp
