#!/usr/bin/env bash
set -euo pipefail

usage() {
  local script_ref
  script_ref="$0"

  cat <<EOF
Usage:
  $script_ref 'user:password' <SolrURL> '<perm1,perm2,perm3>' [apply] [backup-dir]

Arguments:
  user:password            Solr basic auth credentials
  SolrURL                  Solr base URL including /solr (e.g. https://host/solr)
  perm1,perm2,perm3        Comma-separated permission names to remove
  apply                    Optional. Omit for dry-run. Set to 'apply' to execute changes.
  backup-dir               Optional. Default: ./security-migration-backups

Examples:
  $script_ref \
    'admin:SolrRocks' \
    'https://my-solr.example.com/solr' \
    'metrics-history-read,autoscaling-read,autoscaling-write'

  $script_ref \
    'admin:SolrRocks' \
    'https://my-solr.example.com/solr' \
    'metrics-history-read,autoscaling-read,autoscaling-write' \
    apply

Requirements:
  - curl
  - jq
EOF
}

if [[ $# -lt 3 ]]; then
  usage
  exit 1
fi

USER_PASSWD="$1"
SOLR_URL="${2%/}"
PERMISSIONS_CSV="$3"
MODE="${4:-dry-run}"
BACKUP_ROOT="${5:-./security-migration-backups}"

if ! command -v curl >/dev/null 2>&1; then
  echo "Error: curl not found in PATH"
  exit 2
fi

if ! command -v jq >/dev/null 2>&1; then
  echo "Error: jq not found in PATH"
  exit 2
fi

if [[ "$MODE" != "dry-run" && "$MODE" != "apply" ]]; then
  echo "Error: 4th argument must be either 'apply' or omitted."
  usage
  exit 1
fi

TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
SAFE_CLUSTER="$(printf '%s' "$SOLR_URL" | tr -c '[:alnum:].-' '_')"
BACKUP_DIR="$BACKUP_ROOT/$SAFE_CLUSTER-$TIMESTAMP"
mkdir -p "$BACKUP_DIR"

BEFORE_JSON="$BACKUP_DIR/authorization-before.json"
AFTER_JSON="$BACKUP_DIR/authorization-after.json"

echo "Fetching current authorization policy: $SOLR_URL/admin/authorization"
curl -fsS -u "$USER_PASSWD" "$SOLR_URL/admin/authorization" > "$BEFORE_JSON"

TARGETS_JSON="$(printf '%s' "$PERMISSIONS_CSV" | tr ',' '\n' | sed 's/^ *//;s/ *$//' | awk 'NF' | jq -Rsc 'split("\n") | map(select(length>0))')"

PLAN_JSON="$(jq -c --argjson targets "$TARGETS_JSON" '
  (.permissions // .authorization.permissions // [])
  | [ .[]
      | select((.name // "") as $n | $targets | index($n))
      | {name: .name, index: (.index // 0)}
    ]
  | map(select(.index > 0))
  | sort_by(.index)
  | reverse
' "$BEFORE_JSON")"

PLAN_COUNT="$(jq 'length' <<<"$PLAN_JSON")"
if [[ "$PLAN_COUNT" -eq 0 ]]; then
  echo "No matching permissions found. Nothing to change."
  echo "Backup saved to: $BACKUP_DIR"
  exit 0
fi

echo "Planned removals:"
jq -r '.[] | "  - name=\(.name) index=\(.index)"' <<<"$PLAN_JSON"

if [[ "$MODE" != "apply" ]]; then
  echo "Dry-run only. Re-run with 'apply' as 4th argument to execute changes."
  echo "Backup saved to: $BACKUP_DIR"
  exit 0
fi

while IFS= read -r item; do
  idx="$(jq -r '.index' <<<"$item")"
  name="$(jq -r '.name' <<<"$item")"
  payload="$(jq -cn --argjson i "$idx" '{"delete-permission":$i}')"

  echo "Deleting permission: name=$name index=$idx"
  curl -fsS -u "$USER_PASSWD" \
    -H 'Content-Type: application/json' \
    -d "$payload" \
    "$SOLR_URL/admin/authorization" >/dev/null
done < <(jq -c '.[]' <<<"$PLAN_JSON")

curl -fsS -u "$USER_PASSWD" "$SOLR_URL/admin/authorization" > "$AFTER_JSON"

REMAINING_JSON="$(jq -c --argjson targets "$TARGETS_JSON" '
  (.permissions // .authorization.permissions // [])
  | [ .[]
      | select((.name // "") as $n | $targets | index($n))
      | .name
    ]
  | unique
' "$AFTER_JSON")"

REMAINING_COUNT="$(jq 'length' <<<"$REMAINING_JSON")"
if [[ "$REMAINING_COUNT" -gt 0 ]]; then
  echo "Error: some target permissions still remain: $(jq -r 'join(", ")' <<<"$REMAINING_JSON")"
  echo "Check backups in: $BACKUP_DIR"
  exit 3
fi

echo "Migration successful."
echo "Backups:"
echo "  before: $BEFORE_JSON"
echo "  after : $AFTER_JSON"
