#!/usr/bin/env bash
# generate-swarm-mapping.sh
#
# Builds the JSON body for the swarm agent-mapping call:
#
#   PATCH /v5/organizations/{organization_id}/swarms/{swarm_id}/mapping
#
# from two sources:
#
#   1. cluster topology, via the Cubbit CLI:
#        cubbit infrastructure location describe --cluster-id <id> --output json
#      (returns [ { cluster_id, name, type, details: { nodes: [ { node_id,
#        node_name, external_ip, internal_ip, disks: [ { disk_uuid, path,
#        used, status } ] } ] } } ])
#
#   2. the agent public key stored on every disk of every node:
#        head -c 32 "/mnt/cubbit/disk-N/config/keypair" | base64 -w0
#
# Field mapping (composer-hub: server_id = node_id, volume_id = disk_uuid):
#   deployment_state = --deployment-state (default "unset")
#   hostname         = node.node_name
#   public_key       = base64 of the first 32 bytes of <disk.path>/config/keypair
#   server_id        = node.node_id
#   volume_id        = disk.disk_uuid
#
# Disks are taken in the numeric order of their path suffix (disk-1, disk-2, …)
# and the keys read over ssh are matched to them in that same order.
#
# Usage
#   ./generate-swarm-mapping.sh --cluster-id <uuid> --nexus-id <uuid> \
#       --ssh-key ~/.ssh/id_rsa --ssh-user root --out mapping.json
#
#   ./generate-swarm-mapping.sh --cluster-id <uuid> --nexus-id <uuid> --dry-run
#   ./generate-swarm-mapping.sh --cluster-id <uuid> --nexus-id <uuid> \
#       --describe-file describe.json --keys-file keys.json   # offline
#
# Notes
#   * --nexus-id is the nexus that hosts the swarm on this cluster; it is
#     returned when the nexus is created and listed by the nexus API
#     (GET /v2/organizations/{org}/swarms/{swarm}/nexuses).
#   * the CLI profile/endpoint are chosen with the usual `cubbit` globals,
#     passed through here with --profile / --config-path.
set -euo pipefail

# ── defaults ────────────────────────────────────────────────────────────────
CLUSTER_ID=""
NEXUS_ID=""
SSH_USER="root"
SSH_KEY="${HOME}/.ssh/id_rsa"
HOST_FIELD="external"
DISKS="0"                 # 0 = use every candidate disk returned by describe
ONLY_UNUSED="true"
DEPLOYMENT_STATE="unset"
CLI="cubbit"
PROFILE=""
CONFIG_PATH=""
JSON_FLAG="--output json"
DESCRIBE_FILE=""
SAVE_DESCRIBE=""
KEYS_FILE=""
SSH_TIMEOUT="15"
SSH_OPTS=()
DRY_RUN="false"
OUT=""

die()  { printf 'error: %s\n' "$*" >&2; exit 1; }
log()  { printf '%s\n' "$*" >&2; }

usage() {
  cat >&2 <<'EOF'
generate-swarm-mapping.sh — build the swarm agent-mapping JSON

Required
  --cluster-id UUID        cluster to read the topology from
  --nexus-id UUID          nexus hosting the swarm on that cluster

Connection
  --ssh-key PATH           private key (default ~/.ssh/id_rsa)
  --ssh-user USER          ssh user (default root)
  --host-field FIELD       external (default) | internal: which IP to ssh to
  --ssh-timeout SEC        default 15
  --ssh-opt ARG            extra ssh option, repeatable (e.g. --ssh-opt -o
                           --ssh-opt ProxyJump=bastion)

Selection / output
  --disks N                expected keypairs per node; 0 (default) = all disks
  --include-used           include disks already marked used
  --deployment-state S     agent deployment_state (default unset)
  --out PATH               write the JSON here (default: stdout)

CLI
  --cli CMD                CLI executable (default cubbit)
  --profile NAME           cubbit --profile
  --config-path PATH       cubbit --config-path
  --json-flag STR          default "--output json" (older/newer CLIs may use
                           "--format json")

Offline / testing
  --describe-file PATH     use this describe JSON instead of calling the CLI
  --save-describe PATH     keep the describe JSON
  --keys-file PATH         do not ssh: JSON {"<host or node_name>": ["key", …]}
  --dry-run                print the ssh commands and exit, no output file
  -h, --help               this help
EOF
}

