#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;
use DateTime;
use JSON::XS;
use Test::Deep::NoTest;

my (
  %DaysOfWeek,
  $JSON,
  %Links,
  $Path,
  %RulesByZone,
  %Rules,
  %RuleMapping,
  %Zones,
  %ZonesByOffset,
  %ZoneRuleMapping,
);

our (
  $TimeZonesByPopulation
);

Init();
ParseRules();
ParseZones();
MapZones();
GenerateTimeZoneMapping();

sub GenerateTimeZoneMapping {
  $Data::Dumper::Terse = 1;

  print q{package ME::CalDAVTalk::TimeZones;

=head1 NAME

ME::CalDAVTalk::TimeZone - autogenerated timezone data for ME::CalDAVTalk

=head1 SYNOPSIS

    *** WARNING: DO NOT EDIT ***

    This file is generated by utils/GenerateTimeZoneModule.pl

   ./utils/GenerateTimeZoneModule.pl htdocs/ajaxui/build/fastmail/timezones-raw.js > modules/Net/CalDAVTalk/TimeZones.pm

   } . "Generated: " . scalar(gmtime()) . q{

=cut

use strict;
use warnings;

use Data::ICal::Entry::TimeZone;
use Data::ICal::Entry::TimeZone::Daylight;
use Data::ICal::Entry::TimeZone::Standard;
use Data::ICal::TimeZone;
use DateTime::Format::ISO8601;
use DateTime::TimeZone;
use Text::LevenshteinXS qw{distance};

our $RulesByZone = }   . Data::Dumper->Dump([\%RulesByZone]) . q{;
our $ZonesByOffset = } . Data::Dumper->Dump([\%ZonesByOffset])    . q{;

#
# This list is copied from:
#   AjaxApp/API/Mailbox.pm
#   http://wiki.zimbra.com/wiki/Time_Zones_in_ZCS
#

our %OtherLinks = (
  'AUS Central Standard Time'                                         => 'Australia/Darwin',
  'AUS Central'                                                       => 'Australia/Darwin',
  'AUS Eastern Standard Time'                                         => 'Australia/Sydney',
  'AUS Eastern'                                                       => 'Australia/Sydney',
  'Afghanistan Standard Time'                                         => 'Asia/Kabul',
  'Afghanistan'                                                       => 'Asia/Kabul',
  'Alaskan Standard Time'                                             => 'America/Anchorage',
  'Alaskan'                                                           => 'America/Anchorage',
  'Arab Standard Time'                                                => 'Asia/Riyadh',
  'Arab'                                                              => 'Asia/Riyadh',
  'Arabian Standard Time'                                             => 'Asia/Muscat',
  'Arabian'                                                           => 'Asia/Muscat',
  'Arabic Standard Time'                                              => 'Asia/Baghdad',
  'Argentina Standard Time'                                           => 'America/Argentina/Buenos_Aires',
  'Armenian Standard Time'                                            => 'Asia/Yerevan',
  'Atlantic Standard Time'                                            => 'America/Halifax',
  'Atlantic'                                                          => 'America/Halifax',
  'Azerbaijan Standard Time'                                          => 'Asia/Baku',
  'Azores Standard Time'                                              => 'Atlantic/Azores',
  'Azores'                                                            => 'Atlantic/Azores',
  'Bangkok Standard Time'                                             => 'Asia/Bangkok',
  'Bangkok'                                                           => 'Asia/Bangkok',
  'Bangladesh Standard Time'                                          => 'Asia/Dhaka',
  'Beijing'                                                           => 'Asia/Shanghai',
  'Canada Central Standard Time'                                      => 'America/Regina',
  'Canada Central'                                                    => 'America/Regina',
  'Cape Verde Standard Time'                                          => 'Atlantic/Cape_Verde',
  'Caucasus Standard Time'                                            => 'Asia/Yerevan',
  'Caucasus'                                                          => 'Asia/Yerevan',
  'Cen. Australia Standard Time'                                      => 'Australia/Adelaide',
  'Cen. Australia'                                                    => 'Australia/Adelaide',
  'Central America Standard Time'                                     => 'America/Regina',
  'Central Asia Standard Time'                                        => 'Asia/Almaty',
  'Central Asia'                                                      => 'Asia/Almaty',
  'Central Brazilian Standard Time'                                   => 'America/Cuiaba',
  'Central Europe Standard Time'                                      => 'Europe/Prague',
  'Central Europe'                                                    => 'Europe/Prague',
  'Central European Standard Time'                                    => 'Europe/Belgrade',
  'Central European'                                                  => 'Europe/Belgrade',
  'Central Pacific Standard Time'                                     => 'Pacific/Guadalcanal',
  'Central Pacific'                                                   => 'Pacific/Guadalcanal',
  'Central Standard Time (Mexico)'                                    => 'America/Mexico_City',
  'Central Standard Time'                                             => 'America/Chicago',
  'Central'                                                           => 'America/Chicago',
  'China Standard Time'                                               => 'Asia/Shanghai',
  'China'                                                             => 'Asia/Shanghai',
  'E. Africa Standard Time'                                           => 'Africa/Nairobi',
  'E. Africa'                                                         => 'Africa/Nairobi',
  'E. Australia Standard Time'                                        => 'Australia/Brisbane',
  'E. Australia'                                                      => 'Australia/Brisbane',
  'E. Europe Standard Time'                                           => 'Europe/Minsk',
  'E. Europe'                                                         => 'Europe/Minsk',
  'E. South America Standard Time'                                    => 'America/Sao_Paulo',
  'E. South America'                                                  => 'America/Sao_Paulo',
  'Eastern Standard Time'                                             => 'America/New_York',
  'Eastern'                                                           => 'America/New_York',
  'Egypt Standard Time'                                               => 'Africa/Cairo',
  'Egypt'                                                             => 'Africa/Cairo',
  'Ekaterinburg Standard Time'                                        => 'Asia/Yekaterinburg',
  'Ekaterinburg'                                                      => 'Asia/Yekaterinburg',
  'FLE Standard Time'                                                 => 'Europe/Helsinki',
  'FLE'                                                               => 'Europe/Helsinki',
  'Fiji Standard Time'                                                => 'Pacific/Fiji',
  'Fiji'                                                              => 'Pacific/Fiji',
  'GFT Standard Time'                                                 => 'Europe/Athens',
  'GFT'                                                               => 'Europe/Athens',
  'GMT Standard Time'                                                 => 'Europe/London',
  'GMT'                                                               => 'Europe/London',
  'GTB Standard Time'                                                 => 'Europe/Athens',
  'GTB'                                                               => 'Europe/Athens',
  'Georgian Standard Time'                                            => 'Asia/Tbilisi',
  'Greenland Standard Time'                                           => 'America/Godthab',
  'Hawaiian Standard Time'                                            => 'Pacific/Honolulu',
  'Hawaiian'                                                          => 'Pacific/Honolulu',
  'India Standard Time'                                               => 'Asia/Calcutta',
  'India'                                                             => 'Asia/Calcutta',
  'Iran Standard Time'                                                => 'Asia/Tehran',
  'Iran'                                                              => 'Asia/Tehran',
  'Israel Standard Time'                                              => 'Asia/Jerusalem',
  'Israel'                                                            => 'Asia/Jerusalem',
  'Jordan Standard Time'                                              => 'Asia/Amman',
  'Kamchatka Standard Time'                                           => 'Asia/Kamchatka',
  'Korea Standard Time'                                               => 'Asia/Seoul',
  'Korea'                                                             => 'Asia/Seoul',
  'Magadan Standard Time'                                             => 'Asia/Magadan',
  'Mauritius Standard Time'                                           => 'Indian/Mauritius',
  'Mexico Standard Time 2'                                            => 'America/Chihuahua',
  'Mexico Standard Time'                                              => 'America/Mexico_City',
  'Mexico'                                                            => 'America/Mexico_City',
  'Mid-Atlantic Standard Time'                                        => 'Atlantic/South_Georgia',
  'Mid-Atlantic'                                                      => 'Atlantic/South_Georgia',
  'Middle East Standard Time'                                         => 'Asia/Beirut',
  'Montevideo Standard Time'                                          => 'America/Montevideo',
  'Morocco Standard Time'                                             => 'Africa/Casablanca',
  'Mountain Standard Time (Mexico)'                                   => 'America/Chihuahua',
  'Mountain Standard Time'                                            => 'America/Denver',
  'Mountain'                                                          => 'America/Denver',
  'Myanmar Standard Time'                                             => 'Asia/Rangoon',
  'N. Central Asia Standard Time'                                     => 'Asia/Novosibirsk',
  'Namibia Standard Time'                                             => 'Africa/Windhoek',
  'Nepal Standard Time'                                               => 'Asia/Katmandu',
  'New Zealand Standard Time'                                         => 'Pacific/Auckland',
  'New Zealand'                                                       => 'Pacific/Auckland',
  'Newfoundland Standard Time'                                        => 'America/St_Johns',
  'Newfoundland'                                                      => 'America/St_Johns',
  'North Asia East Standard Time'                                     => 'Asia/Irkutsk',
  'North Asia Standard Time'                                          => 'Asia/Krasnoyarsk',
  'Pacific SA Standard Time'                                          => 'America/Santiago',
  'Pacific SA'                                                        => 'America/Santiago',
  'Pacific Standard Time (Mexico)'                                    => 'America/Tijuana',
  'Pacific Standard Time'                                             => 'America/Los_Angeles',
  'Pacific'                                                           => 'America/Los_Angeles',
  'Pakistan Standard Time'                                            => 'Asia/Karachi',
  'Paraguay Standard Time'                                            => 'America/Asuncion',
  'Prague Bratislava'                                                 => 'Europe/Prague',
  'Romance Standard Time'                                             => 'Europe/Paris',
  'Romance'                                                           => 'Europe/Paris',
  'Russian Standard Time'                                             => 'Europe/Moscow',
  'Russian'                                                           => 'Europe/Moscow',
  'SA Eastern Standard Time'                                          => 'America/Cayenne',
  'SA Eastern'                                                        => 'America/Cayenne',
  'SA Pacific Standard Time'                                          => 'America/Bogota',
  'SA Pacific'                                                        => 'America/Bogota',
  'SA Western Standard Time'                                          => 'America/Guyana',
  'SA Western'                                                        => 'America/Guyana',
  'SE Asia Standard Time'                                             => 'Asia/Bangkok',
  'SE Asia'                                                           => 'Asia/Bangkok',
  'Samoa Standard Time'                                               => 'Pacific/Apia',
  'Samoa'                                                             => 'Pacific/Apia',
  'Saudi Arabia Standard Time'                                        => 'Asia/Riyadh',
  'Saudi Arabia'                                                      => 'Asia/Riyadh',
  'Singapore Standard Time'                                           => 'Asia/Singapore',
  'Singapore'                                                         => 'Asia/Singapore',
  'South Africa Standard Time'                                        => 'Africa/Harare',
  'South Africa'                                                      => 'Africa/Harare',
  'Sri Lanka Standard Time'                                           => 'Asia/Colombo',
  'Sri Lanka'                                                         => 'Asia/Colombo',
  'Sydney Standard Time'                                              => 'Australia/Sydney',
  'Syria Standard Time'                                               => 'Asia/Damascus',
  'Taipei Standard Time'                                              => 'Asia/Taipei',
  'Taipei'                                                            => 'Asia/Taipei',
  'Tasmania Standard Time'                                            => 'Australia/Hobart',
  'Tasmania'                                                          => 'Australia/Hobart',
  'Tokyo Standard Time'                                               => 'Asia/Tokyo',
  'Tokyo'                                                             => 'Asia/Tokyo',
  'Tonga Standard Time'                                               => 'Pacific/Tongatapu',
  'US Eastern Standard Time'                                          => 'America/Indianapolis',
  'US Eastern'                                                        => 'America/Indianapolis',
  'US Mountain Standard Time'                                         => 'America/Phoenix',
  'US Mountain'                                                       => 'America/Phoenix',
  'US-Alaskan'                                                        => 'America/Anchorage',
  'US-Arizona'                                                        => 'America/Phoenix',
  'US-Central'                                                        => 'America/Chicago',
  'US-Eastern'                                                        => 'America/New_York',
  'US-Mountain'                                                       => 'America/Denver',
  'US-Pacific'                                                        => 'America/Los_Angeles',
  'US/Alaskan'                                                        => 'America/Anchorage',
  'US/Arizona'                                                        => 'America/Phoenix',
  'US/Central'                                                        => 'America/Chicago',
  'US/Eastern'                                                        => 'America/New_York',
  'US/Mountain'                                                       => 'America/Denver',
  'US/Pacific'                                                        => 'America/Los_Angeles',
  'Ulaanbaatar Standard Time'                                         => 'Asia/Ulaanbaatar',
  'Venezuela Standard Time'                                           => 'America/Caracas',
  'Vladivostok Standard Time'                                         => 'Asia/Vladivostok',
  'Vladivostok'                                                       => 'Asia/Vladivostok',
  'W. Australia Standard Time'                                        => 'Australia/Perth',
  'W. Australia'                                                      => 'Australia/Perth',
  'W. Central Africa Standard Time'                                   => 'Africa/Luanda',
  'W. Europe Standard Time'                                           => 'Europe/Berlin',
  'W. Europe'                                                         => 'Europe/Berlin',
  'Warsaw'                                                            => 'Europe/Warsaw',
  'West Asia Standard Time'                                           => 'Asia/Karachi',
  'West Asia'                                                         => 'Asia/Karachi',
  'West Pacific Standard Time'                                        => 'Pacific/Guam',
  'West Pacific'                                                      => 'Pacific/Guam',
  'Western Brazilian Standard Time'                                   => 'America/Rio_Branco',
  'Yakutsk Standard Time'                                             => 'Asia/Yakutsk',
  'Yakutsk'                                                           => 'Asia/Yakutsk',
  '(GMT-12.00) International Date Line West'                          => 'Etc/GMT-12',
  '(GMT-11.00) Midway Island / Samoa'                                 => 'Pacific/Midway',
  '(GMT-10.00) Hawaii'                                                => 'Pacific/Honolulu',
  '(GMT-09.00) Alaska'                                                => 'America/Anchorage',
  '(GMT-08.00) Pacific Time (US & Canada)'                            => 'America/Los_Angeles',
  '(GMT-08.00) Tijuana / Baja California'                             => 'America/Tijuana',
  '(GMT-07.00) Arizona'                                               => 'America/Phoenix',
  '(GMT-07.00) Chihuahua / La Paz / Mazatlan - New'                   => 'America/Chihuahua',
  '(GMT-07.00) Chihuahua / La Paz / Mazatlan - Old'                   => 'America/Chihuahua',
  '(GMT-07.00) Mountain Time (US & Canada)'                           => 'America/Denver',
  '(GMT-06.00) Central America'                                       => 'America/Chicago',
  '(GMT-06.00) Central Time (US & Canada)'                            => 'America/Chicago',
  '(GMT-06.00) Guadalajara / Mexico City / Monterrey - New'           => 'America/Mexico_City',
  '(GMT-06.00) Guadalajara / Mexico City / Monterrey - Old'           => 'America/Mexico_City',
  '(GMT-06.00) Saskatchewan'                                          => 'America/Belize',
  '(GMT-05.00) Bogota / Lima / Quito / Rio Branco'                    => 'America/Bogota',
  '(GMT-05.00) Eastern Time (US & Canada)'                            => 'America/New_York',
  '(GMT-05.00) Indiana (East)'                                        => 'America/Indiana/Indianapolis',
  '(GMT-04.00) Atlantic Time (Canada)'                                => 'America/Glace_Bay',
  '(GMT-04.00) Caracas / La Paz'                                      => 'America/Caracas',
  '(GMT-04.00) Manaus'                                                => 'America/Manaus',
  '(GMT-04.00) Santiago'                                              => 'America/Santiago',
  '(GMT-03.30) Newfoundland'                                          => 'America/St_Johns',
  '(GMT-03.00) Brasilia'                                              => 'America/Sao_Paulo',
  '(GMT-03.00) Buenos Aires / Georgetown'                             => 'America/Argentina/Buenos_Aires',
  '(GMT-03.00) Greenland'                                             => 'America/Godthab',
  '(GMT-03.00) Montevideo'                                            => 'America/Montevideo',
  '(GMT-02.00) Mid-Atlantic'                                          => 'America/Noronha',
  '(GMT-01.00) Azores'                                                => 'Atlantic/Azores',
  '(GMT-01.00) Cape Verde Is.'                                        => 'Atlantic/Cape_Verde',
  '(GMT) Casablanca / Monrovia / Reykjavik'                           => 'Africa/Casablanca',
  '(GMT) Greenwich Mean Time - Dublin / Edinburgh / Lisbon / London'  => 'Etc/UTC',
  '(GMT+01.00) Amsterdam / Berlin / Bern / Rome / Stockholm / Vienna' => 'Europe/Amsterdam',
  '(GMT+01.00) Belgrade / Bratislava / Budapest / Ljubljana / Prague' => 'Europe/Belgrade',
  '(GMT+01.00) Brussels / Copenhagen / Madrid / Paris'                => 'Europe/Brussels',
  '(GMT+01.00) Sarajevo / Skopje / Warsaw / Zagreb'                   => 'Europe/Warsaw',
  '(GMT+01.00) West Central Africa'                                   => 'Africa/Algiers',
  '(GMT+02.00) Amman'                                                 => 'Asia/Amman',
  '(GMT+02.00) Athens / Bucharest / Istanbul'                         => 'Europe/Athens',
  '(GMT+02.00) Beirut'                                                => 'Asia/Beirut',
  '(GMT+02.00) Cairo'                                                 => 'Africa/Cairo',
  '(GMT+02.00) Harare / Pretoria'                                     => 'Africa/Harare',
  '(GMT+02.00) Helsinki / Kyiv / Riga / Sofia / Tallinn / Vilnius'    => 'Europe/Helsinki',
  '(GMT+02.00) Jerusalem'                                             => 'Asia/Jerusalem',
  '(GMT+02.00) Minsk'                                                 => 'Europe/Minsk',
  '(GMT+02.00) Windhoek'                                              => 'Africa/Windhoek',
  '(GMT+03.00) Baghdad'                                               => 'Asia/Baghdad',
  '(GMT+03.00) Kuwait / Riyadh'                                       => 'Asia/Kuwait',
  '(GMT+03.00) Moscow / St. Petersburg / Volgograd'                   => 'Europe/Moscow',
  '(GMT+03.00) Nairobi'                                               => 'Africa/Nairobi',
  '(GMT+03.00) Tbilisi'                                               => 'Asia/Tbilisi',
  '(GMT+03.30) Tehran'                                                => 'Asia/Tehran',
  '(GMT+04.00) Abu Dhabi / Muscat'                                    => 'Asia/Dubai',
  '(GMT+04.00) Baku'                                                  => 'Asia/Baku',
  '(GMT+04.00) Yerevan'                                               => 'Asia/Yerevan',
  '(GMT+04.30) Kabul'                                                 => 'Asia/Kabul',
  '(GMT+05.00) Ekaterinburg'                                          => 'Asia/Yekaterinburg',
  '(GMT+05.00) Islamabad / Karachi / Tashkent'                        => 'Asia/Karachi',
  '(GMT+05.30) Chennai / Kolkata / Mumbai / New Delhi'                => 'Asia/Kolkata',
  '(GMT+05.30) Sri Jayawardenepura'                                   => 'Asia/Colombo',
  '(GMT+05.45) Kathmandu'                                             => 'Asia/Kathmandu',
  '(GMT+06.00) Almaty / Novosibirsk'                                  => 'Asia/Almaty',
  '(GMT+06.00) Astana / Dhaka'                                        => 'Asia/Dhaka',
  '(GMT+06.30) Yangon (Rangoon)'                                      => 'Asia/Rangoon',
  '(GMT+07.00) Bangkok / Hanoi / Jakarta'                             => 'Asia/Bangkok',
  '(GMT+07.00) Krasnoyarsk'                                           => 'Asia/Krasnoyarsk',
  '(GMT+08.00) Beijing / Chongqing / Hong Kong / Urumqi'              => 'Asia/Shanghai',
  '(GMT+08.00) Irkutsk / Ulaan Bataar'                                => 'Asia/Irkutsk',
  '(GMT+08.00) Kuala Lumpur / Singapore'                              => 'Asia/Kuala_Lumpur',
  '(GMT+08.00) Perth'                                                 => 'Australia/Perth',
  '(GMT+08.00) Taipei'                                                => 'Asia/Taipei',
  '(GMT+09.00) Osaka / Sapporo / Tokyo'                               => 'Asia/Tokyo',
  '(GMT+09.00) Seoul'                                                 => 'Asia/Seoul',
  '(GMT+09.00) Yakutsk'                                               => 'Asia/Yakutsk',
  '(GMT+09.30) Adelaide'                                              => 'Australia/Adelaide',
  '(GMT+09.30) Darwin'                                                => 'Australia/Darwin',
  '(GMT+10.00) Brisbane'                                              => 'Australia/Brisbane',
  '(GMT+10.00) Canberra / Melbourne / Sydney'                         => 'Australia/Sydney',
  '(GMT+10.00) Guam / Port Moresby'                                   => 'Pacific/Guam',
  '(GMT+10.00) Hobart'                                                => 'Australia/Hobart',
  '(GMT+10.00) Vladivostok'                                           => 'Asia/Vladivostok',
  '(GMT+11.00) Magadan / Solomon Is. / New Caledonia'                 => 'Asia/Magadan',
  '(GMT+12.00) Auckland / Wellington'                                 => 'Pacific/Auckland',
  '(GMT+12.00) Fiji / Kamchatka / Marshall Is.'                       => 'Pacific/Fiji',
  "(GMT+13.00) Nuku'alofa"                                            => 'Pacific/Tongatapu',
);

our %OtherLinksReversed;

foreach my $OtherLink (keys %OtherLinks) {
  push @{$OtherLinksReversed{$OtherLinks{$OtherLink}}}, $OtherLink;
}

=head1 SUBROUTINES/METHODS

=head2 $Class->GetTimeZone(%Args)

Args:

   TZID - zone name
   StandardTzOffsetTo - offset

Pick the matching timezone with the highest population size to the offset
if the zone name isn't known.

Returns a DateTime::TimeZone object

=cut

sub GetTimeZone {
  my ($Class, %Args) = @_;

  # can we short circuit {{{

  if ($Args{TZID}) {
    my $Name = $OtherLinks{$Args{TZID}}
      ? $OtherLinks{$Args{TZID}}
      : $Args{TZID};

    my $TimeZone = eval {DateTime::TimeZone->new(name => $Name)};

    if ($TimeZone and $TimeZone->is_olson()) {
      return $TimeZone->name();
    }
  }

  return '' unless exists $Args{StandardTzOffsetTo};

  # }}}

  # get set of timezones for provided standard offset {{{

  my $Now    = DateTime->now()->strftime("%Y%m%dT%H%M%S");
  my $Time   = DateTime::Format::ISO8601->parse_datetime(($Args{Time} || $Now))->epoch();
  my $HasDST = $Args{DaylightTzOffsetTo} ? 'Y' : 'N';

  return '' unless exists $ZonesByOffset->{$Args{StandardTzOffsetTo}}{$HasDST};

  my @TimeZones;

  foreach my $Range (reverse @{$ZonesByOffset->{$Args{StandardTzOffsetTo}}{$HasDST}}) {
    if ($Range->[0] <= $Time) {
      @TimeZones = @{$Range->[1]};
      last;
    }
  }

  return '' unless @TimeZones;

  # }}}

  if ($Args{TZID} and ($Args{TZID} =~ /\w/)) {
    # try to match provided TZID with Olson timezones {{{

    my %TimeZoneEndings;

    foreach my $TimeZone (@TimeZones) {
      my (@TimeZoneParts) = split /[^a-z0-9\+\-\_]+/i, $TimeZone;
      $TimeZoneEndings{$TimeZoneParts[-1]} = $TimeZone;
    }

    my (@TZIDParts) = reverse split /[^a-z0-9\+\-\_]+/i, $Args{TZID};

    my %Distances;

    foreach my $TZIDPart (@TZIDParts) {
      foreach my $TimeZoneEnding (keys %TimeZoneEndings) {
        my $Distance = distance(lc($TZIDPart), lc($TimeZoneEnding));

        if ($Distance == 0) {
          return $TimeZoneEndings{$TimeZoneEnding};
        }

        my $MaxLength = (length($TZIDPart) > length($TimeZoneEnding))
          ? length($TZIDPart)
          : length($TimeZoneEnding);

        if ($Distance < int($MaxLength/2)) {
          $Distances{$Distance}{$TimeZoneEndings{$TimeZoneEnding}} = 1;
        }
      }
    }

    # }}}

    # try to match provided TZID with links {{{

    foreach my $TimeZone (@TimeZones) {
      next unless @{$OtherLinksReversed{$TimeZone} || []};

      foreach my $OtherLink (@{$OtherLinksReversed{$TimeZone}}) {
        my $Distance = distance(lc($Args{TZID}), lc($OtherLink));

        if ($Distance == 0) {
          return $TimeZone;
        }

        my $MaxLength = (length($Args{TZID}) > length($OtherLink))
          ? length($Args{TZID})
          : length($OtherLink);

        if ($Distance < int($MaxLength/2)) {
          $Distances{$Distance}{$TimeZone} = 1;
        }
      }
    }

    # }}}

    if (%Distances) {
      my ($Shortest) = sort { $a <=> $b } keys %Distances;

      # @TimeZones is sorted by population size, so in a tie, biggest population wins
      foreach my $TimeZone (@TimeZones) {
        return $TimeZone if $Distances{$Shortest}{$TimeZone};
      }
    }
  }

  # damn, let's fallback {{{

  my ($Etc) = grep { m{^Etc/} } @TimeZones;
  return $Etc if $Etc;

  # @TimeZones is sorted by population size
  return $TimeZones[0];

  # }}}
}

=head2 $Class->GetVTimeZone($TimeZone)

Returns a Data::ICal::TimeZone object for the named zone

=cut

sub GetVTimeZone {
  my ($Class, $TimeZone) = @_;

  return '' unless $TimeZone;
  return '' unless $RulesByZone->{$TimeZone};

  my $TZ = Data::ICal::TimeZone->new( timezone => $TimeZone );

  return $TZ->definition();
}

=head1 LICENSE AND COPYRIGHT

Copyright 2015 Bron Gondwana.

This program is free software; you can redistribute it and/or modify it
under the terms of the the Artistic License (2.0). You may obtain a
copy of the full license at:

L<http://www.perlfoundation.org/artistic_license_2_0>

Any use, modification, and distribution of the Standard or Modified
Versions is governed by this Artistic License. By using, modifying or
distributing the Package, you accept this license. Do not use, modify,
or distribute the Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made
by someone other than you, you are nevertheless required to ensure that
your Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service
mark, tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge
patent license to make, have made, use, offer to sell, sell, import and
otherwise transfer the Package with respect to any patent claims
licensable by the Copyright Holder that are necessarily infringed by the
Package. If you institute patent litigation (including a cross-claim or
counterclaim) against any party alleging that the Package constitutes
direct or contributory patent infringement, then this Artistic License
to you shall terminate on the date that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


=cut

1; # End of ME::CalDAVTalk::TimeZone
};

}

