#!/bin/sh
# Generated by build_installer.py from installer.py. Do not edit the embedded source.
set -eu

usage() {
  cat <<'HELP'
Usage:
  curl -fsSL https://get.antgpu.ai | sh -s -- [ENROLLMENT_TOKEN] [OPTIONS]

Existing enrollment is preserved by default. A new token requires an explicit reset.
  --preserve-state    Reuse existing machine credentials
  --reset-state       Back up state and enroll as a new machine
  --token-file PATH   Read the token from a private file
  --workdir PATH      Explicitly select an installation/state directory
  --yes              Skip prompts; never implies reset
  --inspect          Show selected installation paths without installing

WSL is not supported by this Linux installer. Native Windows release
validation is pending; this installer does not launch PowerShell setup.

Environment overrides:
  ANTGPU_CONNECT_MANIFEST_URL   HTTPS manifest URL
  ANTGPU_CONNECT_WORKDIR        State directory (default: /var/lib/antgpu/connect)
  ANTGPU_CONNECT_SERVICE_NAME   Service name (default: antgpu-connect)
  ANTGPU_CONNECT_INSTALL_PATH   Binary path (default: /usr/local/bin/connect)
  ANTGPU_CONNECT_AUTH_STATE_FILE Authentication filename (default: .auth)
  ANTGPU_CONNECT_LOG_PATH       Log path (default: STATE_DIR/connect.log)

Requires native Linux, systemd, local Docker, NVIDIA Container Toolkit,
iptables, Python 3, and OpenSSL 3 or newer. Host software is not installed here.
HELP
}

die() { printf 'error: %s\n' "$*" >&2; exit 1; }
need_cmd() { command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"; }
reject_wsl() {
  [ "$(uname -s)" = "Linux" ] || return 0
  kernel_release="$(uname -r)"
  case "$kernel_release" in
    *[Mm][Ii][Cc][Rr][Oo][Ss][Oo][Ff][Tt]*|*[Ww][Ss][Ll]*) detected_wsl=1 ;;
    *) detected_wsl=0 ;;
  esac
  if [ "$detected_wsl" -eq 0 ] && [ -z "${WSL_INTEROP:-}" ] && [ -z "${WSL_DISTRO_NAME:-}" ]; then
    return 0
  fi
  printf '%s\n' \
    'error: Windows Subsystem for Linux (WSL) detected.' \
    'The Linux connector installer does not support WSL.' \
    'Use a native Linux host for this release. Native Windows release validation is pending.' \
    'Windows setup belongs in Windows PowerShell; this installer will not launch it automatically.' \
    'No installation changes were made.' >&2
  exit 1
}

