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

run=false
yes=false
for arg in "$@"; do
  case "$arg" in
    --run) run=true ;;
    --yes) yes=true ;;
    *) echo "unknown argument: $arg" >&2; exit 2 ;;
  esac
done

if [[ "$run" != true ]]; then
  cat <<'TXT'
Dry run only. This creates a temporary namespace and runs two non-root pods with
runtimeClassName=gvisor:
  - Node 22 project toolchain probe (Node/npm/corepack)
  - WordPress CLI/PHP toolchain probe
It removes the namespace on exit.

Run intentionally with:
  bash tools/preflight/gvisor-toolchain-smoke.sh --run [--yes]
TXT
  exit 0
fi

command -v kubectl >/dev/null 2>&1 || { echo "kubectl required" >&2; exit 2; }
kubectl get runtimeclass gvisor >/dev/null
ctx="$(kubectl config current-context)"
ns="awp-gvisor-smoke-$(date +%s)-$$"
printf 'context=%s\nnamespace=%s\nruntimeClass=gvisor\n' "$ctx" "$ns"
if [[ "$yes" != true ]]; then
  read -r -p "Create bounded temporary gVisor smoke resources? [y/N] " answer
  [[ "$answer" =~ ^[Yy]$ ]] || exit 3
fi
cleanup(){ kubectl delete namespace "$ns" --wait=false >/dev/null 2>&1 || true; }
trap cleanup EXIT
kubectl create namespace "$ns"

cat <<'YAML' | kubectl -n "$ns" apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: node-toolchain
spec:
  runtimeClassName: gvisor
  restartPolicy: Never
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 1000
    seccompProfile: {type: RuntimeDefault}
  containers:
    - name: node
      image: node:22-bookworm
      command: ["sh", "-lc", "node --version && npm --version && corepack --version && echo NODE_TYPESCRIPT_REACT_BASELINE_OK"]
      securityContext:
        allowPrivilegeEscalation: false
        capabilities: {drop: ["ALL"]}
      resources:
        requests: {cpu: 50m, memory: 96Mi}
        limits: {cpu: "1", memory: 512Mi}
YAML
kubectl -n "$ns" wait --for=jsonpath='{.status.phase}'=Succeeded pod/node-toolchain --timeout=180s
kubectl -n "$ns" logs node-toolchain

cat <<'YAML' | kubectl -n "$ns" apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: wordpress-toolchain
spec:
  runtimeClassName: gvisor
  restartPolicy: Never
  securityContext:
    runAsNonRoot: true
    runAsUser: 33
    runAsGroup: 33
    seccompProfile: {type: RuntimeDefault}
  containers:
    - name: wp
      image: wordpress:cli-php8.3
      command: ["sh", "-lc", "php --version | head -1; wp --info; echo PHP_WORDPRESS_BASELINE_OK"]
      securityContext:
        allowPrivilegeEscalation: false
        capabilities: {drop: ["ALL"]}
      resources:
        requests: {cpu: 50m, memory: 96Mi}
        limits: {cpu: "1", memory: 512Mi}
YAML
kubectl -n "$ns" wait --for=jsonpath='{.status.phase}'=Succeeded pod/wordpress-toolchain --timeout=240s
kubectl -n "$ns" logs wordpress-toolchain

echo "PASS: representative Node and PHP/WordPress toolchains executed under gVisor."
