#!/usr/bin/env bash
# Pause, resume or stop a campaign, checking first that the action is allowed. Needs: curl, jq.
#   ACTION=pause|resume|stop CAMPAIGN_ID=cmp_... ./campaign-action.sh
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
: "${CAMPAIGN_ID:?Set CAMPAIGN_ID to a campaign id (cmp_...)}"
case "${ACTION:-}" in pause|resume|stop) ;; *) echo "Set ACTION to pause, resume or stop" >&2; exit 2 ;; esac
AUTH="Authorization: Bearer $RELATIONSAI_API_KEY"

campaign=$(curl -sS --fail-with-body "$BASE/campaigns/$CAMPAIGN_ID" -H "$AUTH") || { echo "$campaign" >&2; exit 1; }
if [ "$(jq -r --arg a "$ACTION" '.capabilities[$a]' <<<"$campaign")" != "true" ]; then
  echo "$ACTION is not allowed while the campaign is $(jq -r '.status' <<<"$campaign")" >&2
  exit 1
fi

# No automatic retry: every request runs. If this fails or times out, read the campaign before sending it again.
result=$(curl -sS --fail-with-body --max-time 30 -X POST "$BASE/campaigns/$CAMPAIGN_ID/$ACTION" -H "$AUTH") ||
  { echo "$result" >&2; echo "Read the campaign (GET /campaigns/$CAMPAIGN_ID) before sending the action again." >&2; exit 1; }
jq -r --arg a "$ACTION" '"\($a): \(.id) is now \(.status)"' <<<"$result"
