#!/usr/bin/python3
"""Run one cdx attempt, capture its workspace, and upload the bounded result."""
from __future__ import annotations

import os
import re
import subprocess
import sys
from pathlib import Path

COMMIT = re.compile(r"^[0-9a-f]{40,64}$")
RESULT_FAILURE = 125
WORKSPACE = Path(os.environ.get("CDX_WORKSPACE", "/workspace"))
RESULT_DIR = Path(os.environ.get("CDX_RESULT_DIR", "/result"))
UPLOADER = os.environ.get("CDX_RESULT_UPLOADER", "/usr/local/bin/cdx-result-upload")


def call(argv: list[str], *, check: bool = True) -> subprocess.CompletedProcess:
    completed = subprocess.run(argv, check=False)
    if check and completed.returncode:
        raise RuntimeError(f"{argv[0]} exited {completed.returncode}")
    return completed


def git(*args: str) -> subprocess.CompletedProcess:
    return call([
        "/usr/bin/git", "-c", f"safe.directory={WORKSPACE}", "-C", str(WORKSPACE), *args,
    ])


def main() -> int:
    if len(sys.argv) < 4 or sys.argv[2] != "--" or not COMMIT.fullmatch(sys.argv[1]):
        raise RuntimeError("usage: cdx-k3s-worker INPUT_COMMIT -- AGENT [ARGS...]")
    input_commit = sys.argv[1]
    agent = call(sys.argv[3:], check=False)
    git("add", "-A", "--ignore-errors")
    git(
        "-c", "user.name=cdx-offload", "-c", "user.email=cdx-offload@local",
        "commit", "--allow-empty", "-m", "cdx-offload-result",
    )
    bundle = RESULT_DIR / "result.bundle"
    temporary = RESULT_DIR / "result.bundle.tmp"
    git("bundle", "create", str(temporary), "HEAD", f"^{input_commit}")
    temporary.replace(bundle)
    call([UPLOADER, str(bundle)])
    return agent.returncode


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        print(f"cdx-k3s-worker: {exc}", file=sys.stderr)
        raise SystemExit(RESULT_FAILURE)
