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

usage() {
  echo "Usage: $0 -g <resource-group> -n <app-gateway-name> [--execute] [--exclude-regex '<pattern>']"
  echo "  Without --execute this runs in DRY-RUN mode and only prints what it would delete."
  exit 1
}

RG=""
APPGW=""
EXECUTE=false
EXCLUDE_REGEX=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    -g|--resource-group) RG="$2"; shift 2 ;;
    -n|--name)           APPGW="$2"; shift 2 ;;
    --execute)           EXECUTE=true; shift ;;
    --exclude-regex)     EXCLUDE_REGEX="$2"; shift 2 ;;
    -h|--help)           usage ;;
    *) echo "Unknown arg: $1"; usage ;;
  esac
done

[[ -z "$RG" || -z "$APPGW" ]] && usage
[[ "$EXECUTE" != "true" ]] && echo "Performing dry run..."


tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

all="$tmpdir/all.txt"
used="$tmpdir/used.txt"
unused="$tmpdir/unused.txt"

echo "Fetching SSL certificates for $APPGW in RG $RG ..."
az network application-gateway ssl-cert list -g "$RG" --gateway-name "$APPGW" --query "[].name" -o tsv \
  | sort -u > "$all"

echo "Discovering certificates referenced by HTTPS listeners ..."
# Collect names from httpListeners that have an sslCertificate
az network application-gateway show -g "$RG" -n "$APPGW" \
  --query "httpListeners[?sslCertificate!=null].sslCertificate.id" -o tsv \
  | awk -F/ '{print $NF}' | sort -u > "$used" || true

ALL_CNT="$(wc -l < "$all" | xargs)"
USED_CNT="$(wc -l < "$used" | xargs || echo 0)"

echo "Total certs: $ALL_CNT"
echo "Used certs : $USED_CNT"

# Compute set difference: all - used
comm -23 "$all" "$used" > "$unused"

# Optional: filter out anything matching an exclude regex
if [[ -n "$EXCLUDE_REGEX" ]]; then
  echo "Applying exclude-regex: $EXCLUDE_REGEX"
  # grep -Ev "$EXCLUDE_REGEX" "$unused" > "$unused.filtered" || true
  grep -P -v "$EXCLUDE_REGEX" "$unused" > "$unused.filtered" || true
  mv "$unused.filtered" "$unused"
fi

echo
if [[ ! -s "$unused" ]]; then
  echo "No unreferenced certificates found. Nothing to do."
  exit 0
fi

echo "Unreferenced certificates:"
nl -ba "$unused"
echo

if $EXECUTE; then
  echo "Deleting unreferenced certificates..."
  while read -r CERT; do
    [[ -z "$CERT" ]] && continue
    echo " - Deleting: $CERT"
    az network application-gateway ssl-cert delete -g "$RG" --gateway-name "$APPGW" --name "$CERT"
  done < "$unused"

  echo "Done. You should now be below the 100-certificate limit."
  echo "Tip: restart AGIC to reconcile faster:"
  echo "  kubectl -n kube-system rollout restart deploy/ingress-appgw-deployment"
else
  echo "DRY-RUN complete. Re-run with --execute to delete the above certificates."
fi
