#!/usr/bin/env bash
# bucketc-onboard-deploy.sh <"Client Name"> <bd_company_id> <slug>
# Onboards a GuruRMM client+site, vaults the key, then deploys the agent to every
# machine in the client's Bitdefender company that has a ScreenConnect session.
# Part of the GPS->RMM coverage audit (Bucket C). Idempotent guard on existing client.
set -u
ROOT="${CLAUDETOOLS_ROOT:-/c/claudetools}"; VR="D:/vault"
NAME="$1"; BDC="$2"; SLUG="$3"
GZ="bash $ROOT/.claude/scripts/py.sh C:/claudetools/.claude/skills/bitdefender/scripts/gz.py"
SC="bash $ROOT/.claude/scripts/py.sh C:/claudetools/.claude/skills/screenconnect/scripts/sc.py"
eval "$(bash $ROOT/.claude/scripts/rmm-auth.sh 2>/dev/null)" >/dev/null

EX=$(curl -s "$RMM/api/clients" -H "Authorization: Bearer $TOKEN" | tr -d '\000-\037' | jq -r --arg n "$NAME" '.[]|select(.name|ascii_downcase==($n|ascii_downcase))|.id')
if [ -n "$EX" ]; then echo "[$NAME] already a client ($EX) — skipping onboard"; CID="$EX";
  SC_CODE=$(curl -s "$RMM/api/clients/$CID/sites" -H "Authorization: Bearer $TOKEN" | tr -d '\000-\037' | jq -r '.[0].site_code'); SID_SITE="";
else
  CID=$(curl -s -X POST "$RMM/api/clients" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" --data-binary "{\"name\":\"$NAME\"}" | tr -d '\000-\037' | jq -r '.id')
  RESP=$(curl -s -X POST "$RMM/api/sites" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" --data-binary "{\"client_id\":\"$CID\",\"name\":\"Main\"}" | tr -d '\000-\037')
  SID_SITE=$(echo "$RESP" | jq -r '.site.id'); SC_CODE=$(echo "$RESP" | jq -r '.site.site_code'); AKEY=$(echo "$RESP" | jq -r '.api_key')
  echo "[$NAME] onboarded: site_code=$SC_CODE"
  T="$VR/clients/$SLUG/gururmm-site-main.sops.yaml"; mkdir -p "$(dirname "$T")"
  cat > "$T" <<YAML
client: $NAME
site: Main
created: "2026-07-03"
credentials:
    client_id: "$CID"
    site_id: "$SID_SITE"
    site_code: "$SC_CODE"
    api_key: "$AKEY"
    installer_url: "https://rmm.azcomputerguru.com/install/$SC_CODE"
YAML
  sops --config "$VR/.sops.yaml" --encrypt --in-place "$T" 2>/dev/null && echo "[$NAME] vaulted (clients/$SLUG/gururmm-site-main.sops.yaml)"
fi

ENC=$(py -c "import base64;print(base64.b64encode(\"irm 'https://rmm.azcomputerguru.com/install/$SC_CODE/windows'|iex\".encode('utf-16-le')).decode())")
CMD="powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand $ENC"
MACHINES=$($GZ endpoints --company "$BDC" 2>/dev/null | grep -E '^  [0-9a-f]{24}' | awk '{print $2}' | sort -u)
sent=0; nosc=0
for h in $MACHINES; do
  SID=$($SC raw --method GetSessionsByName --body "{\"sessionName\":\"$h\"}" 2>/dev/null | tr -d '\000-\037' | jq -r '.[0].SessionID // empty')
  if [ -z "$SID" ]; then nosc=$((nosc+1)); continue; fi
  $SC send-command --session "$SID" --command "$CMD" --confirm >/dev/null 2>&1
  sent=$((sent+1))
done
echo "[$NAME] site=$SC_CODE  BD_machines=$(echo "$MACHINES"|wc -w)  deployed_via_SC=$sent  no_SC=$nosc"