sub Init {
  %DaysOfWeek = (
    1 => 'SU',
    2 => 'MO',
    3 => 'TU',
    4 => 'WE',
    5 => 'TH',
    6 => 'FR',
    7 => 'SA',
  );

  unless ($ARGV[0]) {
    die "usage: $0 <path/to/timezones-raw.js>\n";
  }

  unless (-f '/home/mod_perl/hm/utils/oneoff/timezone_populations.pl') {
    die "Error: Timezone population data not found. Generate with utils/GenerateTimeZonePopulations.pl\n";
  }

  require '/home/mod_perl/hm/utils/oneoff/timezone_populations.pl';

  open my $Fh, '<', $ARGV[0]
    or die "Error opening $ARGV[0] ($!)";

  my $JSON = do {local $/; <$Fh>};

  unless (($JSON || '') =~ /O.TimeZone/s) {
    die 'No timezone definitions found';
  }

  foreach my $Part ($JSON =~ /O.TimeZone.load\((.*?)\);/smg) {
    my $Definitions = decode_json($Part);

    @Links{keys %{$Definitions->{link}}}  = values %{$Definitions->{link}};
    @Rules{keys %{$Definitions->{rules}}} = values %{$Definitions->{rules}};
    @Zones{keys %{$Definitions->{zones}}} = values %{$Definitions->{zones}};
  }
}

