#!/usr/bin/env bash
#
# Remove quickstart objects from Padas Core using the same IDs as
# padas-quickstart-core-api.json (same bundle padas_quickstart_push_to_core.py applies).
# Requires: curl, jq
#
# Usage:
#   ./padas_quickstart_delete_from_core.sh \
#     --core-url "https://127.0.0.1:8999" \
#     --token-file /opt/padas/core/data/security/service-account.token \
#     [--bundle /path/to/padas-quickstart-core-api.json] \
#     [--insecure]
#
#   # or: --token "$(jq -r '.token' ...)"  (paste carefully — no spaces inside the secret)
#
# Default bundle: ../config/padas-quickstart-core-api.json next to this script.
#
# --core-url is the API origin only (scheme + host + port), e.g. https://127.0.0.1:8999
# — do not append /api/v1 (this script adds path segments below).
#
# Stop (optional cleanup before delete), then DELETE resources:
#   POST  {base_url}/api/v1/connectors/{id}/stop
#   POST  {base_url}/api/v1/tasks/{id}/stop
#   DELETE {base_url}/api/v1/connectors/{id}
#   DELETE {base_url}/api/v1/tasks/{id}
#   DELETE {base_url}/api/v1/pipelines/{id}   (404 ignored if not exposed on Core)
#   DELETE {base_url}/api/v1/streams/{id}
#
# Stops run in reverse order of .starts_in_order; DELETE lists follow the bundle file.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CORE_URL=""
TOKEN=""
TOKEN_FILE=""
BUNDLE_JSON="${SCRIPT_DIR}/../config/padas-quickstart-core-api.json"
INSECURE=0

print_help() {
  cat >&2 <<'EOF'
Remove quickstart objects from Padas Core (IDs from padas-quickstart-core-api.json). Requires: curl, jq.

Usage:
  padas_quickstart_delete_from_core.sh --core-url URL --token TOKEN [options]

Required:
  --core-url URL          Core API origin only: https://host:port (no /api/v1 suffix)

  Exactly one of:
  --token TOKEN           Raw Bearer secret (no line breaks; avoid stray spaces)
  --token-file PATH       JSON file with a "token" field (same as service-account.token)

Options:
  --bundle PATH           padas-quickstart-core-api.json (default: ../config/ beside this script)
  --registry-json PATH    Same as --bundle (deprecated alias)
  --insecure              Pass curl --insecure (self-signed lab TLS)
  -h, --help              Show this help

Example:
  padas_quickstart_delete_from_core.sh \
    --core-url "https://127.0.0.1:8999" \
    --token-file /opt/padas/core/data/security/service-account.token \
    --insecure
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --core-url)
      CORE_URL="${2:?}"
      shift 2
      ;;
    --token)
      TOKEN="${2:?}"
      shift 2
      ;;
    --token-file)
      TOKEN_FILE="${2:?}"
      shift 2
      ;;
    --bundle)
      BUNDLE_JSON="${2:?}"
      shift 2
      ;;
    --registry-json)
      # backwards compatibility (same file type as --bundle now)
      BUNDLE_JSON="${2:?}"
      shift 2
      ;;
    --insecure)
      INSECURE=1
      shift
      ;;
    -h|--help)
      print_help
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      print_help
      exit 1
      ;;
  esac
done

if [[ -z "${CORE_URL}" ]]; then
  echo "Required: --core-url" >&2
  print_help
  exit 1
fi

if [[ -n "${TOKEN}" && -n "${TOKEN_FILE}" ]]; then
  echo "Use only one of --token or --token-file." >&2
  exit 1
fi
if [[ -z "${TOKEN}" && -z "${TOKEN_FILE}" ]]; then
  echo "Required: --token or --token-file" >&2
  print_help
  exit 1
fi

if [[ -n "${TOKEN_FILE}" ]]; then
  if [[ ! -f "${TOKEN_FILE}" ]]; then
    echo "Token file not found: ${TOKEN_FILE}" >&2
    exit 1
  fi
  TOKEN="$(jq -r '.token // empty' "${TOKEN_FILE}")"
fi

