#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONFIG_PATH="${1:-}"

if [[ -z "$CONFIG_PATH" ]]; then
  echo "usage: rho-gondolin-run <gondolin-run.yaml>" >&2
  exit 2
fi

if [[ -z "${RHO_GONDOLIN_WORKSPACE_DIR:-}" ||
      -z "${RHO_GONDOLIN_DATASET_DIR:-}" ||
      -z "${RHO_GONDOLIN_OUTPUT_DIR:-}" ||
      -z "${RHO_GONDOLIN_GUEST_COMMAND:-}" ]]; then
  echo "rho-gondolin-run must be launched by rho-run with RHO_GONDOLIN_* env vars" >&2
  exit 2
fi

GONDOLIN_DIR="$ROOT_DIR/repos/gondolin"

if [[ ! -d "$GONDOLIN_DIR" ]]; then
  echo "gondolin submodule not found at $GONDOLIN_DIR" >&2
  exit 1
fi

if [[ ! -f "$GONDOLIN_DIR/node_modules/@earendil-works/gondolin/bin/gondolin.ts" ]]; then
  echo "gondolin dependencies are not installed. Run: cd repos/gondolin && pnpm install" >&2
  exit 1
fi

cd "$GONDOLIN_DIR/host"
exec node bin/gondolin.ts exec \
  --mount-hostfs "$RHO_GONDOLIN_WORKSPACE_DIR:/workspace:ro" \
  --mount-hostfs "$RHO_GONDOLIN_DATASET_DIR:/input:ro" \
  --mount-hostfs "$RHO_GONDOLIN_OUTPUT_DIR:/output" \
  -- /bin/sh -lc "$RHO_GONDOLIN_GUEST_COMMAND"
