#!/usr/bin/env bash
# Stop the scheduler/API replica that the owning worker reports to, mid-activity.
# Usage: scheduler-down.sh <workflow_id>
set -uo pipefail
WF=$1
LAB=$(cd "$(dirname "$0")" && pwd)
ts() { date -u +%H:%M:%S; }
q() { "$LAB/psql.sh" -At -c "$1"; }
echo "[$(ts)] submit $WF (20s activity)"; "$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'")
RT=runtime-${OWNER:7:1}            # worker-a-0 reports to runtime-a
echo "[$(ts)] claimed by $OWNER, which reports to $RT; stopping $RT"
"$LAB/dc.sh" stop "$RT" >/dev/null 2>&1
until [ "$(q "SELECT state FROM engine.workflow_executions WHERE workflow_id='$WF'")" = "SUCCEEDED" ]; do sleep 1; done
echo "[$(ts)] $WF SUCCEEDED with $RT still down"
"$LAB/psql.sh" -c "SELECT attempt_number AS attempt, state, worker_id FROM engine.activity_attempts WHERE workflow_id='$WF' ORDER BY 1"
"$LAB/dc.sh" logs --no-log-prefix "${OWNER%-*}" 2>&1 | grep "$WF " | grep -E 'outcome=' | cut -c1-330
"$LAB/dc.sh" start "$RT" >/dev/null 2>&1
