#!/usr/bin/python3

# Author: Benjamin Drung <bdrung@ubuntu.com>

"""Test leap-seconds.list not being outdated."""

import datetime
import os
import pathlib
import re
import sys
import time
import unittest
import zoneinfo


def datetime_from_ntp_timestamp(ntp_timestamp: float) -> datetime.datetime:
    """Convert a NTP timestamp to datetime. NTP epoch starts at 1900-01-01."""
    ntp_epoch = datetime.datetime(1900, 1, 1, tzinfo=datetime.timezone.utc)
    return ntp_epoch + datetime.timedelta(seconds=ntp_timestamp)


def get_exipration_date(leap_second_file: pathlib.Path) -> datetime.datetime:
    """Get the expiration date of the given leap-seconds.list file."""
    content = leap_second_file.read_text()
    match = re.search(r"^#@\s*([0-9]+)\s*$", content, flags=re.MULTILINE)
    assert match is not None
    return datetime_from_ntp_timestamp(float(match.group(1)))


def get_now() -> datetime.datetime:
    """Get the current time (can be overridden by SOURCE_DATE_EPOCH)."""
    return datetime.datetime.fromtimestamp(
        int(os.environ.get("SOURCE_DATE_EPOCH", time.time())), tz=datetime.UTC
    )


class TestLeapSeconds(unittest.TestCase):
    """Test leap-seconds.list not being outdated."""

    def test_leap_seconds_not_expired(self) -> None:
        """Check that leap-seconds.list will not exire in the next four weeks."""
        in_four_weeks = get_now() + datetime.timedelta(days=28)
        checked = []
        for tzpath in zoneinfo.TZPATH:
            leap_second_file = pathlib.Path(tzpath) / "leap-seconds.list"
            if not leap_second_file.exists():
                continue
            with self.subTest(leap_second_file):
                checked.append(leap_second_file)
                self.assertLess(in_four_weeks, get_exipration_date(leap_second_file))
        self.assertNotEqual(checked, [])


def main() -> None:
    """Run unit tests in verbose mode."""
    argv = sys.argv.copy()
    argv.insert(1, "-v")
    unittest.main(argv=argv)


if __name__ == "__main__":
    main()
