#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
"""Run tine from the checkout in tine/tine/ at the commit that tine/tine.lock.json pins.

    tine/bin/tine buck build //:image

tine/tine/ is a plain git checkout, not a submodule, so that this script can move it to the pinned
commit. When tine/tine/ is on a branch or has uncommitted changes, this script leaves it alone, so a
build picks up work on tine itself.
"""

import json
import os
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
CHECKOUT = ROOT / "tine/tine"
PINS = ROOT / "tine/tine.lock.json"
NAME = Path(sys.argv[0]).name


def git(*args: str, directory: Path = CHECKOUT) -> str:
    # subprocess.run() kills git with SIGKILL on KeyboardInterrupt, and git then can't clean up its lock files.
    proc = subprocess.Popen(["git", "-C", str(directory), *args], stdout=subprocess.PIPE, text=True)
    try:
        stdout, _ = proc.communicate()
    except BaseException:
        proc.terminate()
        proc.wait()
        raise
    if proc.returncode != 0:
        raise SystemExit(proc.returncode)
    return stdout.strip()


def git_ok(*args: str) -> bool:
    query = ["git", "-C", str(CHECKOUT), *args]
    return subprocess.run(query, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0


def pin(commit: str, ref: str) -> None:
    if not git_ok("cat-file", "-e", f"{commit}^{{commit}}"):
        git("fetch", "--quiet", "origin", ref)
    git("-c", "advice.detachedHead=false", "checkout", "--quiet", commit)


def developing() -> bool:
    # pin() leaves tine/tine/ on a detached HEAD without changes. A branch or uncommitted changes mean
    # that somebody works on tine in tine/tine/.
    return bool(git("status", "--porcelain")) or git_ok("symbolic-ref", "HEAD")


def main() -> None:
    spec = json.loads(PINS.read_text())["tine"]
    url, ref, commit = spec["repository"], spec["ref"], spec["commit"]

    if not (CHECKOUT / ".git").exists():
        git("clone", "--quiet", "--branch", ref, url, str(CHECKOUT), directory=ROOT)
        pin(commit, ref)
    elif git("rev-parse", "HEAD") != commit:
        if developing():
            print(f"{NAME}: building with tine/tine/ as it is, not the pinned {commit[:12]}", file=sys.stderr)
        else:
            pin(commit, ref)

    command = CHECKOUT / "bin/tine"
    try:
        os.execv(command, [str(command), *sys.argv[1:]])
    except OSError as error:
        raise SystemExit(f"{NAME}: cannot run {command}: {error}") from error


if __name__ == "__main__":
    main()
