#!/usr/bin/env python3
#
# html_cache.py - safely access HTML build records and markers
#
# 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! :-)
#
"""Safely access one quick HTML build record or its marker."""

import argparse
import os
from pathlib import Path
import secrets
import stat
import sys


VERSION = "1.0.3 2026-12-04"
DIR_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW


class CacheMiss(Exception):
    """A missing or stale record is not an internal error."""


def parent_directory(output, create=False):
    """Open every directory component without following symlinks."""
    parts = output.split("/")
    if not output or any(part in ("", ".", "..") for part in parts):
        raise ValueError(f"unsafe HTML path: {output}")
    fd = os.open(".", DIR_FLAGS)
    try:
        for component in [".quick-html-cache", *parts[:-1]]:
            if create:
                try:
                    os.mkdir(component, dir_fd=fd)
                except FileExistsError:
                    pass
            child = os.open(component, DIR_FLAGS, dir_fd=fd)
            os.close(fd)
            fd = child
        return fd, parts[-1] + ".sig"
    except OSError:
        os.close(fd)
        raise


def identity(fd):
    info = os.fstat(fd)
    return f"{info.st_dev}:{info.st_ino}"


def open_record(fd, record):
    """Open a regular signature without following a final symlink."""
    record_fd = os.open(record, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)
    if not stat.S_ISREG(os.fstat(record_fd).st_mode):
        os.close(record_fd)
        raise ValueError(f"not a regular signature: {record}")
    return record_fd


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-V", "--version", action="version", version=VERSION)
    parser.add_argument("action", choices=("lock", "unlock", "remove", "write", "current"))
    parser.add_argument("output", help="HTML path relative to the repository root")
    parser.add_argument("arguments", nargs=argparse.REMAINDER)
    args = parser.parse_args()
    fd = None
    try:
        if args.action == "lock":
            if args.arguments:
                raise ValueError("lock takes no additional arguments")
            fd, record = parent_directory(args.output, create=True)
            marker_fd = os.open(
                record + ".pending", os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
                0o666, dir_fd=fd,
            )
            os.close(marker_fd)
            print(identity(fd))
            return 0

        if not args.arguments:
            raise ValueError(f"{args.action} requires a directory identity")
        expected, *inputs = args.arguments
        try:
            fd, record = parent_directory(args.output)
        except FileNotFoundError:
            if args.action == "current":
                raise CacheMiss from None
            raise
        if expected != "-" and identity(fd) != expected:
            raise ValueError(f"cache directory changed while handling {args.output}")
        if args.action == "current":
            try:
                os.stat(record + ".pending", dir_fd=fd, follow_symlinks=False)
            except FileNotFoundError:
                pass
            else:
                if expected == "-":
                    raise CacheMiss
            try:
                record_fd = open_record(fd, record)
            except FileNotFoundError:
                raise CacheMiss from None
            with os.fdopen(record_fd, "r", encoding="ascii") as stream:
                record_time = os.fstat(stream.fileno()).st_mtime_ns
                content = stream.read()
            for name in inputs:
                try:
                    if os.stat(name).st_mtime_ns > record_time:
                        raise CacheMiss
                except FileNotFoundError:
                    raise CacheMiss from None
            # A writer may have acquired its marker while the record was read.
            if expected == "-":
                try:
                    os.stat(record + ".pending", dir_fd=fd, follow_symlinks=False)
                except FileNotFoundError:
                    pass
                else:
                    raise CacheMiss
            print(content, end="")
            return 0

        if expected == "-" or inputs:
            raise ValueError(f"invalid arguments for {args.action}")
        if args.action in ("unlock", "remove"):
            name = record + ".pending" if args.action == "unlock" else record
            try:
                os.unlink(name, dir_fd=fd)
            except FileNotFoundError:
                if args.action != "remove":
                    raise
            return 0

        temporary = record + ".tmp." + secrets.token_hex(12)
        marker = os.stat(record + ".pending", dir_fd=fd, follow_symlinks=False)
        temp_fd = os.open(
            temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
            0o600, dir_fd=fd,
        )
        try:
            with os.fdopen(temp_fd, "w", encoding="ascii") as stream:
                stream.write(sys.stdin.read())
                # Changes during generation must remain newer than the record.
                stream.flush()
                os.utime(stream.fileno(), ns=(marker.st_mtime_ns, marker.st_mtime_ns))
            os.replace(temporary, record, src_dir_fd=fd, dst_dir_fd=fd)
        finally:
            try:
                os.unlink(temporary, dir_fd=fd)
            except FileNotFoundError:
                pass
        return 0
    except CacheMiss:
        return 1
    except (OSError, UnicodeError, ValueError) as error:
        print(f"{Path(sys.argv[0]).name}: ERROR: {error}", file=sys.stderr)
        return 1
    finally:
        if fd is not None:
            os.close(fd)


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