case "${1-}" in -h|--help) usage; exit 0 ;; esac
need_cmd uname
reject_wsl
[ "$(uname -s)" = Linux ] || die "this release requires native Linux"
need_cmd python3
umask 077
temporary="$(mktemp -d)"
trap 'rm -rf "$temporary"' EXIT HUP INT TERM
cat > "$temporary/installer.py" <<'ANTGPU_INSTALLER_PY'
"""Source embedded into install_connect.sh by build_installer.py."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import ssl
import stat
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.request

PUBLIC_KEY = "cxFiE5lAcyYrklDmSVbdleWIVaCdpHi4p8HR7i0gO4k="
SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")
SAFE_PATH = re.compile(r"^/[A-Za-z0-9/_.-]+$")
DOCKER = ["docker", "--host=unix:///var/run/docker.sock"]


def fail(message):
    raise RuntimeError(message)


def run(args, **kwargs):
    return subprocess.run(args, check=True, **kwargs)


def trusted_path(path, private=False, directory=False):
    """Check before reading credentials, replacing files, or moving state."""
    path = Path(path)
    if not SAFE_PATH.fullmatch(str(path)) or ".." in path.parts or str(path) == "/":
        fail("unsafe installation path: " + str(path))
    for ancestor in reversed([path] + list(path.parents)):
        if not ancestor.exists() and not ancestor.is_symlink():
            continue
        info = ancestor.lstat()
        if stat.S_ISLNK(info.st_mode) or info.st_uid not in (0, os.geteuid()):
            fail("untrusted owner or symlink: " + str(ancestor))
        if info.st_mode & 0o022 and not (ancestor != path and info.st_mode & stat.S_ISVTX):
            fail("group/world-writable installation path: " + str(ancestor))
    if path.exists():
        info = path.lstat()
        if info.st_uid != os.geteuid():
            fail("installation path is not owned by this user: " + str(path))
        if directory and not stat.S_ISDIR(info.st_mode):
            fail("expected directory: " + str(path))
        if not directory and not stat.S_ISREG(info.st_mode):
            fail("expected regular file: " + str(path))
        if private and info.st_mode & 0o077:
            fail("private state requires owner-only permissions: " + str(path))
        if not directory and info.st_nlink != 1:
            fail("refusing hard-linked state/configuration file: " + str(path))
    return path


def atomic_write(path, data, mode):
    path = trusted_path(path)
    trusted_path(path.parent, directory=True)
    fd, temporary = tempfile.mkstemp(prefix=".antgpu-install-", dir=path.parent)
    try:
        with os.fdopen(fd, "wb") as target:
            os.fchmod(target.fileno(), mode)
            target.write(data)
            target.flush()
            os.fsync(target.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def origin(url):
    parsed = urllib.parse.urlsplit(url)
    if (parsed.scheme != "https" or not parsed.hostname or parsed.username is not None
            or parsed.password is not None or parsed.fragment or any(ord(c) < 33 for c in url)):
        fail("artifact URLs must use HTTPS without credentials, fragments, or whitespace")
    return parsed.scheme, parsed.hostname.lower(), parsed.port or 443


class SameOriginRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, fp, code, msg, headers, newurl):
        if origin(request.full_url) != origin(newurl):
            fail("cross-origin artifact redirect rejected")
        return super().redirect_request(request, fp, code, msg, headers, newurl)


def download(url, destination, limit):
    origin(url)
    opener = urllib.request.build_opener(
        SameOriginRedirect(),
        urllib.request.HTTPSHandler(context=ssl.create_default_context()))
    with opener.open(url, timeout=30) as response, open(destination, "xb") as output:
        if origin(response.url) != origin(url):
            fail("artifact response changed origin")
        count = 0
        while True:
            block = response.read(1024 * 1024)
            if not block:
                break
            count += len(block)
            if count > limit:
                fail("artifact exceeds download size limit")
            output.write(block)


def verify_manifest(manifest, manifest_url, platform, work):
    # Match connector-protocol's typed Go JSON encoding, including HTML escaping.
    if not isinstance(manifest, dict):
        fail("invalid manifest document")
    version = manifest.get("version")
    if not isinstance(version, str) or not SAFE_NAME.fullmatch(version):
        fail("invalid manifest version")
    artifacts = manifest.get("binaries")
    if not isinstance(artifacts, list) or not artifacts:
        fail("manifest has no artifacts")
    binaries, seen = [], set()
    for item in artifacts:
        if not isinstance(item, dict):
            fail("invalid manifest artifact")
        binary = {key: item.get(key) for key in ("os", "arch", "url", "sha256")}
        if any(not isinstance(value, str) or not value for value in binary.values()):
            fail("invalid manifest artifact fields")
        if not re.fullmatch(r"[0-9a-fA-F]{64}", binary["sha256"]):
            fail("invalid artifact checksum")
        if origin(binary["url"]) != origin(manifest_url):
            fail("artifact origin differs from manifest origin")
        pair = binary["os"], binary["arch"]
        if pair in seen:
            fail("duplicate manifest platform")
        seen.add(pair)
        binaries.append(binary)
    payload = json.dumps({"version": version, "binaries": binaries}, ensure_ascii=False,
                         separators=(",", ":"))
    for value in ("&", "<", ">", "\u2028", "\u2029"):
        payload = payload.replace(value, "\\u%04x" % ord(value))
    try:
        signature = base64.b64decode(manifest.get("signature", ""), validate=True)
        key = base64.b64decode(PUBLIC_KEY, validate=True)
    except (ValueError, TypeError):
        fail("invalid update signature")
    if len(signature) != 64 or len(key) != 32:
        fail("update signature is missing or invalid")
    (work / "payload").write_bytes(b"antgpu-connector-update-v1\n" + payload.encode("utf-8"))
    (work / "signature").write_bytes(signature)
    (work / "public.der").write_bytes(bytes.fromhex("302a300506032b6570032100") + key)
    result = subprocess.run(["openssl", "pkeyutl", "-verify", "-rawin", "-pubin", "-keyform", "DER",
                             "-inkey", str(work / "public.der"), "-in", str(work / "payload"),
                             "-sigfile", str(work / "signature")], capture_output=True)
    if result.returncode:
        fail("manifest signature verification failed (OpenSSL 3 or newer is required)")
    for binary in binaries:
        if (binary["os"], binary["arch"]) == platform:
            return version, binary
    fail("no signed artifact for %s/%s" % platform)


def inspect_state(state, auth_name):
    trusted_path(state, private=True, directory=True)
    if not state.exists():
        return None
    auth = trusted_path(state / auth_name, private=True)
    if not auth.exists():
        if any(state.iterdir()):
            fail("partial installation at %s; inspect its contents and use --reset-state explicitly" % state)
        return None
    try:
        data = json.loads(auth.read_bytes())
        if not isinstance(data.get("machine_id"), str) or not data["machine_id"]:
            raise ValueError()
        if not isinstance(data.get("machine_token"), str) or not data["machine_token"]:
            raise ValueError()
    except (ValueError, AttributeError):
        fail("invalid enrollment state at " + str(auth))
    return data["machine_id"]


def check_no_workloads():
    # Root daemon access is required to prove replacement/reset is safe.
    result = run(DOCKER + ["ps", "--format", "{{json .}}"], capture_output=True, text=True)
    for line in result.stdout.splitlines():
        row = json.loads(line)
        labels = row.get("Labels", "")
        if any(key in labels for key in ("antgpu.", "managed-by=antgpu", "template-name=")):
            fail("a provider workload is running; stop rentals through the platform before installing")


def backup_reset(state):
    trusted_path(state, private=True, directory=True)
    if not state.exists():
        return None
    if len(state.parts) < 4 or state in (Path("/var/lib/docker"), Path("/var/lib/antgpu")):
        fail("refusing reset of a system/shared directory")
    if any(state.iterdir()) and not any((state / name).exists() for name in
            (".auth", ".auth-dev", ".auth-teststand", "conn.yaml", "conn-dev.yaml", "conn-teststand.yaml", ".antgpu-install.json")):
        fail("directory has no recognizable connector state; refusing reset")
    for root, directories, files in os.walk(state, followlinks=False):
        if Path(root).is_mount() and Path(root) != state:
            fail("state contains a mounted directory; refusing reset")
        for name in directories + files:
            child = Path(root) / name
            if child.is_symlink() or child.stat().st_dev != state.stat().st_dev:
                fail("state contains a symlink or mounted filesystem; refusing reset")
    if state.is_mount():
        fail("state directory is a mount point; refusing reset")
    # Atomic rename retains private recovery data and never recursively deletes.
    backup = state.with_name(state.name + ".backup-" + time.strftime("%Y%m%d-%H%M%S"))
    if backup.exists():
        fail("backup path already exists: " + str(backup))
    state.rename(backup)
    state.mkdir(mode=0o700)
    return backup


def read_token(args):
    if args.token and args.token_file:
        fail("use either a token argument or --token-file")
    token = args.token or ""
    if args.token_file:
        path = Path(args.token_file)
        info = path.lstat()
        owners = {os.geteuid(), int(os.getenv("SUDO_UID", str(os.geteuid())))}
        if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_uid not in owners or info.st_nlink != 1:
            fail("token file must be a private regular file owned by the installing user")
        token = path.read_text().strip()
    if token and not re.fullmatch(r"[A-Za-z0-9_.=+/:-]+", token):
        fail("invalid enrollment token format")
    return token


def choose_mode(args, identity, state):
    mode = "reset" if args.reset_state else "preserve"
    if identity:
        print("Existing enrollment: %s\nState: %s" % (identity, state))
        if not args.reset_state and not args.preserve_state and not args.yes:
            try:
                with open("/dev/tty", "r+") as tty:
                    tty.write("1. Preserve enrollment [default]\n2. Reset enrollment (backup state)\n3. Cancel\nChoice [1]: ")
                    tty.flush()
                    choice = tty.readline().strip() or "1"
                if choice == "2":
                    mode = "reset"
                elif choice != "1":
                    fail("installation cancelled")
            except OSError:
                pass  # Unattended default preserves the identity.
    if mode == "preserve" and identity and (args.token or args.token_file):
        fail("existing enrollment found; omit the new token to preserve it, or select --reset-state")
    return mode


def check_prerequisites():
    run(DOCKER + ["info"], stdout=subprocess.DEVNULL)
    run(["iptables", "-S", "DOCKER-USER"], stdout=subprocess.DEVNULL)
    run(["nvidia-smi"], stdout=subprocess.DEVNULL)
    # Do not weaken the connector's mandatory benchmark/admission checks.
    probe = subprocess.run(DOCKER + ["run", "--rm", "--gpus", "all", "ubuntu:22.04", "nvidia-smi"],
                           stdout=subprocess.DEVNULL, timeout=120)
    if probe.returncode:
        fail("Docker GPU runtime check failed; configure NVIDIA Container Toolkit before installing")


def require_host():
    if sys.platform != "linux" or os.geteuid() != 0:
        fail("this release requires native Linux and root privileges")


def preserve_unit_settings(previous, replacement):
    if not previous:
        return replacement
    keys = ("WorkingDirectory", "EnvironmentFile", "ExecStart")
    updates = {line.split("=", 1)[0]: line for line in replacement.splitlines()
               if line.split("=", 1)[0] in keys}
    lines, section, replaced = [], "", set()
    for line in previous.splitlines():
        if line.startswith("["):
            section = line
        key = line.split("=", 1)[0]
        if section == "[Service]" and key in updates:
            if key not in replaced:
                lines.append(updates[key])
                replaced.add(key)
        else:
            lines.append(line)
    if replaced != set(keys):
        fail("existing service is not a recognized connector unit; repair it explicitly before installing")
    return "\n".join(lines) + "\n"


def main(argv=None):
    parser = argparse.ArgumentParser(description="Install or repair AntGPU Connector without losing enrollment")
    parser.add_argument("token", nargs="?")
    modes = parser.add_mutually_exclusive_group()
    modes.add_argument("--preserve-state", action="store_true")
    modes.add_argument("--reset-state", action="store_true")
    parser.add_argument("--token-file")
    parser.add_argument("--workdir", help="explicitly select a state directory when other installations exist")
    parser.add_argument("--yes", action="store_true", help="disable prompts; never implies reset")
    parser.add_argument("--inspect", action="store_true", help="show detected installation paths without installing")
    args = parser.parse_args(argv)
    os.umask(0o077)
    require_host()
    machine = os.uname().machine
    arch = {"x86_64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(machine)
    if not arch:
        fail("unsupported architecture: " + machine)
    service = os.getenv("ANTGPU_CONNECT_SERVICE_NAME", "antgpu-connect")
    auth_name = os.getenv("ANTGPU_CONNECT_AUTH_STATE_FILE", ".auth")
    if not SAFE_NAME.fullmatch(service) or not re.fullmatch(r"[A-Za-z0-9_.-]+", auth_name) or auth_name in (".", ".."):
        fail("invalid service name or unsupported authentication state filename")
    state = trusted_path(args.workdir or os.getenv("ANTGPU_CONNECT_WORKDIR", "/var/lib/antgpu/connect"), private=True, directory=True)
    binary_path = trusted_path(os.getenv("ANTGPU_CONNECT_INSTALL_PATH", "/usr/local/bin/connect"))
    unit_path = trusted_path("/etc/systemd/system/" + service + ".service")
    env_path = trusted_path("/etc/default/" + service, private=True)
    log_path = trusted_path(os.getenv("ANTGPU_CONNECT_LOG_PATH") or str(state / "connect.log"))
    print("Service: %s\nBinary: %s\nState: %s\nEnvironment: %s\nLogs: %s" % (service, binary_path, state, env_path, log_path))
    previous_unit = ""
    legacy_environment = []
    legacy_paths = []
    # Inspect installed units as data, never execute or source their contents.
    if unit_path.exists():
        unit = unit_path.read_text()
        previous_unit = unit
        expected = "WorkingDirectory=" + str(state)
        if expected not in unit.splitlines():
            fail("existing service uses a different state path; inspect %s and select it with ANTGPU_CONNECT_WORKDIR" % unit_path)
        if str(binary_path) not in unit:
            fail("existing service uses a different binary; inspect %s and select it with ANTGPU_CONNECT_INSTALL_PATH" % unit_path)
        for line in unit.splitlines():
            if line.startswith("EnvironmentFile="):
                legacy_path = trusted_path(line.split("=", 1)[1].lstrip("-"), private=True)
                if legacy_path != env_path and legacy_path.exists():
                    legacy_environment.extend(legacy_path.read_text().splitlines())
                    legacy_paths.append(legacy_path)
    # Other known installations are disclosed, never implicitly adopted/deleted.
    alternatives = [Path("/var/lib/antgpu/connect"), Path("/var/lib/antgpu/connect-dev"), Path("/var/lib/launchpad/connect")]
    for other in alternatives:
        if other != state and other.exists():
            print("Other installation/state found (untouched): " + str(other))
            if not state.exists() and state == Path("/var/lib/antgpu/connect") and not args.workdir:
                fail("select the intended installation with --workdir; other state was found")
    try:
        identity = inspect_state(state, auth_name)
    except RuntimeError:
        if not args.reset_state:
            raise
        # Explicit reset can recover incomplete state, but never unsafe ownership.
        trusted_path(state, private=True, directory=True)
        identity = None
    if args.inspect:
        print("Enrollment: " + (identity or "not enrolled"))
        return
    for command in ("openssl", "systemctl", "docker", "iptables", "nvidia-smi"):
        if not shutil.which(command):
            fail("required command not found: " + command)
    mode = choose_mode(args, identity, state)
    token = read_token(args)
    if (mode == "reset" or not identity) and not token:
        fail("enrollment token is required for a fresh installation/reset; use --token-file for unattended setup")
    if mode == "reset" and not args.yes:
        try:
            with open("/dev/tty", "r+") as tty:
                tty.write("Back up and reset %s? Type reset: " % state)
                tty.flush()
                confirmation = tty.readline().strip()
            if confirmation != "reset":
                fail("reset cancelled")
        except OSError:
            fail("unattended reset requires both --reset-state and --yes")
    check_no_workloads()
    check_prerequisites()
    manifest_url = os.getenv("ANTGPU_CONNECT_MANIFEST_URL", "https://api.antgpu.ai/internal/connect/connector/manifest")
    with tempfile.TemporaryDirectory(prefix="antgpu-install-") as temporary:
        work = Path(temporary)
        manifest_path = work / "manifest.json"
        download(manifest_url, manifest_path, 1024 * 1024)
        manifest = json.loads(manifest_path.read_bytes())
        version, artifact = verify_manifest(manifest, manifest_url, ("linux", arch), work)
        candidate = work / "connect"
        download(artifact["url"], candidate, 256 * 1024 * 1024)
        if hashlib.sha256(candidate.read_bytes()).hexdigest() != artifact["sha256"].lower():
            fail("connector binary checksum mismatch")
        candidate.chmod(0o500)
        output = run([str(candidate), "--version"], capture_output=True, text=True, timeout=10)
        if not output.stdout.split() or output.stdout.split()[0] != version:
            fail("signed connector binary version differs from manifest")
        check_no_workloads()
        # Quiesce the old agent and recheck to close the admission race.
        originals = {path: (path.read_bytes(), stat.S_IMODE(path.stat().st_mode)) if path.exists() else None
                     for path in [binary_path, env_path, unit_path] + (legacy_paths if mode == "preserve" else [])}
        was_active = subprocess.run(["systemctl", "is-active", "--quiet", service + ".service"]).returncode == 0
        if was_active:
            run(["systemctl", "stop", service + ".service"])
        backup = None
        try:
            check_no_workloads()
            backup = backup_reset(state) if mode == "reset" else None
            if backup:
                print("Private recovery backup: " + str(backup))
            for directory in (state, binary_path.parent, log_path.parent):
                trusted_path(directory, directory=True)
                directory.mkdir(mode=0o700 if directory == state else 0o755, parents=True, exist_ok=True)
            # Preserve configured log environment without retaining enrollment secrets.
            old_env = legacy_environment + (env_path.read_text().splitlines() if env_path.exists() else [])
            if identity and mode == "preserve":
                for path in legacy_paths:
                    lines = [line for line in path.read_text().splitlines() if not line.lstrip().startswith(("ANTGPU_CONNECT_TOKEN=", "export ANTGPU_CONNECT_TOKEN="))]
                    atomic_write(path, ("\n".join(lines) + "\n").encode(), 0o600)
            retained = [line for line in old_env if not line.lstrip().startswith(("ANTGPU_CONNECT_TOKEN=", "export ANTGPU_CONNECT_TOKEN=", "CONNECT_LOG_PATH=", "ANTGPU_CONNECT_AUTH_STATE_FILE=", "ANTGPU_CONNECT_INSTALL_PATH="))]
            retained += ["CONNECT_LOG_PATH=" + str(log_path), "ANTGPU_CONNECT_AUTH_STATE_FILE=" + auth_name,
                         "ANTGPU_CONNECT_INSTALL_PATH=" + str(binary_path)]
            if not identity or mode == "reset":
                retained.append("ANTGPU_CONNECT_TOKEN=" + token)
            atomic_write(env_path, ("\n".join(retained) + "\n").encode(), 0o600)
            atomic_write(binary_path, candidate.read_bytes(), 0o755)
            unit = """[Unit]
