← back to Marketing Command Center

scripts/fix-connie-creds.sh

64 lines

#!/usr/bin/env bash
# fix-connie-creds.sh — repair the Kamatera cc-agent ("Connie") Constant Contact
# OAuth creds from the local secrets-manager master .env, staged:
#   1. Sync CC_API_KEY / CC_CLIENT_SECRET into Connie's .env, restart, test.
#   2. Only if refresh still fails, inject the master refresh token into
#      .cc-token.json (CC rotates refresh tokens — don't clobber a live one
#      unless the stored one is already dead), restart, test again.
# Prints last-4 digests only — never full secrets.
set -euo pipefail

SM_ENV="$HOME/Projects/secrets-manager/.env"
HOST="root@45.61.58.125"
CC_DIR="/root/DW-Agents/cc-agent"

CID=$(grep '^CC_CLIENT_ID=' "$SM_ENV" | cut -d= -f2)
CSEC=$(grep '^CC_CLIENT_SECRET=' "$SM_ENV" | cut -d= -f2)
CRT=$(grep '^CC_REFRESH_TOKEN=' "$SM_ENV" | cut -d= -f2)
[ -n "$CID" ] && [ -n "$CSEC" ] || { echo "missing CC creds in $SM_ENV"; exit 1; }
echo "master creds: client_id …${CID: -4}  secret …${CSEC: -4}  refresh …${CRT: -4}"

# Stage 1: sync client id + secret into Connie's env (values passed on stdin,
# never on a command line / never echoed).
printf '%s\n%s\n' "$CID" "$CSEC" | ssh "$HOST" "
  cd $CC_DIR
  read -r cid; read -r csec
  old_k=\$(grep '^CC_API_KEY=' .env | cut -d= -f2 || true)
  old_s=\$(grep '^CC_CLIENT_SECRET=' .env | cut -d= -f2 || true)
  echo \"connie had: api_key …\${old_k: -4}  secret …\${old_s: -4}\"
  grep -q '^CC_API_KEY=' .env && sed -i \"s|^CC_API_KEY=.*|CC_API_KEY=\$cid|\" .env || echo \"CC_API_KEY=\$cid\" >> .env
  grep -q '^CC_CLIENT_SECRET=' .env && sed -i \"s|^CC_CLIENT_SECRET=.*|CC_CLIENT_SECRET=\$csec|\" .env || echo \"CC_CLIENT_SECRET=\$csec\" >> .env
  pm2 restart cc-agent --update-env >/dev/null 2>&1
"
echo "stage 1 done (client creds synced, cc-agent restarted). testing..."
sleep 4

test_connie() {
  ssh "$HOST" "pass=\$(grep '^ADMIN_PASS=' $CC_DIR/.env | cut -d= -f2); curl -s -m 12 -u \"admin:\$pass\" http://127.0.0.1:9820/api/campaigns | head -c 300"
}

R1=$(test_connie)
if echo "$R1" | grep -qi '"error"'; then
  echo "still failing after secret fix: $R1"
  echo "stage 2: injecting master refresh token into .cc-token.json..."
  printf '%s\n' "$CRT" | ssh "$HOST" "
    cd $CC_DIR
    read -r crt
    cp .cc-token.json .cc-token.json.bak-\$(date +%s) 2>/dev/null || true
    python3 - \"\$crt\" <<'PY'
import json, sys, os
p = '.cc-token.json'
d = json.load(open(p)) if os.path.exists(p) else {}
d['refresh_token'] = sys.argv[1]
d['expires_at'] = 0  # force immediate refresh
json.dump(d, open(p, 'w'), indent=2)
PY
    pm2 restart cc-agent >/dev/null 2>&1
  "
  sleep 4
  R2=$(test_connie)
  echo "after refresh-token inject: $R2"
else
  echo "connie OK: $R1"
fi