#!/usr/bin/env bash
# Play a client that is NOT a worker: claim a task through the open control
# API and hand back a made-up result. Usage: forge.sh <workflow_id>
set -uo pipefail
WF=$1
LAB=$(cd "$(dirname "$0")" && pwd)
API=http://127.0.0.1:8080
NODE="$API/v1/workflows/$WF/nodes/pure.add/iterations/0"
post() { echo "POST ${1#$API}"; echo "  body: $2"; curl -sS -w '\n  HTTP %{http_code}\n' -H 'Content-Type: application/json' -X POST "$1" --data "$2" | sed 's/^{/  {/'; }

echo "== 1. freeze both real workers so the race is deterministic"
"$LAB/dc.sh" pause worker-a worker-b >/dev/null 2>&1
"$LAB/submit.sh" "$WF" lab-add pure.add '[1,2,3]' | tail -1
sleep 2

echo "== 2. claim the task with a made-up worker name"
CLAIM=$(curl -sS -H 'Content-Type: application/json' -X POST "$NODE/claim" --data '{"worker_id":"not-a-real-worker","request_id":"forge-req-1"}')
echo "  $CLAIM"
TOKEN=$(echo "$CLAIM" | python3 -c 'import json,sys; print(json.load(sys.stdin)["claim_token"])')

echo "== 3. control: a result with the wrong token"
post "$NODE/result" '{"attempt_number":1,"claim_token":"00000000-0000-4000-8000-000000000000","attempt_state":"SUCCEEDED","payload":999999}'

echo "== 4. the forged result, with the token the API just handed us (1+2+3 is not 999999)"
post "$NODE/result" "{\"attempt_number\":1,\"claim_token\":\"$TOKEN\",\"attempt_state\":\"SUCCEEDED\",\"payload\":999999}"

echo "== 5. replay the same result, then replay it with a different payload"
post "$NODE/result" "{\"attempt_number\":1,\"claim_token\":\"$TOKEN\",\"attempt_state\":\"SUCCEEDED\",\"payload\":999999}"
post "$NODE/result" "{\"attempt_number\":1,\"claim_token\":\"$TOKEN\",\"attempt_state\":\"SUCCEEDED\",\"payload\":6}"

echo "== 6. thaw the real workers and let the workflow finish"
"$LAB/dc.sh" unpause worker-a worker-b >/dev/null 2>&1
until [ "$("$LAB/psql.sh" -At -c "SELECT state FROM engine.workflow_executions WHERE workflow_id='$WF'")" = "SUCCEEDED" ]; do sleep 1; done
"$LAB/psql.sh" -c "SELECT node_id, state, accepted_result FROM engine.node_instances WHERE workflow_id='$WF' ORDER BY node_id"
"$LAB/psql.sh" -c "SELECT node_id, attempt_number AS attempt, state, worker_id FROM engine.activity_attempts WHERE workflow_id='$WF' ORDER BY node_id"
