#!/usr/bin/env bash

set -euo pipefail

readonly DEFAULT_NAMESPACE="tidb-serverless"
readonly APP_SELECTOR="app.kubernetes.io/name=cse-pack-backup-offline"
readonly PACK_BACKUP_PREFIX_ANNOTATION="cse.tidbcloud.com/pack-backup-prefix"

usage() {
  cat <<'EOF'
Usage:
  list-completed-pack-backup-offline-tasks.sh -l SELECTOR [OPTIONS]

Options:
  -l, --selector=SELECTOR        Additional Job label selector (required)
  -n, --namespace=NAMESPACE     Kubernetes namespace (default: tidb-serverless)
  -h, --help                    Show this help

The script performs one batched Job query and keeps only Complete=True Jobs.
It reads the packed-backup prefix from the required Job annotation. A completed
Job without a valid annotation makes collection fail. It prints a JSON array
with this shape:

  [{"task_name":"<job-name>","pack_backup_prefix":"s3://.../<pack-id>/"}]

Example:
  list-completed-pack-backup-offline-tasks.sh \
    -l app.kubernetes.io/instance=pack-backup-offline-20260720-120000
EOF
}

die() {
  echo "error: $*" >&2
  exit 1
}

take_value() {
  local option="$1"
  local value="${2-}"
  [[ -n "$value" ]] || die "$option requires a value"
  printf '%s' "$value"
}

namespace="$DEFAULT_NAMESPACE"
selector=""

while (($# > 0)); do
  case "$1" in
    -l|--selector)
      shift
      selector="$(take_value --selector "${1-}")"
      ;;
    --selector=*)
      selector="$(take_value --selector "${1#*=}")"
      ;;
    -n|--namespace)
      shift
      namespace="$(take_value --namespace "${1-}")"
      ;;
    --namespace=*)
      namespace="$(take_value --namespace "${1#*=}")"
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "unknown argument '$1'"
      ;;
  esac
  shift
done

[[ -n "$selector" ]] || die "-l/--selector is required"

command -v kubectl >/dev/null || die "kubectl is required"
command -v jq >/dev/null || die "jq is required"

combined_selector="${APP_SELECTOR},${selector}"
jobs_json="$(kubectl --request-timeout=30s -n "$namespace" \
  get jobs -l "$combined_selector" -o json)"

jq -ce --arg annotation "$PACK_BACKUP_PREFIX_ANNOTATION" '
  [
    .items[]
    | select(any(.status.conditions[]?; .type == "Complete" and .status == "True"))
    | .metadata.name as $task_name
    | (.metadata.annotations // {}) as $annotations
    | if ($annotations | type) != "object" then
        error("missing required packed-backup prefix annotation on Job \($task_name)")
      elif ($annotations | has($annotation) | not) then
        error("missing required packed-backup prefix annotation on Job \($task_name)")
      else
        $annotations[$annotation] as $prefix
        | if ($prefix | type) != "string" then
            error("invalid packed-backup prefix annotation on Job \($task_name): expected a string")
          elif ($prefix | test("^s3://[^/]+/.+/$") | not) then
            error("invalid packed-backup prefix annotation on Job \($task_name): \($prefix)")
          else
            {
              task_name: $task_name,
              pack_backup_prefix: $prefix
            }
          end
      end
  ]
  | sort_by(.task_name)
' <<<"$jobs_json"
