#!/bin/sh

# this shell script refreshes world timezone definitions in
#   ./TZ.h
#
# to run it, use:
#   ./TZupdateWin.sh
# modified from TZupdate.sh to run in cygwin home/<user> dir

dir=$(cd ${0%/*} 2>/dev/null; pwd)
base=${0##*/}

csv=https://raw.githubusercontent.com/nayarsystems/posix_tz_db/master/zones.csv

set -e

tz_tmpdir=$(mktemp -d)
trap 'rm -r $tz_tmpdir' EXIT

input=$tz_tmpdir/zones.csv
names=$tz_tmpdir/names.txt
values=$tz_tmpdir/values.txt

FILE=./TZ.h
if [ -f "$FILE" ]; then
    echo "Will backup $FILE" 
else 
    #echo "$FILE does not exist."
    touch "$FILE" 
fi


#wget -O $input $csv  ||
curl $csv > $input

sed -e 's/^[^,]*,//g' -e 's,^,PSTR(,g' -e 's,$,),g' < $input > $values
sed -e 's/^\([^,]*\),.*/#define TZ_\1/g' -e 's,["],,g' < $input | tr '/\-+' '_mp' > $names

(

cat << EOF

// autogenerated from $csv
// by script <esp8266 arduino core>/tools/${base}
// $(date -u)
//
// This database is autogenerated from IANA timezone database
//    ${csv}
//    (using https://www.iana.org/time-zones)
// and can be updated on demand in this repository
// or by yourself using the above script

#ifndef TZDB_H
#define TZDB_H

EOF

paste $names $values

cat << EOF

#endif // TZDB_H
EOF

) > $tz_tmpdir/TZ.h

backup=$(date +%s)
mv ${dir}/TZ.h ${dir}/TZ.h.$backup
mv $tz_tmpdir/TZ.h ${dir}/TZ.h
cat << EOF

Done:
    '${dir}/TZ.h' is updated

Diff:
----8<-------8<------8<---
$(diff -u ${dir}/TZ.h.$backup ${dir}/TZ.h)
--->8----->8------>8------

EOF