need_value() { [ $# -ge 2 ] || die "missing value for $1"; }

while [ $# -gt 0 ]; do
  case "$1" in
    --cluster-id)       need_value "$@"; CLUSTER_ID="$2"; shift 2 ;;
    --nexus-id)         need_value "$@"; NEXUS_ID="$2"; shift 2 ;;
    --ssh-key)          need_value "$@"; SSH_KEY="$2"; shift 2 ;;
    --ssh-user)         need_value "$@"; SSH_USER="$2"; shift 2 ;;
    --host-field)       need_value "$@"; HOST_FIELD="$2"; shift 2 ;;
    --disks)            need_value "$@"; DISKS="$2"; shift 2 ;;
    --include-used)     ONLY_UNUSED="false"; shift ;;
    --deployment-state) need_value "$@"; DEPLOYMENT_STATE="$2"; shift 2 ;;
    --cli)              need_value "$@"; CLI="$2"; shift 2 ;;
    --profile)          need_value "$@"; PROFILE="$2"; shift 2 ;;
    --config-path)      need_value "$@"; CONFIG_PATH="$2"; shift 2 ;;
    --json-flag)        need_value "$@"; JSON_FLAG="$2"; shift 2 ;;
    --describe-file)    need_value "$@"; DESCRIBE_FILE="$2"; shift 2 ;;
    --save-describe)    need_value "$@"; SAVE_DESCRIBE="$2"; shift 2 ;;
    --keys-file)        need_value "$@"; KEYS_FILE="$2"; shift 2 ;;
    --ssh-timeout)      need_value "$@"; SSH_TIMEOUT="$2"; shift 2 ;;
    --ssh-opt)          need_value "$@"; SSH_OPTS+=("$2"); shift 2 ;;
    --dry-run)          DRY_RUN="true"; shift ;;
    --out)              need_value "$@"; OUT="$2"; shift 2 ;;
    -h|--help)          usage; exit 0 ;;
    *)                  usage; die "unknown argument: $1" ;;
  esac
done

# ── preconditions ───────────────────────────────────────────────────────────
[ -n "$CLUSTER_ID" ] || { usage; die "--cluster-id is required"; }
[ -n "$NEXUS_ID" ]   || { usage; die "--nexus-id is required"; }
command -v jq >/dev/null 2>&1 || die "jq is required (https://jqlang.github.io/jq/)"
case "$HOST_FIELD" in external|internal) ;; *) die "--host-field must be external or internal" ;; esac
case "$DISKS" in ''|*[!0-9]*) die "--disks must be a number" ;; esac
if [ -z "$KEYS_FILE" ] && [ "$DRY_RUN" != "true" ]; then
  command -v ssh >/dev/null 2>&1 || die "ssh is required"
  [ -r "$SSH_KEY" ] || die "cannot read ssh key $SSH_KEY (use --ssh-key)"
fi

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

# ── 1. cluster topology ─────────────────────────────────────────────────────
read -r -a JSON_ARGS <<< "$JSON_FLAG"
read -r -a CLI_CMD <<< "$CLI"
GLOBAL_ARGS=()
[ -n "$PROFILE" ]     && GLOBAL_ARGS+=(--profile "$PROFILE")
[ -n "$CONFIG_PATH" ] && GLOBAL_ARGS+=(--config-path "$CONFIG_PATH")

describe() {
  if [ -n "$DESCRIBE_FILE" ]; then
    [ -r "$DESCRIBE_FILE" ] || die "cannot read --describe-file $DESCRIBE_FILE"
    cat "$DESCRIBE_FILE"
    return
  fi

  if ! command -v "${CLI_CMD[0]}" >/dev/null 2>&1 && [ ! -x "${CLI_CMD[0]}" ]; then
    die "CLI '${CLI_CMD[0]}' not found (use --cli /path/to/cubbit)"
  fi

  log "-> $CLI ${GLOBAL_ARGS[*]:-} infrastructure location describe --cluster-id $CLUSTER_ID $JSON_FLAG"
  "${CLI_CMD[@]}" "${GLOBAL_ARGS[@]}" infrastructure location describe \
      --cluster-id "$CLUSTER_ID" "${JSON_ARGS[@]}"
}

