#!/usr/bin/env python3
#
# html-locks.py - inspect and clean up HTML build 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! :-)
#
"""Inspect or remove HTML build markers in the current repository."""

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

sys.dont_write_bytecode = True
import html_cache


VERSION = "1.1.0 2026-12-04"
CACHE = Path(".quick-html-cache")


def markers():
    """Find markers without traversing symlinked directories."""
    try:
        info = CACHE.lstat()
    except FileNotFoundError:
        return []
    if not stat.S_ISDIR(info.st_mode):
        raise OSError(f"{CACHE} is not a directory")

    def fail(error):
        raise error

    found = []
    for root, directories, files in os.walk(CACHE, onerror=fail, followlinks=False):
        for name in directories:
            path = Path(root) / name
            if path.is_symlink() and not name.endswith(".sig.pending"):
                raise OSError(f"symlinked cache directory is unsupported: {path}")
        for name in directories + files:
            if name.endswith(".sig.pending"):
                found.append(Path(root) / name)
    return sorted(found)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-V", "--version", action="version", version=VERSION)
    parser.add_argument("action", choices=("check", "cleanup"))
    args = parser.parse_args()
    try:
        found = markers()
        if args.action == "check":
            if found:
                print("HTML build markers found:")
                for marker in found:
                    print(marker)
                print("CAUTION: Markers may belong to active builds or signature commands.")
                print("After stopping all such commands and their converters, run make cleanup_locks.")
                return 1
            print("No HTML build markers found.")
            return 0

        print("CAUTION: Run cleanup only after all builds and signature commands have stopped,")
        print("including any converters still running after their parent exits.")
        for marker in found:
            output = marker.relative_to(CACHE).as_posix()[:-len(".sig.pending")]
            fd, record = html_cache.parent_directory(output)
            try:
                # Remove the record first so a surviving marker never exposes it.
                try:
                    os.unlink(record, dir_fd=fd)
                except FileNotFoundError:
                    pass
                os.unlink(record + ".pending", dir_fd=fd)
            finally:
                os.close(fd)
            print(f"Removed {marker} and its signature, if present.")
        return 0
    except (OSError, ValueError) as error:
        print(f"{Path(sys.argv[0]).name}: ERROR: {error}", file=sys.stderr)
        return 1


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