#!/usr/bin/env python3
"""Run Factory from an ephemeral Git ref and publish the result ref."""
from __future__ import annotations
import json, os, re, subprocess, sys
from pathlib import Path

WORKSPACE=Path("/workspace/repo")
EXECUTION=re.compile(r"refs/heads/factory-exec/[0-9a-f]{24}")
RESULT=re.compile(r"refs/heads/factory-result/[0-9a-f]{24}")

def call(args: list[str], *, cwd: Path|None=None, check=True):
    result=subprocess.run(args,cwd=cwd,check=False)
    if check and result.returncode: raise RuntimeError(f"{args[0]} exited {result.returncode}")
    return result

def main()->int:
    url=os.environ["FACTORY_REPO_URL"]; execution=os.environ["FACTORY_EXECUTION_REF"]; result_ref=os.environ["FACTORY_RESULT_REF"]
    if not EXECUTION.fullmatch(execution) or not RESULT.fullmatch(result_ref): raise RuntimeError("invalid transport ref")
    invocation=json.loads(os.environ["FACTORY_INVOCATION_JSON"])
    if not isinstance(invocation,list) or not invocation or any(not isinstance(v,str) for v in invocation): raise RuntimeError("invalid Factory invocation")
    branch=execution.removeprefix("refs/heads/")
    call(["/usr/bin/git","clone","--single-branch","--branch",branch,"--",url,str(WORKSPACE)])
    call(["/usr/bin/git","config","user.name","Overdeck Factory"],cwd=WORKSPACE)
    call(["/usr/bin/git","config","user.email","factory@overdeck.invalid"],cwd=WORKSPACE)
    factory=call(["/opt/factory/bin/factory","--repo",str(WORKSPACE),*invocation],cwd=WORKSPACE,check=False)
    call(["/usr/bin/git","add","-A"],cwd=WORKSPACE)
    call(["/usr/bin/git","commit","--allow-empty","-m","Capture Factory Kubernetes result"],cwd=WORKSPACE)
    call(["/usr/bin/git","push","origin",f"HEAD:{result_ref}"],cwd=WORKSPACE)
    return factory.returncode
if __name__=="__main__":
    try: raise SystemExit(main())
    except Exception as exc:
        print(f"factory-kubernetes-worker: {exc}",file=sys.stderr); raise SystemExit(1)
