#!/usr/bin/env python3
#
# restore-lastmod.py - restore timestamps from a trusted sitemap
#
# Copyright (c) 2026 by Landon Curt Noll.  All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright, this permission notice and text
# this comment, and the disclaimer below appear in all of the following:
#
#       supporting documentation
#       source copies
#       source works derived from this source
#       binaries derived from this source or from derived source
#
# LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
# EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
# chongo (Landon Curt Noll, http://www.isthe.com/chongo/index.html) /\oo/\
#
# Share and enjoy! :-)
#
"""Restore timestamps from a sitemap known to describe this checkout."""

import argparse
from datetime import datetime
import os
from pathlib import Path, PurePosixPath
import stat
import subprocess
import sys
from urllib.parse import unquote, urlsplit
import xml.etree.ElementTree as ET


VERSION = "1.0.3 2026-12-04"
SITEMAP_NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
SITE_HOST = "www.ioccc.org"


def git_paths(*args):
    """Return NUL-separated paths from Git, failing on any Git error."""
    result = subprocess.run(
        ["git", *args], check=True, stdout=subprocess.PIPE,
    )
    return {os.fsdecode(path) for path in result.stdout.split(b"\0") if path}


def sitemap_entries(sitemap):
    """Validate all URLs and dates before changing any filesystem timestamp."""
    root = ET.parse(sitemap).getroot()
    if root.tag != SITEMAP_NS + "urlset":
        raise ValueError("not a sitemap urlset")
    entries = {}
    for node in root.findall(SITEMAP_NS + "url"):
        loc = node.findtext(SITEMAP_NS + "loc")
        date = node.findtext(SITEMAP_NS + "lastmod")
        if not loc or not date:
            raise ValueError("sitemap entry is missing loc or lastmod")
        url = urlsplit(loc)
        if url.scheme != "https" or url.netloc != SITE_HOST or url.query or url.fragment:
            raise ValueError(f"unsupported sitemap URL: {loc}")
        path = unquote(url.path, errors="strict")
        if not path.startswith("/") or "\0" in path or "\\" in path:
            raise ValueError(f"invalid sitemap path: {loc}")
        name = path[1:]
        parts = name.split("/")
        if not name or any(part in ("", ".", "..") for part in parts):
            raise ValueError(f"invalid sitemap path: {loc}")
        timestamp = datetime.fromisoformat(date.replace("Z", "+00:00"))
        if timestamp.tzinfo is None:
            raise ValueError(f"lastmod lacks a timezone: {date}")
        if name in entries and entries[name] != timestamp.timestamp():
            raise ValueError(f"conflicting lastmod values: {name}")
        entries[name] = timestamp.timestamp()
    return entries


def restore(root_fd, name, timestamp):
    """Open each component without following symlinks, then update its mtime."""
    parts = PurePosixPath(name).parts
    directory = os.dup(root_fd)
    try:
        for component in parts[:-1]:
            next_directory = os.open(
                component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
                dir_fd=directory,
            )
            os.close(directory)
            directory = next_directory
        fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
        try:
            info = os.fstat(fd)
            if not stat.S_ISREG(info.st_mode):
                raise ValueError("not a regular file")
            # Do not unnecessarily alter a file already at the sitemap time.
            if info.st_mtime_ns != int(timestamp * 1_000_000_000):
                os.utime(fd, ns=(info.st_atime_ns, int(timestamp * 1_000_000_000)))
        finally:
            os.close(fd)
    finally:
        os.close(directory)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-V", "--version", action="version", version=VERSION)
    parser.parse_args()
    try:
        root = Path(subprocess.check_output(
            ["git", "rev-parse", "--show-toplevel"], text=True,
        ).strip())
        os.chdir(root)
        entries = sitemap_entries("sitemap.xml")
        tracked = git_paths("ls-files", "-z")
        # Inspect the index and worktree separately: their changes can cancel
        # each other when compared directly against HEAD.
        changed = git_paths("diff", "--name-only", "--no-renames", "-z", "--")
        changed |= git_paths("diff", "--cached", "--name-only", "--no-renames", "-z", "--")
        root_fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY)
    except (OSError, ValueError, ET.ParseError, subprocess.CalledProcessError) as error:
        print(f"restore-lastmod.py: ERROR: {error}", file=sys.stderr)
        return 1

    failed = False
    try:
        for name, timestamp in entries.items():
            # Missing files are always reported, even if Git also marks them deleted.
            if not os.path.lexists(name):
                print(f"restore-lastmod.py: Warning: missing file: {name}", file=sys.stderr)
                failed = True
                continue
            if name not in tracked or name in changed:
                print(f"restore-lastmod.py: Warning: skipped untracked or modified file: {name}", file=sys.stderr)
                failed = True
                continue
            try:
                restore(root_fd, name, timestamp)
            except (OSError, ValueError) as error:
                print(f"restore-lastmod.py: Warning: cannot restore {name}: {error}", file=sys.stderr)
                failed = True
    finally:
        os.close(root_fd)
    return int(failed)


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