#!/usr/bin/python3
"""Show or configure the local timezone without changing the clock or hardware RTC."""

import argparse
import datetime
import json
import os
from pathlib import Path
import re
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
from zoneinfo import ZoneInfo


def validate_zone(name, zoneinfo=Path("/usr/share/zoneinfo")):
    if not re.fullmatch(r"[A-Za-z0-9_+-]+(?:/[A-Za-z0-9_+-]+)*", name):
        raise ValueError("Use an IANA timezone such as America/New_York; paths and '..' are not allowed.")
    if not zoneinfo.is_dir():
        raise ValueError("Timezone data is missing. Install it with: sudo txpk --install tzdata")
    base = zoneinfo.resolve(strict=True)
    try:
        path = (base / name).resolve(strict=True)
    except FileNotFoundError as error:
        raise ValueError(f"Unknown timezone: {name}. Use sudo timezone-config --select to choose one.") from error
    if not path.is_relative_to(base) or not path.is_file():
        raise ValueError("The timezone must be a file inside /usr/share/zoneinfo.")
    with path.open("rb") as stream:
        if stream.read(4) != b"TZif":
            raise ValueError(f"{name} is not a timezone data file.")
        stream.seek(0)
        try:
            ZoneInfo.from_file(stream, key=name)
        except (ValueError, EOFError, struct.error) as error:
            raise ValueError(f"{name} contains invalid timezone data.") from error
    return zoneinfo / name


def snapshot(path):
    try:
        info = path.lstat()
    except FileNotFoundError:
        return None
    if stat.S_ISLNK(info.st_mode):
        return ("symlink", os.readlink(path), None)
    if stat.S_ISREG(info.st_mode):
        return ("file", path.read_bytes(), stat.S_IMODE(info.st_mode))
    raise ValueError(f"Refusing to replace {path}: expected a regular file or symlink.")


def write_snapshot(path, state):
    if state[0] == "symlink":
        path.symlink_to(state[1])
    else:
        with path.open("xb") as stream:
            stream.write(state[1])
            os.fchmod(stream.fileno(), state[2])
            stream.flush()
            os.fsync(stream.fileno())


def set_timezone(name, etc=Path("/etc"), zoneinfo=Path("/usr/share/zoneinfo")):
    if os.geteuid() != 0:
        raise ValueError("Use sudo timezone-config --select or sudo timezone-config AREA/CITY to change the timezone.")
    target = validate_zone(name, zoneinfo).absolute()
    paths = {key: etc / key for key in ("localtime", "timezone")}
    previous = {key: snapshot(path) for key, path in paths.items()}
    desired = {"localtime": ("symlink", str(target), None),
               "timezone": ("file", (name + "\n").encode(), 0o644)}
    if previous == desired:
        print(f"Timezone is already {name}; no files changed.")
        return None
    stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    backup = Path(tempfile.mkdtemp(prefix=f"tuxenix-timezone-backup-{stamp}-", dir=etc))
    absent = []
    for key, state in previous.items():
        if state is None:
            absent.append(key)
        else:
            write_snapshot(backup / key, state)
    (backup / "absent.json").write_text(json.dumps(absent) + "\n")
    staging = Path(tempfile.mkdtemp(prefix=".tuxenix-timezone-", dir=etc))
    replaced = []
    try:
        for key, state in desired.items():
            write_snapshot(staging / key, state)
        for key in ("timezone", "localtime"):
            os.replace(staging / key, paths[key])
            replaced.append(key)
        directory_fd = os.open(etc, os.O_RDONLY | os.O_DIRECTORY)
        try:
            os.fsync(directory_fd)
        finally:
            os.close(directory_fd)
    except OSError as error:
        try:
            for key in reversed(replaced):
                state = previous[key]
                if state is None:
                    paths[key].unlink()
                else:
                    restore = staging / (key + ".restore")
                    write_snapshot(restore, state)
                    os.replace(restore, paths[key])
        except OSError as rollback_error:
            raise OSError(f"Timezone update failed ({error}); restore also failed ({rollback_error}). Backup: {backup}") from error
        raise OSError(f"Timezone update failed; previous settings restored. Backup: {backup}. {error}") from error
    finally:
        shutil.rmtree(staging)
    print(f"Timezone set to {name}. Previous settings saved in {backup}")
    print("The clock and hardware RTC were not changed. Restart IceWM to refresh its clock display.")
    return backup


def show_timezone(etc=Path("/etc"), zoneinfo=Path("/usr/share/zoneinfo")):
    localtime = etc / "localtime"
    name = "custom /etc/localtime"
    try:
        name = str(localtime.resolve(strict=True).relative_to(zoneinfo.resolve(strict=True)))
    except (OSError, ValueError):
        if not localtime.exists():
            name = "not configured"
    print(f"Timezone: {name}")
    print("Local time: " + datetime.datetime.now().astimezone().isoformat(timespec="seconds"))
    print("UTC time:   " + datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"))
    if not zoneinfo.is_dir():
        print("Timezone data is missing. Install it with: sudo txpk --install tzdata")
    if os.environ.get("TZ"):
        print("Note: TZ is set in your environment and may override the system timezone for this session.")


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, epilog=(
        "Examples: timezone-config; sudo timezone-config --select; "
        "sudo timezone-config America/New_York. Choose your actual location, not a fixed UTC offset."))
    parser.add_argument("zone", nargs="?", help="IANA timezone name (requires sudo)")
    parser.add_argument("--select", action="store_true", help="choose a timezone interactively using tzselect (requires sudo)")
    args = parser.parse_args(argv)
    if args.select and args.zone:
        parser.error("use --select or a timezone name, not both")
    try:
        if not args.select and not args.zone:
            show_timezone()
            return 0
        if os.geteuid() != 0:
            raise ValueError("Run timezone changes with sudo.")
        name = args.zone
        if args.select:
            if not Path("/usr/share/zoneinfo/zone1970.tab").is_file():
                raise ValueError("Timezone data is missing. Install it with: sudo txpk --install tzdata")
            result = subprocess.run(["/usr/bin/tzselect"], stdout=subprocess.PIPE, text=True, check=False)
            if result.returncode:
                print("Timezone selection cancelled or failed; no settings changed.", file=sys.stderr)
                return 1
            name = result.stdout.strip()
        set_timezone(name)
        return 0
    except (OSError, ValueError, EOFError) as error:
        print(f"timezone-config: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