sub MapZones {
  foreach my $StandardTzOffset (keys %ZoneRuleMapping) {
    foreach my $RuleName (keys %{$ZoneRuleMapping{$StandardTzOffset}}) {
      foreach my $ZoneName (keys %{$ZoneRuleMapping{$StandardTzOffset}{$RuleName}}) {
        my $NewDaylightTzOffset;

        if ($RuleMapping{$RuleName}{Daylight}{DaylightTzOffset}) {
          my $StandardHours    = int($StandardTzOffset / 100);
          my $StandardMinutes  = int(abs($StandardTzOffset) % 100);
          my $DaylightTzOffset = $RuleMapping{$RuleName}{Daylight}{DaylightTzOffset};
          my $DaylightHours    = int($DaylightTzOffset / 100);
          my $DaylightMinutes  = int(abs($DaylightTzOffset) % 100);

          my ($NewHours, $NewMinutes);

          if ($StandardTzOffset < 0) {
            $NewHours   = $StandardHours + $DaylightHours;
            $NewMinutes = -$StandardMinutes + $DaylightMinutes;

            if ($StandardMinutes < $NewMinutes) {
              $NewHours++;
            }

            $NewDaylightTzOffset = sprintf('%s%04d',
                ($NewHours < 0 ? '-' : '+'),
                abs($NewHours * 100)
                  + abs($NewMinutes)
            );
          }
          else {
            $NewHours   = $StandardHours + $DaylightHours;
            $NewMinutes = ($StandardMinutes + $DaylightMinutes) % 60;

            if (($StandardMinutes + $DaylightMinutes) >= 60) {
              $NewHours++;
            }

            $NewDaylightTzOffset = sprintf('%+05d',
                ($NewHours * 100)
                  + $NewMinutes
            );
          }
        }

        $RulesByZone{$ZoneName} = {
          StandardTzOffset => $StandardTzOffset,
          ($RuleMapping{$RuleName}{Standard}{RRule}
            ? (StandardRRule => $RuleMapping{$RuleName}{Standard}{RRule})
            : ()),
          ($NewDaylightTzOffset
            ? (DaylightTzOffset => $NewDaylightTzOffset)
            : ()),
          ($RuleMapping{$RuleName}{Daylight}{RRule}
            ? (DaylightRRule => $RuleMapping{$RuleName}{Daylight}{RRule})
            : ()),
        }
      }
    }
  }
}

