#!/usr/bin/env python3

# Copyright © 2013-2022 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import collections
import datetime
import os
import subprocess as ipc
import sys

import pytz

# pylint: disable=wrong-import-position

sys.path[0] += '/..'
basedir = sys.path[0]

from lib import gettext

int(0_0)  # Python >= 3.6 is required

def get_tzdata_version():
    version = pytz.OLSON_VERSION
    if os.path.exists('/etc/debian_version'):
        # On Debian systems, pytz uses the system timezone database,
        # so pytz.OLSON_VERSION is not reliable.
        version = ipc.check_output(['dpkg-query', '-Wf', '${Version}', 'tzdata'])
        version = version.decode('ASCII')
        version, revision = version.rsplit('-', 1)
        del revision
    return version

def main():
    minyear = gettext.epoch.year
    maxyear = datetime.date.today().year + 1
    tzdata = collections.defaultdict(set)
    for tzname in pytz.all_timezones:
        if tzname.startswith('Etc/'):
            continue
        tz = pytz.timezone(tzname)
        try:
            timestamps = list(tz._utc_transition_times)  # pylint: disable=protected-access
        except AttributeError:
            timestamps = []
        timestamps += [datetime.datetime(minyear, 1, 1)]
        for timestamp in timestamps:
            if not (minyear <= timestamp.year <= maxyear):
                continue
            timestamp = tz.fromutc(timestamp)
            code, offset = timestamp.strftime('%Z %z').split()
            assert 3 <= len(code) <= 6
            tzdata[code].add(offset)
    path = os.path.join(basedir, 'data', 'timezones')
    sys.stdout = open(path + '.tmp', 'wt', encoding='ASCII')  # pylint: disable=consider-using-with
    tzdata_version = get_tzdata_version()
    today = datetime.date.today()
    print(f'''\
# This file has been generated automatically by private/update-timezones.
# Do not edit.
# Timezone database version: {tzdata_version}
# Last update: {today}
''')
    print('[timezones]')
    for code, offsets in sorted(tzdata.items()):
        offsets = str.join(' ', sorted(offsets))
        print(f'{code} = {offsets}')
    print()
    print('# vim\72ft=dosini')
    sys.stdout.close()
    os.rename(path + '.tmp', path)

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et
