#!/usr/bin/env bash
# Stub container runtime for dispatch.test.sh (STORY-348 T-PB-348a/348c).
# Speaks the subset of docker lib/sandbox.sh emits and EMULATES it well enough
# to observe what the agent would see:
#   run (attached)  — the agent's container. argv is recorded to argv.log next
#                     to this file; the command runs from the image's bin dir
#                     (image-bin/) with an EMPTY environment except the `-e`
#                     names/values, a fresh container HOME and FAKE_NETWORK, in
#                     the host directory mounted at the -w target. It cannot
#                     hide absolute host paths — that is the real runtime's job.
#   run -d          — the egress proxy: a state dir containers/<name>/ holding
#                     the mounted config dir's path (conf) and its log
#                     (proxy.log). image-bin/egress-probe plays the client.
#   network create|connect|rm, exec (proxy readiness), logs, rm -f,
#   image inspect, build (stack pack images — recorded in images/).
# Every non-attached call is appended to ops.log. An image whose name contains
# `broken` never becomes ready (exec fails).
set -uo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
state="$here/containers"; mkdir -p "$state"

case "${1:-}" in
  network)
    printf '%s\n' "$*" >> "$here/ops.log"
    case "${2:-}" in
      create) [[ "${3:-}" == --internal ]] || { echo "fake-runtime: network must be --internal" >&2; exit 2; }
              mkdir "$state/net-$4" || exit 1 ;;
      connect) [[ -d "$state/net-$3" && -d "$state/$4" ]] || exit 1
               echo "$3" >> "$state/$4/networks" ;;
      rm) rmdir "$state/net-$3" || exit 1 ;;
      *) echo "fake-runtime: unknown network verb $2" >&2; exit 2 ;;
    esac
    exit 0 ;;
  exec) printf '%s\n' "$*" >> "$here/ops.log"
        [[ -d "$state/$2" ]] && ! grep -q broken "$state/$2/image"; exit ;;
  logs) printf '%s\n' "$*" >> "$here/ops.log"; cat "$state/$2/proxy.log"; exit ;;
  rm)   printf '%s\n' "$*" >> "$here/ops.log"; rm -rf "${state:?}/$3"; exit 0 ;;
  # Pack images (T-PB-348b): `image inspect <tag>` succeeds once `build -t
  # <tag> -f <file> <ctx>` has run; a Dockerfile containing BROKEN fails to build.
  image) printf '%s\n' "$*" >> "$here/ops.log"
         [[ "${2:-}" == inspect && -f "$here/images/$(printf '%s' "${3:-}" | tr ':/' '__')" ]]; exit ;;
  build) printf '%s\n' "$*" >> "$here/ops.log"
         [[ "${2:-}" == -t && "${4:-}" == -f && -f "${5:-}" && -d "${6:-}" ]] || {
           echo "fake-runtime: build wants -t <tag> -f <file> <context>" >&2; exit 2; }
         if grep -q BROKEN "$5"; then echo "fake-runtime: step 2/3 failed: BROKEN" >&2; exit 1; fi
         mkdir -p "$here/images"; : > "$here/images/$(printf '%s' "$3" | tr ':/' '__')"; exit 0 ;;
  run)  ;;
  *) echo "fake-runtime: '${1:-}' is not supported" >&2; exit 2 ;;
esac
shift
detached=0; [[ "${1:-}" == -d ]] && detached=1
if [[ $detached -eq 1 ]]; then printf 'run %s\n' "$*" >> "$here/ops.log"; else printf '%s\n' "$@" > "$here/argv.log"; fi
mounts=(); envs=(); workdir=""; name=""; network=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --rm|-i|--init|-d) shift ;;
    -v) mounts+=("${2%:ro}"); shift 2 ;;
    -w) workdir="$2"; shift 2 ;;
    -e) envs+=("$2"); shift 2 ;;
    --name) name="$2"; shift 2 ;;
    --network) network="$2"; shift 2 ;;
    --user) shift 2 ;;
    -*) echo "fake-runtime: unknown flag $1" >&2; exit 2 ;;
    *) break ;;
  esac
done
image="$1"; cmd="$2"; shift 2

if [[ $detached -eq 1 ]]; then
  [[ -n "$name" && ! -e "$state/$name" ]] || { echo "fake-runtime: bad or duplicate --name" >&2; exit 1; }
  mkdir "$state/$name"; echo "$image" > "$state/$name/image"; : > "$state/$name/proxy.log"
  for m in "${mounts[@]+"${mounts[@]}"}"; do
    [[ "${m##*:}" == /etc/harness-egress ]] && echo "${m%:*}" > "$state/$name/conf"
  done
  echo "fake-container-id-$name"
  exit 0
fi

cwd=""
for m in "${mounts[@]+"${mounts[@]}"}"; do [[ "${m##*:}" == "$workdir" ]] && cwd="${m%:*}"; done
[[ -n "$cwd" ]] || { echo "fake-runtime: -w ${workdir} is not a mount target" >&2; exit 2; }
croot="$(mktemp -d)"; mkdir -p "$croot/home"
envargs=("HOME=$croot/home" "PATH=$here/image-bin:/usr/bin:/bin" "SANDBOX_IMAGE=$image"
         "FAKE_NETWORK=${network:-default}")
for e in "${envs[@]+"${envs[@]}"}"; do
  if [[ "$e" == *=* ]]; then envargs+=("$e")
  elif [[ -n "${!e+x}" ]]; then envargs+=("$e=${!e}"); fi
done
rc=0
( cd "$cwd" && exec env -i "${envargs[@]}" "$cmd" "$@" ) || rc=$?
rm -rf "$croot"
exit "$rc"