sub ParseRules {
  foreach my $RuleName (sort keys %Rules) {
    foreach my $RuleEntry (reverse @{$Rules{$RuleName}}) {
      # Rules format:
      # 0: start year
      # 1: end year
      # 2: month
      # 3: date (or 0 for last day of month)
      # 4: day (0 for none, +/-1-7 for next/prev sun-sat offset against date)
      # 5: hour
      # 6: minute
      # 7: second
      # 8: utc=0/local=1/wall=2
      # 9: offset in seconds
      # 10: suffix
      # e.g. [ 1987, 2006, 4, 3, 0, 0, 2, 0, 2, 3600, 'BST' ]

      my $Year  = $RuleEntry->[0] or die "Invalid year for $RuleName";
      my $Month = ($RuleEntry->[2] || 0) + 1;
      my $RRule = "FREQ=YEARLY;BYMONTH=$Month";

      next if $RuleEntry->[0] eq ($RuleEntry->[1] || '');

      if ($RuleEntry->[4]) {
        # day offset against date
        my $Day = $DaysOfWeek{abs($RuleEntry->[4])}
          or die "Invalid day of week $RuleEntry->[4]";

        my $Nth = "";
        if ($RuleEntry->[3]) {
          my $Date = DateTime->new(
            year  => $Year,
            month => $Month,
            day   => $RuleEntry->[3],
          );

          my $Direction = $RuleEntry->[4] < 0 ? -1 : 1;

          # converting incmoing (1-7 sun-sat) to datetime (1-7 mon-sun)
          my $Target = (abs($RuleEntry->[4]) - 1);
          $Target = 0 if $Target == 7;

          $Date->add(days => $Direction * (($Date->dow - $Target) % 7));

          my $StartDay = $Date->day;
          $Nth = 0;
          while ($Date->day <= $StartDay) {
            $Nth++;
            $Date->subtract(days => 7);
          }
        }

        if ($RuleEntry->[4] < 0) {
          $Nth ||= 1;
          $RRule .= ";BYDAY=-$Nth$Day";
        }
        else {
          $RRule .= ";BYDAY=$Nth$Day";
        }
      }

      elsif ($RuleEntry->[3]) {
        # no day, so use specific date
        my $Date = DateTime->new(
          year  => $Year,
          month => $Month,
          day   => $RuleEntry->[3],
        )->day();

        $RRule .= ";BYMONTHDAY=$Date";
      }

      my $Type = $RuleEntry->[-2]
        ? 'Daylight'
        : 'Standard';

      next if exists $RuleMapping{$RuleName}{$Type};

      my $DaylightTzOffset;

      if ($RuleEntry->[-2]) {
        $DaylightTzOffset = sprintf('%04d',
          (int($RuleEntry->[-2] / 3600) * 100)
            + int($RuleEntry->[-2] % 3600 / 60)
        );
      }

      $RuleMapping{$RuleName}{$Type} = {
        RRule                 => $RRule,
        ($DaylightTzOffset
          ? (DaylightTzOffset => $DaylightTzOffset)
          : ()),
      };

      last if exists($RuleMapping{$RuleName}{Daylight}) and exists($RuleMapping{$RuleName}{Standard});
    }
  }
}

