#!/bin/zsh
set -eu

export PATH=/Users/admin/.local/bin:/opt/homebrew/bin:/usr/bin:/bin

/opt/homebrew/bin/python3 - <<'PY'
import os
import stat
import sys

TRUST_ROOT = "/Users/admin"
PARENT_COMPONENTS = (".config", "ahel", "claude-shim")
FINAL_COMPONENT = "workdir"
DOCUMENTED_PATH = "/Users/admin/.config/ahel/claude-shim/workdir"
UV = "/opt/homebrew/bin/uv"
SERVER = "/Users/admin/dev/ahel/services/claude-shim/server.py"
WORKDIR_DEV_ENV = "CLAUDE_SHIM_WORKDIR_DEV"
WORKDIR_INO_ENV = "CLAUDE_SHIM_WORKDIR_INO"


def fail_workdir():
    print(f"claude-shim: invalid workdir: {DOCUMENTED_PATH}", file=sys.stderr)
    raise SystemExit(1)


def directory_flags():
    flags = os.O_RDONLY | os.O_DIRECTORY
    if hasattr(os, "O_NOFOLLOW"):
        flags |= os.O_NOFOLLOW
    return flags


def checked_directory(path, expected_uid, *, dir_fd=None):
    if dir_fd is None:
        descriptor = os.open(path, directory_flags())
    else:
        descriptor = os.open(path, directory_flags(), dir_fd=dir_fd)
    file_stat = os.fstat(descriptor)
    if not stat.S_ISDIR(file_stat.st_mode) or file_stat.st_uid != expected_uid:
        os.close(descriptor)
        raise ValueError("unsafe directory")
    return descriptor


def prepare_workdir():
    expected_uid = os.getuid()
    descriptors = []
    workdir = -1
    try:
        current = checked_directory(TRUST_ROOT, expected_uid)
        descriptors.append(current)
        for component in PARENT_COMPONENTS:
            current = checked_directory(component, expected_uid, dir_fd=current)
            descriptors.append(current)

        try:
            workdir = checked_directory(FINAL_COMPONENT, expected_uid, dir_fd=current)
        except FileNotFoundError:
            try:
                os.mkdir(FINAL_COMPONENT, mode=0o700, dir_fd=current)
            except FileExistsError:
                pass
            workdir = checked_directory(FINAL_COMPONENT, expected_uid, dir_fd=current)
        before = os.fstat(workdir)
        os.fchmod(workdir, 0o700)
        after = os.fstat(workdir)
        if (
            not stat.S_ISDIR(after.st_mode)
            or after.st_uid != expected_uid
            or stat.S_IMODE(after.st_mode) != 0o700
            or after.st_dev != before.st_dev
            or after.st_ino != before.st_ino
        ):
            raise ValueError("workdir identity changed")

        path_stat = os.stat(DOCUMENTED_PATH, follow_symlinks=False)
        if (
            not stat.S_ISDIR(path_stat.st_mode)
            or path_stat.st_uid != expected_uid
            or stat.S_IMODE(path_stat.st_mode) != 0o700
            or path_stat.st_dev != after.st_dev
            or path_stat.st_ino != after.st_ino
        ):
            raise ValueError("workdir path changed")
        return workdir, after
    except BaseException:
        if workdir >= 0:
            os.close(workdir)
        raise
    finally:
        for descriptor in reversed(descriptors):
            os.close(descriptor)


def launch_server(workdir, validated_stat):
    try:
        os.fchdir(workdir)
        inherited = os.stat(".")
        if (
            not stat.S_ISDIR(inherited.st_mode)
            or inherited.st_uid != os.getuid()
            or stat.S_IMODE(inherited.st_mode) != 0o700
            or inherited.st_dev != validated_stat.st_dev
            or inherited.st_ino != validated_stat.st_ino
        ):
            raise ValueError("inherited workdir changed")

        environment = os.environ.copy()
        environment[WORKDIR_DEV_ENV] = str(inherited.st_dev)
        environment[WORKDIR_INO_ENV] = str(inherited.st_ino)
        argv = [
            UV,
            "run",
            "--quiet",
            "--with",
            "fastapi",
            "--with",
            "uvicorn",
            "--with",
            "pydantic",
            SERVER,
            "--token-file",
            "/Users/admin/.config/ahel/claude-shim/token",
            "--host",
            "192.168.8.168",
            "--port",
            "8091",
        ]
        os.execve(UV, argv, environment)
    finally:
        os.close(workdir)


try:
    workdir, validated_stat = prepare_workdir()
    launch_server(workdir, validated_stat)
except (OSError, ValueError):
    fail_workdir()
PY
