#!/usr/bin/env bash
# Freeze the worker that owns a running attempt, let the engine replace it,
# then thaw the frozen worker and watch what happens to its late result.
# Usage: zombie-worker.sh <workflow_id>      (run from the repo root)
set -euo pipefail
WF=$1
LAB=$(cd "$(dirname "$0")" && pwd)
ts() { date -u +%H:%M:%S; }
q() { "$LAB/psql.sh" -At -c "$1"; }
attempts() { "$LAB/psql.sh" -c "SELECT attempt_number AS attempt, state, is_current, worker_id,
  to_char(heartbeat_deadline,'HH24:MI:SS') AS hb_deadline FROM engine.activity_attempts
  WHERE workflow_id='$WF' ORDER BY attempt_number"; }

echo "[$(ts)] submit $WF"
"$LAB/submit.sh" "$WF" lab-slow dur048.sleep '"hello"' | tail -1

until [ "$(q "SELECT count(*) FROM engine.activity_attempts WHERE workflow_id='$WF' AND state='CLAIMED'")" = "1" ]; do sleep 0.2; done
OWNER=$(q "SELECT worker_id FROM engine.activity_attempts WHERE workflow_id='$WF' AND state='CLAIMED'")
SVC=${OWNER%-*}                      # worker-a-1 -> worker-a
echo "[$(ts)] attempt 1 claimed by $OWNER; freezing service $SVC"
"$LAB/dc.sh" pause "$SVC" >/dev/null 2>&1
attempts

echo "[$(ts)] waiting for the engine to replace the attempt and finish the workflow"
until [ "$(q "SELECT state FROM engine.workflow_executions WHERE workflow_id='$WF'")" = "SUCCEEDED" ]; do sleep 1; done
echo "[$(ts)] workflow SUCCEEDED while $SVC is still frozen"
attempts

echo "[$(ts)] thawing $SVC"
"$LAB/dc.sh" unpause "$SVC" >/dev/null 2>&1
sleep 25
echo "[$(ts)] $SVC log lines about $WF after the thaw:"
"$LAB/dc.sh" logs --no-log-prefix "$SVC" 2>&1 | grep "$WF" | grep -E 'rejected|STALE|outcome' | cut -c1-400
attempts
