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

echo 'Packrift MCP activation wave runner'
echo 'Release: PACKRIFT-MCP-ACTIVATION-WAVE-R05'
echo 'Current external-qualified tool calls: 161/50'
echo 'Threshold wave tasks: 1; full-source capture tasks: 1'
echo 'This is a thin wrapper around the hosted Packrift MCP first-run scripts. It does not create a CLI, checkout surface, or order.'
echo 'Run it from an external reviewer or real MCP host environment. Packrift self-runs do not prove the adoption goal.'
echo 'Set PACKRIFT_ACTIVATION_WAVE_SCOPE=full to run every current source task instead of only the threshold-clearing wave.'

if [ "${PACKRIFT_EXTERNAL_ACTIVATION:-}" != "1" ]; then
  echo ''
  echo 'Refusing to execute until PACKRIFT_EXTERNAL_ACTIVATION=1 is set.'
  echo 'Copy one of these source-specific commands into the real external host or reviewer environment:'
  echo 'curl -sS '\''https://mcp.packrift.com/r/run/mcp_so/generic_streamable_http?format=sh'\'' | bash'
  echo ''
  echo 'Or explicitly run the guarded wave bundle: PACKRIFT_EXTERNAL_ACTIVATION=1 curl -sS https://mcp.packrift.com/ai/mcp-activation-wave-runner.sh | bash'
  echo 'Or run the full-source capture bundle: PACKRIFT_EXTERNAL_ACTIVATION=1 PACKRIFT_ACTIVATION_WAVE_SCOPE=full curl -sS https://mcp.packrift.com/ai/mcp-activation-wave-runner.sh | bash'
  exit 2
fi

wave_scope="${PACKRIFT_ACTIVATION_WAVE_SCOPE:-threshold}"
case "$wave_scope" in
  threshold|full) ;;
  *)
    echo "Unsupported PACKRIFT_ACTIVATION_WAVE_SCOPE=$wave_scope. Use threshold or full."
    exit 2
    ;;
esac
echo "Activation wave scope: $wave_scope"

run_wave_task() {
  local rank="$1"
  local source="$2"
  local script_url="$3"
  local expected_lift="$4"
  local tmp_file
  tmp_file="$(mktemp)"
  trap 'rm -f "$tmp_file"' RETURN
  echo ''
  echo "[$rank] Running Packrift MCP source activation: $source (expected tool-call lift: $expected_lift)"
  echo "Fetching existing first-run script: $script_url"
  curl -fsSL "$script_url" -o "$tmp_file"
  PACKRIFT_MCP_SESSION_ID="mcp-wave-${source}-$(date -u +%Y%m%dT%H%M%SZ)-$RANDOM" bash "$tmp_file"
}

if [ "$wave_scope" = "full" ]; then
run_wave_task '1' 'mcp_so' 'https://mcp.packrift.com/r/run/mcp_so/generic_streamable_http?format=sh' '4'
else
run_wave_task '1' 'mcp_so' 'https://mcp.packrift.com/r/run/mcp_so/generic_streamable_http?format=sh' '4'
fi

echo ''
echo 'Packrift MCP activation wave runner finished.'
echo 'Review proof after telemetry settles:'
echo 'https://mcp.packrift.com/ai/mcp-source-activation-queue.json'
echo 'https://mcp.packrift.com/ai/mcp-funnel-snapshot.json'