Description=AntGPU Connector
After=network-online.target docker.service
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=%s
EnvironmentFile=-%s
ExecStart=/bin/sh -c 'exec %s --foreground --service-name %s --state-dir %s "$$ANTGPU_CONNECT_TOKEN"'
Restart=on-failure
RestartSec=3
TimeoutStopSec=20

[Install]
WantedBy=multi-user.target
""" % (state, env_path, binary_path, service, state)
            atomic_write(unit_path, preserve_unit_settings(previous_unit, unit).encode(), 0o644)
            run(["systemctl", "daemon-reload"])
            run(["systemctl", "enable", "--now", service + ".service"])
            run(["systemctl", "is-active", "--quiet", service + ".service"])
            atomic_write(state / ".antgpu-install.json", json.dumps({"service": service, "binary": str(binary_path), "auth": auth_name}).encode(), 0o600)
        except Exception:
            subprocess.run(["systemctl", "stop", service + ".service"])
            for path, original in originals.items():
                if original is None:
                    if path.exists():
                        path.unlink()
                else:
                    atomic_write(path, *original)
            if backup:
                failed = state.with_name(state.name + ".failed-" + time.strftime("%Y%m%d-%H%M%S"))
                state.rename(failed)
                backup.rename(state)
                print("Failed reset state retained privately: " + str(failed))
            subprocess.run(["systemctl", "daemon-reload"])
            if was_active:
                subprocess.run(["systemctl", "start", service + ".service"])
            raise
    print("Installed connector %s; enrollment %s.\nLogs: journalctl -u %s -f" %
          (version, "preserved" if identity and mode != "reset" else "requested", service))
    print("The connector removes its persisted one-time token after enrollment succeeds.")


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, OSError, ValueError, TypeError, subprocess.SubprocessError) as exc:
        # Command failures may include token argv; do not print their repr.
        message = "host command failed; inspect the service logs" if isinstance(exc, subprocess.SubprocessError) else str(exc)
        print("error: " + message, file=sys.stderr)
        sys.exit(1)
ANTGPU_INSTALLER_PY
if [ "$(id -u)" -eq 0 ]; then
  python3 - "$@" < "$temporary/installer.py"
else
  need_cmd sudo
  # Preserve only installer settings; root receives Python source through stdin.
  sudo -- env \
    ANTGPU_CONNECT_MANIFEST_URL="${ANTGPU_CONNECT_MANIFEST_URL:-https://api.antgpu.ai/internal/connect/connector/manifest}" \
    ANTGPU_CONNECT_WORKDIR="${ANTGPU_CONNECT_WORKDIR:-/var/lib/antgpu/connect}" \
    ANTGPU_CONNECT_SERVICE_NAME="${ANTGPU_CONNECT_SERVICE_NAME:-antgpu-connect}" \
    ANTGPU_CONNECT_INSTALL_PATH="${ANTGPU_CONNECT_INSTALL_PATH:-/usr/local/bin/connect}" \
    ANTGPU_CONNECT_AUTH_STATE_FILE="${ANTGPU_CONNECT_AUTH_STATE_FILE:-.auth}" \
    ANTGPU_CONNECT_LOG_PATH="${ANTGPU_CONNECT_LOG_PATH:-}" \
    python3 - "$@" < "$temporary/installer.py"
fi