sub ParseZones {
  # setup %ZonesByOffset {{{

  my %RangeByOffset;

  foreach my $ZoneName (keys %Zones) {
    my $Start = 0;

    foreach my $ZoneEntry (@{$Zones{$ZoneName}}) {
      my $StandardTzOffset = sprintf('%s%04d',
        ($ZoneEntry->[1] < 0 ? '-' : '+' ),
        (int(abs($ZoneEntry->[1]) / 3600) * 100)
          + int(abs($ZoneEntry->[1]) % 3600 / 60)
      );

      my $End    = $ZoneEntry->[0] / 1000;
      my $HasDST = ($ZoneEntry->[2] eq '-') ? 'N' : 'Y';

      $RangeByOffset{$StandardTzOffset}{$HasDST}{Times}{$Start} = 1;
      $RangeByOffset{$StandardTzOffset}{$HasDST}{Times}{($End || (2**31))} = 1;

      push @{$RangeByOffset{$StandardTzOffset}{$HasDST}{ZoneNames}{$ZoneName}}, {
        Start => $Start,
        End   => $End,
      };

      $Start = $ZoneEntry->[0] / 1000;
    }
  }

  foreach my $StandardTzOffset (keys %RangeByOffset) {
    foreach my $HasDST (keys %{$RangeByOffset{$StandardTzOffset}}) {
      my @SortedRangeTimes
        = sort { $a <=> $b }
            keys %{$RangeByOffset{$StandardTzOffset}{$HasDST}{Times}};

      my $PreviousStart = $SortedRangeTimes[0];

      my %TempZonesByOffset;

      RANGE:
      for (my $i = 0; $i < (@SortedRangeTimes - 1); $i++) {
        my $Start = $SortedRangeTimes[$i];
        my $End   = $SortedRangeTimes[$i+1];

        my %ZoneNames;

        foreach my $ZoneName (keys %{$RangeByOffset{$StandardTzOffset}{$HasDST}{ZoneNames}}) {
          foreach my $ZoneEntry (@{$RangeByOffset{$StandardTzOffset}{$HasDST}{ZoneNames}{$ZoneName}}) {
            if ($ZoneEntry->{Start} <= $Start) {
              if (($ZoneEntry->{End} >= $End) or ($ZoneEntry->{End} == 0)) {
                $ZoneNames{$ZoneName} = 1;
              }
            }
          }
        }

        if (exists $TempZonesByOffset{$PreviousStart}) {
          next RANGE if eq_deeply($TempZonesByOffset{$PreviousStart}, [sort keys %ZoneNames]);
        }

        $TempZonesByOffset{$Start} = [sort keys %ZoneNames];
        $PreviousStart             = $Start;
      }

      foreach my $Start (sort { $a <=> $b } keys %TempZonesByOffset) {
        my @SortedTimeZones
          = grep { ($_ ne 'Etc/GMT') and ($_ ne 'Etc/UCT') }
              sort { ($TimeZonesByPopulation->{$b} || 0) <=> ($TimeZonesByPopulation->{$a} || 0) }
                @{$TempZonesByOffset{$Start}};

        push @{$ZonesByOffset{$StandardTzOffset}{$HasDST}}, [$Start, \@SortedTimeZones];
      }
    }
  }

  # }}}

  # setup %ZoneRuleMapping {{{

  foreach my $ZoneName (sort keys %Zones) {
      # until we actually want a complete VTIMEZONE, choose the last zone entry
      my $ZoneEntry        = $Zones{$ZoneName}[-1];
      my $RuleName         = $ZoneEntry->[2];
      my $StandardTzOffset = sprintf('%s%04d',
        ($ZoneEntry->[1] < 0 ? '-' : '+' ),
        (int(abs($ZoneEntry->[1]) / 3600) * 100)
          + int(abs($ZoneEntry->[1]) % 3600 / 60)
      );

      $ZoneRuleMapping{$StandardTzOffset}{$RuleName}{$ZoneName} = 1;
  }

  # }}}
}