# trim leading/trailing whitespace (common paste issue)
CORE_URL="${CORE_URL#"${CORE_URL%%[![:space:]]*}"}"
CORE_URL="${CORE_URL%"${CORE_URL##*[![:space:]]}"}"
TOKEN="${TOKEN#"${TOKEN%%[![:space:]]*}"}"
TOKEN="${TOKEN%"${TOKEN##*[![:space:]]}"}"

if [[ -z "${TOKEN}" ]]; then
  echo "Token is empty after reading/trimming." >&2
  exit 1
fi
if [[ "${TOKEN}" == *[[:space:]]* ]]; then
  echo "warning: token still contains spaces or tabs — Core often returns 401. Prefer --token-file or jq -r with no line wrap." >&2
fi

if [[ ! -f "${BUNDLE_JSON}" ]]; then
  echo "Bundle file not found: ${BUNDLE_JSON}" >&2
  exit 1
fi

BASE="${CORE_URL%/}"
# Accept https://host:8999/api/v1 if pasted by mistake
if [[ "${BASE}" == */api/v1 ]]; then
  BASE="${BASE%/api/v1}"
  BASE="${BASE%/}"
fi

# Bearer only — no Content-Type on empty-body POST/DELETE (matches typical Core curl examples)
AUTH_BEARER=(-H "Authorization: Bearer ${TOKEN}")
CURL_EXTRA=()
if [[ "${INSECURE}" -eq 1 ]]; then
  CURL_EXTRA+=(--insecure)
fi

BODY_FILE="$(mktemp "${TMPDIR:-/tmp}/padas_quickstart_del.XXXXXX")"
trap 'rm -f "${BODY_FILE}"' EXIT

# args: method path
# prints one line to stdout; 2xx and 404 count as success for idempotent cleanup
api() {
  local method="$1"
  local path="$2"
  local url="${BASE}${path}"
  local code shellcode
  set +e
  code="$(
    curl -sS "${CURL_EXTRA[@]}" "${AUTH_BEARER[@]}" -o "${BODY_FILE}" -w '%{http_code}' \
      -X "${method}" "${url}" </dev/null
  )"
  shellcode=$?
  set -e
  if [[ "$shellcode" -ne 0 ]]; then
    echo "${method} ${path} -> transport error (curl exit ${shellcode})" >&2
    return "$shellcode"
  fi
  if [[ "$code" =~ ^2 ]] || [[ "$code" == "404" ]]; then
    echo "${method} ${path} -> HTTP ${code}"
    return 0
  fi
  echo "${method} ${path} -> HTTP ${code}" >&2
  if [[ -s "${BODY_FILE}" ]]; then
    head -c 800 "${BODY_FILE}" >&2 || true
    echo >&2
  fi
  return 1
}

echo "Using bundle: ${BUNDLE_JSON}"
echo "Core base: ${BASE}"
echo

# --- stop: reverse of .starts_in_order (connector vs task paths) ---
while IFS=$'\t' read -r kind id; do
  [[ -n "${kind}" && -n "${id}" ]] || continue
  if [[ "${kind}" == "connector" ]]; then
    api POST "/api/v1/connectors/${id}/stop" || true
  elif [[ "${kind}" == "task" ]]; then
    api POST "/api/v1/tasks/${id}/stop" || true
  fi
done < <(jq -r '.starts_in_order | reverse | .[] | "\(.kind)\t\(.id)"' "${BUNDLE_JSON}")

echo

# --- delete connectors, task, optional pipelines, streams ---
while read -r id; do
  [[ -n "$id" ]] || continue
  api DELETE "/api/v1/connectors/${id}" || true
done < <(jq -r '.connectors[]?.connector.id // empty' "${BUNDLE_JSON}")

while read -r id; do
  [[ -n "$id" ]] || continue
  api DELETE "/api/v1/tasks/${id}" || true
done < <(jq -r 'if (.task != null) and (.task.task != null) then .task.task.id else empty end' "${BUNDLE_JSON}")

while read -r id; do
  [[ -n "$id" ]] || continue
  api DELETE "/api/v1/pipelines/${id}" || true
done < <(jq -r '.pipelines[]?.id // empty' "${BUNDLE_JSON}")

while read -r id; do
  [[ -n "$id" ]] || continue
  api DELETE "/api/v1/streams/${id}" || true
done < <(jq -r '.streams[]?.stream.id // empty' "${BUNDLE_JSON}")

echo
echo "Done. Re-check: GET ${BASE}/api/v1/status (same --token / TLS options you use for Core)."
