#!/bin/sh
# The trusted runner provides Python and the extracted Deslop Clean release.
exec python3 -I - "$@" <<'PY'
import os
from pathlib import Path
import subprocess
import sys


def main():
    args = sys.argv[1:]
    if len(args) not in (3, 4) or (len(args) == 4 and args[3] != "--json"):
        raise ValueError("Usage: ci-check /absolute/path/to/deslop-clean PROJECT BASELINE [--json]")
    binary, project, baseline = (Path(arg) for arg in args[:3])
    if not binary.is_absolute():
        raise ValueError("Specify the absolute path to the runner's Deslop Clean installation")
    binary, project, baseline = (path.resolve(strict=True) for path in (binary, project, baseline))
    if not project.is_dir() or not baseline.is_file():
        raise ValueError("Expected a project directory and a reviewed baseline file")
    if binary.is_relative_to(project):
        raise ValueError("Install Deslop Clean outside the project being analyzed")
    if not binary.is_file() or not os.access(binary, os.X_OK):
        raise ValueError("Runner installation is missing an executable deslop-clean")
    # Keep stdout valid JSON when machine output is requested.
    subprocess.run([binary, "--version"], stdout=sys.stderr, check=True, timeout=10)
    os.execv(binary, [str(binary), "gate", str(project), "--baseline", str(baseline), *args[3:]])


try:
    main()
except (ValueError, OSError, subprocess.SubprocessError) as error:
    print(f"ci-check: {error}", file=sys.stderr)
    sys.exit(2)
PY