log "reading cluster $CLUSTER_ID"
describe > "$WORKDIR/describe.json" || die "describe failed"
jq -e . "$WORKDIR/describe.json" >/dev/null 2>&1 \
  || die "describe did not return JSON — try --json-flag '--output json' (or '--format json')"
if [ -n "$SAVE_DESCRIBE" ]; then
  cp "$WORKDIR/describe.json" "$SAVE_DESCRIBE"
  log "describe saved to $SAVE_DESCRIBE"
fi

# describe returns either a single cluster object or an array of them, and may
# or may not echo the requested id back; keep the requested one when it is
# there, otherwise fall back to the first cluster that actually has nodes.
jq -c --arg cid "$CLUSTER_ID" '
  (if type == "array" then . else [.] end) as $all
  | ([ $all[] | select((.cluster_id // "") == $cid) ]) as $match
  | (if ($match | length) > 0 then $match
     else [ $all[] | select(((.details.nodes // .nodes // []) | length) > 0) ] end)
  | if length > 0 then .[0] else empty end
  | (.details.nodes // .nodes // [])
  | .[]
' "$WORKDIR/describe.json" > "$WORKDIR/nodes.ndjson"

NODE_COUNT="$(grep -c . "$WORKDIR/nodes.ndjson" || true)"
[ "${NODE_COUNT:-0}" -gt 0 ] || die "no nodes in the describe output for cluster $CLUSTER_ID"

# ── 2. keys per node + agent entries ────────────────────────────────────────
: > "$WORKDIR/agents.ndjson"
TOTAL=0

key_from_file() { # $1 host, $2 node_name, $3 index
  jq -r --arg h "$1" --arg n "$2" --argjson i "$3" '
    (.[$h] // .[$n] // empty)
    | if type == "array" then .[$i] // empty else empty end
  ' "$KEYS_FILE"
}

while IFS= read -r node; do
  node_id="$(jq -r '.node_id // ""' <<<"$node")"
  node_name="$(jq -r '.node_name // ""' <<<"$node")"
  host="$(jq -r --arg f "$HOST_FIELD" '
    if $f == "external" then (.external_ip // .internal_ip // "")
    else (.internal_ip // .external_ip // "") end' <<<"$node")"

  [ -n "$node_id" ]   || die "a node has no node_id"
  [ -n "$node_name" ] || die "node $node_id has no node_name"
  [ -n "$host" ]      || die "node $node_name has neither external_ip nor internal_ip"

  # candidate disks, ordered by the numeric suffix of the path (disk-1, disk-2, …)
  jq -c --argjson onlyUnused "$ONLY_UNUSED" '
    [ (.disks // [])[]
      | select($onlyUnused == false or (.used // false) == false)
      | {volume_id: .disk_uuid, path: .path, used: (.used // false),
         status: (.status.code // "")}
    ]
    | sort_by((.path | try capture("(?<n>[0-9]+)$").n catch "999999") | tonumber)
  ' <<<"$node" > "$WORKDIR/disks.json"

  disk_count="$(jq 'length' "$WORKDIR/disks.json")"
  if [ "$disk_count" -eq 0 ]; then
    log "warning: $node_name ($host) has no candidate disks — skipped"
    continue
  fi
  if [ "$DISKS" -gt 0 ] && [ "$disk_count" -ne "$DISKS" ]; then
    die "$node_name: $disk_count candidate disks but --disks $DISKS requested (use --disks 0 for all)"
  fi

  paths=()
  while IFS= read -r p; do paths+=("$p"); done < <(jq -r '.[].path' "$WORKDIR/disks.json")
  while IFS=$'\t' read -r p st; do
    case "$st" in
      ""|status_ok|status_in_use|status_warning) ;;
      *) log "warning: $node_name $p has status '$st'" ;;
    esac
  done < <(jq -r '.[] | [.path, .status] | @tsv' "$WORKDIR/disks.json")

  keys=()
  if [ -n "$KEYS_FILE" ]; then
    [ -r "$KEYS_FILE" ] || die "cannot read --keys-file $KEYS_FILE"
    for i in $(seq 0 $((disk_count - 1))); do
      keys+=("$(key_from_file "$host" "$node_name" "$i")")
    done
  else
    remote="for p in"
    for p in "${paths[@]}"; do remote+=" '$p'"; done
    remote+='; do head -c 32 "$p/config/keypair" | base64 -w0; echo; done'

    if [ "$DRY_RUN" = "true" ]; then
      opts=""
      [ "${#SSH_OPTS[@]}" -gt 0 ] && opts=" ${SSH_OPTS[*]}"
      log "[dry-run] ssh -n -i $SSH_KEY$opts $SSH_USER@$host \"$remote\""
      continue
    fi

    log "-> ssh $SSH_USER@$host ($node_name): $disk_count keypair(s)"
    # -n: never let ssh eat the stdin of the node loop
    SSH_CMD=(ssh -n -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=accept-new
             -o ConnectTimeout="$SSH_TIMEOUT")
    if [ "${#SSH_OPTS[@]}" -gt 0 ]; then
      SSH_CMD+=("${SSH_OPTS[@]}")
    fi
    SSH_CMD+=("$SSH_USER@$host" "$remote")

    if ! "${SSH_CMD[@]}" > "$WORKDIR/keys.txt" 2> "$WORKDIR/ssh.err"; then
      cat "$WORKDIR/ssh.err" >&2
      die "ssh failed for $SSH_USER@$host (see the message above)"
    fi
    while IFS= read -r line || [ -n "$line" ]; do keys+=("$line"); done < "$WORKDIR/keys.txt"
  fi

  [ "${#keys[@]}" -eq "$disk_count" ] \
    || die "$node_name: expected $disk_count keys (one per disk), got ${#keys[@]}"

  for i in $(seq 0 $((disk_count - 1))); do
    key="${keys[$i]}"
    [ -n "$key" ] || die "$node_name ${paths[$i]}: empty public key (missing ${paths[$i]}/config/keypair?)"
    decoded="$(printf '%s' "$key" | base64 -d 2>/dev/null | wc -c | tr -d ' ')"
    [ "$decoded" = "32" ] || log "warning: $node_name ${paths[$i]}: key decodes to $decoded bytes, expected 32"

    volume_id="$(jq -r --argjson i "$i" '.[$i].volume_id' "$WORKDIR/disks.json")"
    jq -cn \
      --arg state "$DEPLOYMENT_STATE" \
      --arg host "$node_name" \
      --arg key "$key" \
      --arg server "$node_id" \
      --arg volume "$volume_id" \
      '{deployment_state: $state, hostname: $host, public_key: $key,
        server_id: $server, volume_id: $volume}' >> "$WORKDIR/agents.ndjson"
    TOTAL=$((TOTAL + 1))
  done
done < "$WORKDIR/nodes.ndjson"

if [ "$DRY_RUN" = "true" ]; then
  log "[dry-run] nothing executed, no output written"
  exit 0
fi
[ "$TOTAL" -gt 0 ] || die "no agents produced (no disks or no keys)"

# ── 3. payload ──────────────────────────────────────────────────────────────
jq -n --arg cluster "$CLUSTER_ID" --arg nexus "$NEXUS_ID" \
      --slurpfile agents "$WORKDIR/agents.ndjson" \
      '{cluster_id: $cluster, nexus_id: $nexus, agents: $agents}' \
      > "$WORKDIR/mapping.json"

jq -e '.cluster_id and .nexus_id and (.agents | length > 0)' "$WORKDIR/mapping.json" >/dev/null \
  || die "internal error: produced an invalid mapping"

log "ok: $TOTAL agent(s) on $NODE_COUNT node(s)"
log "next: PATCH /v5/organizations/{organization_id}/swarms/{swarm_id}/mapping with this body"

if [ -n "$OUT" ]; then
  cp "$WORKDIR/mapping.json" "$OUT"
  log "written $OUT"
else
  cat "$WORKDIR/mapping.json"
fi
