#!/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 <<'EOF'
Dry run only. This smoke will:
  1. create a temporary Kubernetes namespace,
  2. create one PVC,
  3. write a checkpoint file from a temporary pod,
  4. delete that pod,
  5. create a replacement pod mounting the same PVC,
  6. verify the checkpoint file survived,
  7. delete the temporary namespace.

Run intentionally with:
  AWP_RUNTIME_CLASS=gvisor bash tools/preflight/workspace-wip-smoke.sh --run [--yes]

Set AWP_RUNTIME_CLASS empty only when explicitly testing the native fallback.
EOF
  exit 0
fi

command -v kubectl >/dev/null 2>&1 || { echo "kubectl required" >&2; exit 2; }
ctx="$(kubectl config current-context)"
ns="awp-wip-smoke-$(date +%s)-$$"
runtime="${AWP_RUNTIME_CLASS:-}"

printf 'context=%s\nnamespace=%s\nruntimeClass=%s\n' "$ctx" "$ns" "${runtime:-<native>}"
if [[ "$yes" != true ]]; then
  read -r -p "Create bounded temporary smoke resources in this context? [y/N] " answer
  [[ "$answer" =~ ^[Yy]$ ]] || exit 3
fi

cleanup(){ kubectl delete namespace "$ns" --wait=true --timeout=60s >/dev/null 2>&1 || true; }
trap cleanup EXIT

kubectl create namespace "$ns"
kubectl -n "$ns" apply -f - <<'YAML'
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: wip
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 64Mi
YAML

runtime_line=""
if [[ -n "$runtime" ]]; then
  kubectl get runtimeclass "$runtime" >/dev/null
  runtime_line="  runtimeClassName: $runtime"
fi

cat <<YAML | kubectl -n "$ns" apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: writer
spec:
$runtime_line
  restartPolicy: Never
  securityContext:
    fsGroup: 1000
  containers:
  - name: writer
    image: busybox:1.36
    command: ["sh","-c","echo checkpoint-awp > /wip/checkpoint.txt; sync; cat /wip/checkpoint.txt"]
    securityContext:
      allowPrivilegeEscalation: false
      runAsNonRoot: true
      runAsUser: 1000
      capabilities: {drop: ["ALL"]}
    volumeMounts:
    - name: wip
      mountPath: /wip
  volumes:
  - name: wip
    persistentVolumeClaim: {claimName: wip}
YAML

kubectl -n "$ns" wait --for=jsonpath='{.status.phase}'=Succeeded pod/writer --timeout=120s
kubectl -n "$ns" logs writer
kubectl -n "$ns" delete pod writer --wait=true

cat <<YAML | kubectl -n "$ns" apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: reader
spec:
$runtime_line
  restartPolicy: Never
  securityContext:
    fsGroup: 1000
  containers:
  - name: reader
    image: busybox:1.36
    command: ["sh","-c","test \"\$(cat /wip/checkpoint.txt)\" = checkpoint-awp && echo WIP_PERSISTED"]
    securityContext:
      allowPrivilegeEscalation: false
      runAsNonRoot: true
      runAsUser: 1000
      capabilities: {drop: ["ALL"]}
    volumeMounts:
    - name: wip
      mountPath: /wip
  volumes:
  - name: wip
    persistentVolumeClaim: {claimName: wip}
YAML

kubectl -n "$ns" wait --for=jsonpath='{.status.phase}'=Succeeded pod/reader --timeout=120s
result="$(kubectl -n "$ns" logs reader)"
printf 'result=%s\n' "$result"
[[ "$result" == *WIP_PERSISTED* ]]

echo "PASS: checkpoint survived pod replacement."
echo "NOTE: this proves only the PVC/pod replacement slice; control-plane restart, node interruption, change collection and orphan recovery remain separate gates."