#!/usr/bin/env bash
set -xeuo pipefail

SRC_COMMIT="9ee45289e01232b8df1413efea11db170ae3b3b4"
SRC_FILE=timezones.h
DST_FILE=timezones.py

[ -e ${SRC_FILE} ] && rm ${SRC_FILE}
wget -O ${SRC_FILE} \
	https://raw.githubusercontent.com/tarantool/tarantool/${SRC_COMMIT}/src/lib/tzcode/timezones.h

# We don't need aliases in indexToTimezone because Tarantool always replace it:
#
# tarantool> T = date.parse '2022-01-01T00:00 Pacific/Enderbury'
# ---
# ...
# tarantool> T
# ---
# - 2022-01-01T00:00:00 Pacific/Kanton
# ...
#
# So we can do the same and don't worry, be happy.

cat <<EOF > ${DST_FILE}
"""
Tarantool timezone info. Automatically generated by
\`\`gen-timezones.sh\`\`.
"""
# pylint: disable=too-many-lines

TZ_UTC = 0x01
TZ_RFC = 0x02
TZ_MILITARY = 0x04
TZ_AMBIGUOUS = 0x08
TZ_NYI = 0x10
TZ_OLSON = 0x20
TZ_ALIAS = 0x40
TZ_DST = 0x80

indexToTimezone = {
EOF

grep ZONE_ABBREV ${SRC_FILE} | sed "s/ZONE_ABBREV( *//g" | sed "s/[),]//g" \
	| awk '{printf("    %s: %s,\n", $1, $3)}' >> ${DST_FILE}
grep ZONE_UNIQUE ${SRC_FILE} | sed "s/ZONE_UNIQUE( *//g" | sed "s/[),]//g" \
	| awk '{printf("    %s: %s,\n", $1, $2)}' >> ${DST_FILE}

cat <<EOF >> ${DST_FILE}
}

timezoneToIndex = {
EOF

grep ZONE_ABBREV ${SRC_FILE} | sed "s/ZONE_ABBREV( *//g" | sed "s/[),]//g" \
	| awk '{printf("    %s: %s,\n", $3, $1)}' >> ${DST_FILE}
grep ZONE_UNIQUE ${SRC_FILE} | sed "s/ZONE_UNIQUE( *//g" | sed "s/[),]//g" \
	| awk '{printf("    %s: %s,\n", $2, $1)}' >> ${DST_FILE}
grep ZONE_ALIAS  ${SRC_FILE} | sed "s/ZONE_ALIAS( *//g"  | sed "s/[),]//g" \
	| awk '{printf("    %s: %s,\n", $2, $1)}' >> ${DST_FILE}

cat <<EOF >> ${DST_FILE}
}

timezoneAbbrevInfo = {
EOF

grep ZONE_ABBREV ${SRC_FILE} | sed "s/ZONE_ABBREV( *//g" | sed "s/[),]//g"  \
	| awk '{printf("    %s: {\"offset\": %d, \"category\": %s},\n", $3, $2, $4)}' | sed "s/|/ | /g" >> ${DST_FILE}
echo "}" >> ${DST_FILE}

rm timezones.h

python <<EOF
import pytz
from timezones import timezoneToIndex, timezoneAbbrevInfo

if __name__ != '__main__':
    raise RuntimeError('Import not expected')

for timezone in timezoneToIndex.keys():
    if timezone in pytz.all_timezones:
        continue

    if not timezone in timezoneAbbrevInfo:
        raise KeyError(f'Unknown Tarantool timezone {timezone}')
EOF
