#!/bin/sh

# $Id: yaouh.sh,v 1.4 2009/02/05 09:03:37 guru Exp $
#
# idea basada en yaouh0.3_alpha.py
# http://wiki.openmoko.org/wiki/Yaouh
#
# Matthias Apitz <guru@unixarea.de>, Feb 2009

# Reasoning regarding timestamps
# 1) Initial run, no lastrun file found
#    - set lastrun to current date
#    - update older tiles (=all!)
#    - touch files when checked!
# 2) run completed
#    - remove lastrun, next run will be full one again
# 3) run stopped, then contuned later
#    - lastrun still set, so simply continue

osmdir=~/Maps/OSM
baseURL=http://tile.openstreetmap.org/
LR=${osmdir}/lastrun

BeginOfLine=`tput hpa 0 el`
CUR=0
SKIPPED=0
MD5=0
DL=0

cd ${osmdir}

if [ -f lastrun ]; then
  echo "Will CONTINUE update from $(cat ${LR}) :"
  echo "Found a file ${LR} and will skip all newer tiles."
  echo "If this is not what you want, just remove this file."
else
  echo "INITIAL UPDATE:"
  echo "No file ${LR} found, will create a new one"
  echo "to be able to continue in case the update is stopped."
  date > ${LR}
fi
echo -n . ; sleep 1;echo -n . ; sleep 1;echo -n . ; sleep 1;echo . ;

find * -name *.png -print > /tmp/maps.$$
TILECNT=$(cat /tmp/maps.$$ | wc -l)

while read file; do
    # progress indicator
    if [[ $((CUR%10)) -eq "0" ]] ; then
      echo -n ${BeginOfLine}
      printf "%2d%% (%d/%d) : %d %d %d [Skipped/Identical/Updated]" $((CUR*100/TILECNT)) $CUR $TILECNT $SKIPPED $MD5 $DL
    fi
    CUR=$((CUR+1))

    # Already checked in last run ?
    if [ lastrun -ot ${file} ]; then
      SKIPPED=$((SKIPPED+1))
	    continue
    fi

    # compare MD5
    remoteMd5=`curl -A yaouh.sh -I ${baseURL}${file} --stderr /dev/null | grep ETag | cut -d\" -f 2`
    localMd5=`md5sum ${file} | cut -f 1 -d \ `

    if [ "${remoteMd5}" != "${localMd5}" ]; then
      wget --user-agent yaouh.sh -q ${baseURL}${file} -O ${file}
      DL=$((DL+1))
    else
      MD5=$((MD5+1))
      touch ${file}
    fi
done < /tmp/maps.$$

# cleanup
rm /tmp/maps.$$
# Make sure next run is a full one again..
rm  ${LR}
