#!/usr/bin/env bash
# Stale segment sweep
# Segments nobody has sent to, and segments that now match zero contacts. Both quietly rot after a season and make the segment list unusable.
#
# Category : Data hygiene
# Safety   : read only
# Uses     : groups list, contacts list, campaigns list
# Returns  : Empty segments, and segments not referenced by any live campaign.
#
# Requires the SendSquared CLI and jq:
#   curl -fsSL https://cli.sendsquared.com/install.sh | bash
#   sendsquared auth login
#
# Free to use and adapt. https://sendsquared.com/cli/scripts/#stale-segments

# Segments that are empty, and segments no live campaign targets.
#
# Note the variable name: GROUPS is a reserved array in bash (the caller's
# group memberships), so assigning to it silently does nothing and the script
# reads back a group id instead of the API response.
set -euo pipefail

SEGMENTS=$(sendsquared groups list --type segment)
TOTAL=$(jq '[.data[]?] | length' <<<"$SEGMENTS")
echo "--- $TOTAL segments"

USED=$(sendsquared campaigns list --limit 500 | jq -r '[.data[]? | .action_id // empty] | unique | join(" ")')

echo
echo "empty segments"
EMPTY=0
while IFS=$'\t' read -r ID NAME; do
  [ -z "$ID" ] && continue
  N=$(sendsquared contacts list --group "$ID" --limit 1 2>/dev/null | jq '[.data[]?] | length')
  if [ "${N:-0}" -eq 0 ]; then echo "  $ID  $NAME"; EMPTY=$((EMPTY+1)); fi
done < <(jq -r '.data[]? | [.id, (.name // "untitled")] | @tsv' <<<"$SEGMENTS")
if [ "$EMPTY" -eq 0 ]; then echo "  none"; fi

echo
echo "segments no live campaign targets"
UNUSED=0
while IFS=$'\t' read -r ID NAME; do
  [ -z "$ID" ] && continue
  case " $USED " in *" $ID "*) : ;; *) echo "  $ID  $NAME"; UNUSED=$((UNUSED+1)) ;; esac
done < <(jq -r '.data[]? | [.id, (.name // "untitled")] | @tsv' <<<"$SEGMENTS")
if [ "$UNUSED" -eq 0 ]; then echo "  none"; fi
