#!/usr/bin/env bash

set -euo pipefail

SCRIPT_NAME="$(basename "$0")"

DEFAULT_SSH_USER="root"
DEFAULT_SSH_PORT="22"
DEFAULT_K3S_VERSION="v1.36.5+k3s1"
DEFAULT_K3SUP_VERSION="0.13.11"
DEFAULT_NAMESPACE="cubbit"
DEFAULT_KUBECONFIG_DIR="${HOME}/.kube"
CUBBIT_MOUNT_BASE="/mnt/cubbit"

if [[ -t 1 && "${TERM:-}" != "dumb" ]]; then
  RED="$(printf '\033[0;31m')"
  GREEN="$(printf '\033[0;32m')"
  YELLOW="$(printf '\033[1;33m')"
  BLUE="$(printf '\033[0;34m')"
  NC="$(printf '\033[0m')"
else
  RED=""
  GREEN=""
  YELLOW=""
  BLUE=""
  NC=""
fi

NODES_RAW=""
CONTEXT=""
SSH_KEY=""
SSH_USER="$DEFAULT_SSH_USER"
SSH_PORT="$DEFAULT_SSH_PORT"
K3S_VERSION="$DEFAULT_K3S_VERSION"
K3SUP_VERSION="$DEFAULT_K3SUP_VERSION"
NAMESPACE="$DEFAULT_NAMESPACE"
KUBECONFIG_DIR="$DEFAULT_KUBECONFIG_DIR"
TLS_SAN=""
K3S_EXTRA_ARGS=""
FORCE="no"
SKIP_PREFLIGHT="no"
DELETE_MODE="no"
AUTO_YES="no"

K3SUP_BIN=""
KUBECONFIG_PATH=""
CONTROL_PLANE_NODE=""
CONTROL_PLANE_REUSE="no"

declare -a NODES=()
declare -a WORKER_NODES=()
declare -a WORKERS_TO_JOIN=()
declare -a PREFLIGHT_OUTPUTS=()

usage() {
  cat <<EOF
Create a multi-node k3s cluster over SSH using a pinned k3sup version.

Topology:
  The first node in --nodes is the k3s control plane. Every other node joins the
  cluster as a worker. Disks are NOT formatted, mounted, or modified; this
  script assumes the Cubbit data disks were already prepared by Ansible.

Usage:
  ${SCRIPT_NAME} --nodes <ip1,ip2,...> --context <name> --ssh-key <path> [options]
  ${SCRIPT_NAME} --nodes <ip1,ip2,...> --ssh-key <path> --delete [options]

Required:
  --nodes <list>              Ordered comma-separated node list. The first entry
                              is the control plane, the rest are workers. Each entry must
                              be an IPv4 address (<ipv4>) or <ipv4>:<ssh_port> to
                              override the common SSH port
                              (example: 10.0.0.1,10.0.0.2:2222).
  --context <name>            Kubeconfig context name (required unless --delete).
                              The kubeconfig is written to
                              ${DEFAULT_KUBECONFIG_DIR}/kubeconfig-<name>.yaml
  --ssh-key <path>            SSH private key used for every node.

Options:
  --user <user>               SSH user. Default: ${DEFAULT_SSH_USER}
  --ssh-port <port>           Common SSH port. Default: ${DEFAULT_SSH_PORT}
  --k3s-version <version>     k3s version. Default: ${DEFAULT_K3S_VERSION}
  --k3sup-version <version>   k3sup version to enforce locally. Default: ${DEFAULT_K3SUP_VERSION}
  --namespace <name>          Namespace to create on the cluster. Default: ${DEFAULT_NAMESPACE}
  --tls-san <value>           Additional TLS SAN for the k3s API server. Default: control plane IP
  --k3s-extra-args <args>     Extra arguments appended to the k3s defaults
                              (control plane: --node-external-ip + --disable=traefik,
                              workers: --node-external-ip).
  --force                     If a node already runs k3s, skip it instead of
                              aborting. If the control plane already runs k3s,
                              reuse it and fetch its kubeconfig with
                              --skip-install. The installed k3s version is NOT
                              checked against --k3s-version on reused or
                              skipped nodes.
  --skip-preflight            Disable the remote preflight checks. Existing k3s
                              detection is skipped too, so --force cannot reuse
                              or skip nodes in this mode.
  --delete                    Uninstall k3s from the workers first, then the
                              control plane. Fails if a node has no k3s
                              installation, the expected uninstall script is
                              missing, or k3s remnants remain. The generated
                              kubeconfig is left in place.
  --yes                       Non-interactive mode. Also skips the --delete prompt.
  --help                      Show this help.

Examples:
  ${SCRIPT_NAME} --nodes 203.0.113.10,203.0.113.11,203.0.113.12 \\
    --context nexus-demogg --ssh-key ~/.ssh/nexus.pem

  ${SCRIPT_NAME} --nodes 203.0.113.10,203.0.113.11 \\
    --context nexus-demogg --ssh-key ~/.ssh/nexus.pem --user cubbit

  ${SCRIPT_NAME} --nodes 203.0.113.10,203.0.113.11 \\
    --ssh-key ~/.ssh/nexus.pem --delete

Notes:
  - The SSH user must be root or have passwordless sudo.
  - No disk creation, formatting, or mounting is performed.
  - --k3s-extra-args is applied to both the control plane and the workers; avoid
    control plane-only flags that workers do not accept.
  - --force reuses or skips existing k3s nodes without verifying their version
    against --k3s-version. Remaining workers are still joined with the pinned
    version.
  - --skip-preflight bypasses all remote inspection, including existing k3s
    detection. Use it only when the nodes are known to be ready.
  - Supported OS: Ubuntu only. The preflight prints a warning on other
    distributions.
  - Docker is left untouched. Stop docker-compose.service before starting the
    new agent workload so the legacy and Kubernetes agents do not run
    concurrently with the same agent identity, state directory, and data disk.
EOF
}

print_status() {
  printf '%b[INFO]%b %s\n' "${BLUE}" "${NC}" "$1"
}

print_success() {
  printf '%b[SUCCESS]%b %s\n' "${GREEN}" "${NC}" "$1"
}

print_warning() {
  printf '%b[WARNING]%b %s\n' "${YELLOW}" "${NC}" "$1" >&2
}

print_error() {
  printf '%b[ERROR]%b %s\n' "${RED}" "${NC}" "$1" >&2
}

fail() {
  print_error "$*"
  exit 1
}

trim() {
  local value="$1"
  value="${value#"${value%%[![:space:]]*}"}"
  value="${value%"${value##*[![:space:]]}"}"
  printf '%s' "$value"
}

require_option_value() {
  local option_name="$1"
  local value="${2-}"

  if [[ $# -lt 2 || -z "$value" ]]; then
    fail "missing value for ${option_name}"
  fi

  case "$value" in
    --nodes|--context|--ssh-key|--user|--ssh-port|--k3s-version|--k3sup-version|--namespace|--tls-san|--k3s-extra-args|--force|--skip-preflight|--delete|--yes|--help)
      fail "missing value for ${option_name} (next argument '${value}' is another option)"
      ;;
  esac
}

node_host() {
  printf '%s' "${1%%|*}"
}

node_port() {
  printf '%s' "${1##*|}"
}

preflight_value() {
  local output="$1"
  local key="$2"
  printf '%s\n' "$output" | awk -F= -v wanted="$key" '$1 == wanted { print $2; exit }'
}

check_local_prerequisites() {
  local missing=()
  local cmd=""

  for cmd in ssh curl awk grep sed tr uname mkdir mktemp chmod date; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      missing+=("$cmd")
    fi
  done

  if [[ ${#missing[@]} -gt 0 ]]; then
    fail "Local machine is missing required commands: ${missing[*]}"
  fi
}

build_node_list() {
  local raw_nodes=()
  local entry=""
  local host=""
  local port=""
  local seen=""
  local o1=""
  local o2=""
  local o3=""
  local o4=""
  local octet=""

  NODES=()

  IFS=',' read -r -a raw_nodes <<<"$NODES_RAW"
  for entry in "${raw_nodes[@]}"; do
    entry="$(trim "$entry")"
    [[ -n "$entry" ]] || fail "--nodes contains an empty entry"
    [[ "$entry" != *:*:* ]] || fail "IPv6 addresses are not supported by this script: ${entry}"

    if [[ "$entry" == *:* ]]; then
      host="$(trim "${entry%%:*}")"
      port="$(trim "${entry##*:}")"
    else
      host="$entry"
      port="$SSH_PORT"
    fi

    [[ "$host" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || fail "invalid node '${host}': an IPv4 address is required"
    o1=""; o2=""; o3=""; o4=""
    IFS='.' read -r o1 o2 o3 o4 <<< "$host"
    for octet in "$o1" "$o2" "$o3" "$o4"; do
      [[ "$octet" =~ ^[0-9]+$ && "$octet" -le 255 ]] || fail "invalid IPv4 address: ${host}"
    done
    [[ "$port" =~ ^[0-9]+$ ]] || fail "invalid SSH port '${port}' for node '${host}'"
    [[ "$port" -ge 1 && "$port" -le 65535 ]] || fail "SSH port out of range for node '${host}': ${port}"

    if printf '%s\n' "$seen" | grep -qx "$host"; then
      fail "duplicate node in --nodes: ${host}"
    fi
    seen="${seen}${host}"$'\n'

    NODES+=("${host}|${port}")
  done

  [[ ${#NODES[@]} -gt 0 ]] || fail "--nodes must contain at least one node"

  CONTROL_PLANE_NODE="${NODES[0]}"
  WORKER_NODES=("${NODES[@]:1}")
}

finalize_inputs() {
  [[ -n "$NODES_RAW" ]] || fail "--nodes is required"
  [[ -n "$SSH_KEY" ]] || fail "--ssh-key is required"
  [[ -f "$SSH_KEY" ]] || fail "SSH key not found: ${SSH_KEY}"
  [[ "$SSH_PORT" =~ ^[0-9]+$ ]] || fail "--ssh-port must be numeric"
  [[ "$SSH_PORT" -ge 1 && "$SSH_PORT" -le 65535 ]] || fail "--ssh-port out of range: ${SSH_PORT}"
  [[ "$SSH_USER" =~ ^[A-Za-z0-9._-]+$ ]] || fail "--user may only contain letters, digits, '.', '_' and '-'"
  [[ "$NAMESPACE" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]] || fail "--namespace must be a valid Kubernetes namespace"
  [[ "$K3S_EXTRA_ARGS" != *$'\n'* ]] || fail "--k3s-extra-args must not contain newlines"

  if [[ "$DELETE_MODE" != "yes" ]]; then
    [[ -n "$CONTEXT" ]] || fail "--context is required"
  fi

  if [[ -n "$CONTEXT" ]]; then
    [[ "$CONTEXT" =~ ^[A-Za-z0-9._-]+$ ]] || fail "--context may only contain letters, digits, '.', '_' and '-'"
  fi

  if [[ -n "$TLS_SAN" ]]; then
    [[ "$TLS_SAN" =~ ^[A-Za-z0-9._-]+$ ]] || fail "--tls-san may only contain letters, digits, '.', '_' and '-'"
  fi

  build_node_list

  if [[ "$DELETE_MODE" != "yes" ]]; then
    KUBECONFIG_PATH="${KUBECONFIG_DIR}/kubeconfig-${CONTEXT}.yaml"
  fi
}

prompt_yes_no() {
  local prompt="$1"
  local default_value="$2"
  local value=""
  local lower_value=""

  while true; do
    printf '%s [%s]: ' "${prompt}" "${default_value}" >&2
    read -r value
    value="${value:-$default_value}"
    lower_value="$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')"
    case "$lower_value" in
      yes|y|true|t|1)
        printf 'yes'
        return
        ;;
      no|n|false|f|0)
        printf 'no'
        return
        ;;
    esac
    print_warning "Please answer with yes/no (or y/n)."
  done
}

ssh_run() {
  local node="$1"
  shift

  local host=""
  local port=""
  host="$(node_host "$node")"
  port="$(node_port "$node")"

  ssh -p "$port" -i "$SSH_KEY" \
    -o BatchMode=yes \
    -o ConnectTimeout=10 \
    -o StrictHostKeyChecking=accept-new \
    "${SSH_USER}@${host}" "$@"
}

node_sudo_status() {
  local node="$1"
  ssh_run "$node" "bash -s" <<'REMOTE_SUDO'
set -u
if [ "$(id -u)" -eq 0 ]; then
  echo "root"
elif sudo -n true >/dev/null 2>&1; then
  echo "ok"
else
  echo "missing"
fi
REMOTE_SUDO
}

ensure_local_k3sup() {
  local tools_dir="/tmp/cubbit-tools/bin"
  local os=""
  local arch=""
  local k3sup_file="k3sup"
  local current_version=""
  local download_url=""

  mkdir -p "$tools_dir"

  os="$(uname | tr '[:upper:]' '[:lower:]')"
  arch="$(uname -m)"
  case "$arch" in
    x86_64) arch="amd64" ;;
    aarch64|arm64) arch="arm64" ;;
    *) fail "unsupported architecture for k3sup: $arch" ;;
  esac

  if [[ "$os" != "linux" ]]; then
    k3sup_file="${k3sup_file}-${os}"
  fi
  if [[ "$arch" != "amd64" ]]; then
    k3sup_file="${k3sup_file}-${arch}"
  fi

  K3SUP_BIN="${tools_dir}/k3sup"

  if [[ -x "$K3SUP_BIN" ]]; then
    current_version="$("$K3SUP_BIN" version 2>/dev/null | awk '/Version/ {print $2}' || true)"
  fi

  if [[ "$current_version" != "$K3SUP_VERSION" ]]; then
    download_url="https://github.com/alexellis/k3sup/releases/download/${K3SUP_VERSION}/${k3sup_file}"
    print_status "Installing k3sup ${K3SUP_VERSION} from ${download_url}"
    curl -sS -L --fail -o "$K3SUP_BIN" "$download_url"
    chmod +x "$K3SUP_BIN"
  fi

  current_version="$("$K3SUP_BIN" version 2>/dev/null | awk '/Version/ {print $2}' || true)"
  if [[ "$current_version" != "$K3SUP_VERSION" ]]; then
    fail "requested k3sup ${K3SUP_VERSION}, found ${current_version:-unknown}"
  fi
}

run_preflight() {
  local node="$1"

  ssh_run "$node" "bash -s" <<'REMOTE_PREFLIGHT'
set -u

echo "hostname=$(hostname 2>/dev/null || echo unknown)"

if [ -r /etc/os-release ]; then
  # shellcheck disable=SC1091
  . /etc/os-release
  echo "os_id=${ID:-unknown}"
  echo "os_version=${VERSION_ID:-unknown}"
else
  echo "os_id=unknown"
  echo "os_version=unknown"
fi

if [ "$(id -u)" -eq 0 ]; then
  echo "sudo=root"
elif sudo -n true >/dev/null 2>&1; then
  echo "sudo=ok"
else
  echo "sudo=missing"
fi

if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
  echo "cgroup=v2"
else
  echo "cgroup=v1-or-unknown"
fi

if awk 'NR>1 && NF {found=1} END {exit !found}' /proc/swaps 2>/dev/null; then
  echo "swap=on"
else
  echo "swap=off"
fi

if [ -x /usr/local/bin/k3s ] || [ -f /etc/rancher/k3s/k3s.yaml ] || systemctl is-active --quiet k3s 2>/dev/null; then
  echo "k3s_control_plane=yes"
else
  echo "k3s_control_plane=no"
fi

if [ -x /usr/local/bin/k3s-agent-uninstall.sh ] || systemctl is-active --quiet k3s-agent 2>/dev/null; then
  echo "k3s_worker=yes"
else
  echo "k3s_worker=no"
fi

for cmd in bash curl tar systemctl awk grep timeout; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "missing_cmd=$cmd"
  fi
done

if [ "$(id -u)" -ne 0 ] && ! command -v sudo >/dev/null 2>&1; then
  echo "missing_cmd=sudo"
fi

if command -v findmnt >/dev/null 2>&1; then
  mounts="$(findmnt -rn -o TARGET 2>/dev/null | awk -v base="/mnt/cubbit" '$0 == base || index($0, base "/") == 1 { print }' || true)"
else
  mounts=""
fi
if [ -n "$mounts" ]; then
  echo "cubbit_mounts=yes"
  while IFS= read -r mount_point; do
    [ -n "$mount_point" ] && echo "cubbit_mount=$mount_point"
  done <<< "$mounts"
else
  echo "cubbit_mounts=no"
fi

if command -v df >/dev/null 2>&1; then
  echo "var_lib_free=$(df -Pk /var/lib 2>/dev/null | awk 'NR==2 {printf "%.1fGiB", $4/1024/1024}')"
fi

if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -qi '^Status: active'; then
  echo "firewall=ufw-active"
fi
if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state 2>/dev/null | grep -qx running; then
  echo "firewall=firewalld-active"
fi

if command -v ss >/dev/null 2>&1; then
  listeners="$(ss -lntu 2>/dev/null | awk 'NR>1 && $5 ~ /:(6443|8472|10250)$/ {print $1, $5}' || true)"
  if [ -n "$listeners" ]; then
    echo "port_listeners=yes"
    while IFS= read -r listener; do
      [ -n "$listener" ] && echo "listener=$listener"
    done <<< "$listeners"
  else
    echo "port_listeners=no"
  fi
fi
REMOTE_PREFLIGHT
}

preflight_all() {
  local index=0
  local node=""
  local host=""
  local output=""

  PREFLIGHT_OUTPUTS=()

  for index in "${!NODES[@]}"; do
    node="${NODES[$index]}"
    host="$(node_host "$node")"
    print_status "Running preflight on ${host}"

    if ! output="$(run_preflight "$node" 2>&1)"; then
      fail "preflight failed on ${host}: ${output}"
    fi

    printf '%s\n' "$output" | sed 's/^/  /'
    PREFLIGHT_OUTPUTS[$index]="$output"
  done
}

check_preflight_results() {
  local index=0
  local node=""
  local host=""
  local output=""
  local missing=""
  local value=""

  for index in "${!NODES[@]}"; do
    node="${NODES[$index]}"
    host="$(node_host "$node")"
    output="${PREFLIGHT_OUTPUTS[$index]}"

    missing=""
    while IFS='=' read -r key value; do
      if [[ "$key" == "missing_cmd" ]]; then
        missing="${missing}${missing:+, }${value}"
      fi
    done <<< "$output"
    if [[ -n "$missing" ]]; then
      fail "node ${host} is missing required commands: ${missing}"
    fi

    if printf '%s\n' "$output" | grep -qx 'sudo=missing'; then
      fail "node ${host} does not provide passwordless sudo for ${SSH_USER}"
    fi

    if printf '%s\n' "$output" | grep -qx 'swap=on'; then
      print_warning "node ${host} has active swap; k3s recommends disabling it. Run 'sudo swapoff -a' and remove swap entries from /etc/fstab."
    fi

    value="$(preflight_value "$output" os_id)"
    if [[ -n "$value" && "$value" != "ubuntu" ]]; then
      print_warning "node ${host} runs '${value}'; this runbook is supported on Ubuntu only."
    fi

    value="$(preflight_value "$output" cgroup)"
    if [[ "$value" == "v1-or-unknown" ]]; then
      print_warning "node ${host} does not expose cgroup v2 controllers; verify the k3s cgroup requirements."
    fi

    value="$(preflight_value "$output" firewall)"
    if [[ -n "$value" ]]; then
      print_warning "node ${host} reports ${value}; ensure 6443/tcp, 10250/tcp and 8472/udp are reachable between nodes."
    fi

    if printf '%s\n' "$output" | grep -qx 'cubbit_mounts=no'; then
      print_warning "node ${host} has no ${CUBBIT_MOUNT_BASE} mounts; confirm the Ansible data disks are mounted before migrating agents."
    fi

    if printf '%s\n' "$output" | grep -qx 'port_listeners=yes'; then
      print_warning "node ${host} already listens on one of 6443/tcp, 8472/udp or 10250/tcp; verify there is no conflicting cluster."
    fi
  done
}

evaluate_existing_k3s() {
  local control_plane_output="${PREFLIGHT_OUTPUTS[0]}"
  local control_plane_present=""
  local worker_present=""
  local index=0
  local node=""
  local host=""
  local output=""

  control_plane_present="$(preflight_value "$control_plane_output" k3s_control_plane)"
  worker_present="$(preflight_value "$control_plane_output" k3s_worker)"
  CONTROL_PLANE_REUSE="no"

  if [[ "$worker_present" == "yes" && "$control_plane_present" != "yes" ]]; then
    fail "control plane node $(node_host "$CONTROL_PLANE_NODE") has the k3s agent component installed; run --delete or clean it manually"
  fi

  if [[ "$control_plane_present" == "yes" ]]; then
    if [[ "$FORCE" == "yes" ]]; then
      print_warning "control plane node $(node_host "$CONTROL_PLANE_NODE") already runs k3s; reusing it because --force was provided"
      print_warning "the reused control plane version is not checked against --k3s-version=${K3S_VERSION}; workers will be joined with this pinned version"
      CONTROL_PLANE_REUSE="yes"
    else
      fail "control plane node $(node_host "$CONTROL_PLANE_NODE") already runs k3s; run --delete, clean it manually, or pass --force to reuse it"
    fi
  fi

  WORKERS_TO_JOIN=()
  for index in "${!WORKER_NODES[@]}"; do
    node="${WORKER_NODES[$index]}"
    host="$(node_host "$node")"
    output="${PREFLIGHT_OUTPUTS[$((index + 1))]}"

    control_plane_present="$(preflight_value "$output" k3s_control_plane)"
    worker_present="$(preflight_value "$output" k3s_worker)"

    if [[ "$control_plane_present" == "yes" || "$worker_present" == "yes" ]]; then
      if [[ "$FORCE" == "yes" ]]; then
        print_warning "worker node ${host} already runs k3s; skipping it because --force was provided; its version is not checked against --k3s-version=${K3S_VERSION}"
        continue
      fi
      fail "worker node ${host} already runs k3s; run --delete, clean it manually, or pass --force to skip it"
    fi

    WORKERS_TO_JOIN+=("$node")
  done
}

ensure_kubeconfig_path() {
  local backup_path=""

  mkdir -p "$KUBECONFIG_DIR"
  if [[ -e "$KUBECONFIG_PATH" ]]; then
    backup_path="${KUBECONFIG_PATH}.bak.$(date +%Y%m%d%H%M%S)"
    mv "$KUBECONFIG_PATH" "$backup_path"
    print_warning "existing kubeconfig moved to ${backup_path}"
  fi
}

k3sup_sudo_args() {
  if [[ "$SSH_USER" == "root" ]]; then
    printf '%s\n' "--sudo=false"
  else
    printf '%s\n' "--sudo=true"
  fi
}

install_control_plane() {
  local host=""
  local port=""
  local control_plane_extra_args=""
  local sudo_arg=""
  local -a k3sup_args=()

  host="$(node_host "$CONTROL_PLANE_NODE")"
  port="$(node_port "$CONTROL_PLANE_NODE")"
  control_plane_extra_args="--node-external-ip=${host} --disable=traefik"
  if [[ -n "$K3S_EXTRA_ARGS" ]]; then
    control_plane_extra_args="${control_plane_extra_args} ${K3S_EXTRA_ARGS}"
  fi
  sudo_arg="$(k3sup_sudo_args)"

  k3sup_args=(
    install
    --ip "$host"
    --user "$SSH_USER"
    --ssh-port "$port"
    --ssh-key "$SSH_KEY"
    --k3s-version "$K3S_VERSION"
    --k3s-extra-args "$control_plane_extra_args"
    --context "$CONTEXT"
    --local-path "$KUBECONFIG_PATH"
    "$sudo_arg"
  )

  if [[ -n "$TLS_SAN" ]]; then
    k3sup_args+=(--tls-san "$TLS_SAN")
  fi

  if [[ "$CONTROL_PLANE_REUSE" == "yes" ]]; then
    k3sup_args+=(--skip-install)
    print_status "Fetching kubeconfig from the existing k3s control plane ${host}"
  else
    print_status "Installing the k3s control plane on ${host}"
  fi

  "$K3SUP_BIN" "${k3sup_args[@]}"
}

wait_for_control_plane_ready() {
  print_status "Waiting for the k3s API on $(node_host "$CONTROL_PLANE_NODE")"

  ssh_run "$CONTROL_PLANE_NODE" "bash -s" <<'REMOTE_WAIT'
set -u
if [ "$(id -u)" -eq 0 ]; then
  SUDO=""
else
  SUDO="sudo"
fi

i=0
while [ "$i" -lt 60 ]; do
  if $SUDO k3s kubectl get nodes >/dev/null 2>&1; then
    exit 0
  fi
  sleep 2
  i=$((i + 1))
done

echo "the k3s API did not become ready on this control plane node" >&2
exit 1
REMOTE_WAIT
}

check_worker_reachability() {
  local node=""
  local host=""
  local control_plane_host=""

  control_plane_host="$(node_host "$CONTROL_PLANE_NODE")"

  for node in "${WORKERS_TO_JOIN[@]}"; do
    host="$(node_host "$node")"
    print_status "Checking ${host} -> ${control_plane_host}:6443/tcp"
    if ! ssh_run "$node" "timeout 5 bash -c '</dev/tcp/${control_plane_host}/6443' >/dev/null 2>&1"; then
      fail "worker ${host} cannot reach control plane ${control_plane_host}:6443/tcp; open the k3s API port between the nodes"
    fi
  done
}

join_workers() {
  local node=""
  local host=""
  local port=""
  local control_plane_host=""
  local control_plane_port=""
  local worker_extra_args=""
  local sudo_arg=""
  local -a k3sup_args=()

  control_plane_host="$(node_host "$CONTROL_PLANE_NODE")"
  control_plane_port="$(node_port "$CONTROL_PLANE_NODE")"
  sudo_arg="$(k3sup_sudo_args)"

  for node in "${WORKERS_TO_JOIN[@]}"; do
    host="$(node_host "$node")"
    port="$(node_port "$node")"
    worker_extra_args="--node-external-ip=${host}"
    if [[ -n "$K3S_EXTRA_ARGS" ]]; then
      worker_extra_args="${worker_extra_args} ${K3S_EXTRA_ARGS}"
    fi

    print_status "Joining worker ${host} to control plane ${control_plane_host}"
    k3sup_args=(
      join
      --ip "$host"
      --user "$SSH_USER"
      --ssh-port "$port"
      --ssh-key "$SSH_KEY"
      --server-ip "$control_plane_host"
      --server-user "$SSH_USER"
      --server-ssh-port "$control_plane_port"
      --k3s-version "$K3S_VERSION"
      --k3s-extra-args "$worker_extra_args"
      "$sudo_arg"
    )
    "$K3SUP_BIN" "${k3sup_args[@]}"
  done
}

verify_cluster() {
  local expected=$((1 + ${#WORKERS_TO_JOIN[@]}))

  print_status "Waiting for ${expected} Ready node(s)"
  ssh_run "$CONTROL_PLANE_NODE" "export CUBBIT_EXPECTED='${expected}'; bash -s" <<'REMOTE_VERIFY'
set -u
if [ "$(id -u)" -eq 0 ]; then
  SUDO=""
else
  SUDO="sudo"
fi

i=0
while [ "$i" -lt 60 ]; do
  nodes="$($SUDO k3s kubectl get nodes --no-headers 2>/dev/null || true)"
  ready="$(printf '%s\n' "$nodes" | awk '$2 ~ /^Ready/ {count++} END {print count+0}')"
  if [ "$ready" -ge "$CUBBIT_EXPECTED" ]; then
    printf '%s\n' "$nodes"
    exit 0
  fi
  sleep 5
  i=$((i + 1))
done

printf '%s\n' "$nodes"
echo "timed out waiting for $CUBBIT_EXPECTED Ready node(s)" >&2
exit 1
REMOTE_VERIFY
}

create_namespace() {
  print_status "Ensuring namespace '${NAMESPACE}' exists"
  ssh_run "$CONTROL_PLANE_NODE" "export CUBBIT_NAMESPACE='${NAMESPACE}'; bash -s" <<'REMOTE_NAMESPACE'
set -eu
if [ "$(id -u)" -eq 0 ]; then
  SUDO=""
else
  SUDO="sudo"
fi

if $SUDO k3s kubectl get namespace "$CUBBIT_NAMESPACE" >/dev/null 2>&1; then
  echo "namespace $CUBBIT_NAMESPACE already exists"
else
  $SUDO k3s kubectl create namespace "$CUBBIT_NAMESPACE"
fi
REMOTE_NAMESPACE
}

print_summary() {
  print_success "k3s cluster '${CONTEXT}' is ready"
  print_status "Kubeconfig: ${KUBECONFIG_PATH}"
  print_status "Control plane SSH endpoint: $(node_host "$CONTROL_PLANE_NODE"):$(node_port "$CONTROL_PLANE_NODE")"
  if [[ ${#WORKERS_TO_JOIN[@]} -gt 0 ]]; then
    print_status "Workers joined: ${#WORKERS_TO_JOIN[@]}"
  else
    print_status "Workers joined: 0"
  fi
  print_status "Next step: install kubectl and kubectl-cubbit, then run 'kubectl cubbit cluster-connect' (see tools/efesto/docs/agent/Swarm-migration-k3s-cluster.md)"
}

check_delete_prerequisites() {
  local node=""
  local host=""
  local status=""

  for node in "${NODES[@]}"; do
    host="$(node_host "$node")"
    if ! ssh_run "$node" "true" >/dev/null 2>&1; then
      fail "cannot SSH to ${host} as ${SSH_USER}"
    fi
    status="$(node_sudo_status "$node" | tr -d '\r')"
    if [[ "$status" == "missing" ]]; then
      fail "node ${host} does not provide passwordless sudo for ${SSH_USER}"
    fi
  done
}

delete_worker() {
  local node="$1"
  local host=""

  host="$(node_host "$node")"
  print_status "Uninstalling k3s worker from ${host}"
  ssh_run "$node" "bash -s" <<'REMOTE_DELETE_WORKER'
set -u
if [ "$(id -u)" -eq 0 ]; then
  SUDO=""
else
  SUDO="sudo"
fi

if [ ! -x /usr/local/bin/k3s-agent-uninstall.sh ]; then
  if [ -x /usr/local/bin/k3s-uninstall.sh ]; then
    echo "error: node has a k3s control plane installation, refusing to uninstall it as a worker" >&2
  else
    echo "error: no k3s worker installation found" >&2
  fi
  exit 1
fi

if ! $SUDO /usr/local/bin/k3s-agent-uninstall.sh; then
  echo "error: k3s-agent uninstall script failed" >&2
  exit 1
fi

failed=0
if $SUDO test -e /usr/local/bin/k3s; then
  echo "error: /usr/local/bin/k3s is still present after uninstall" >&2
  failed=1
fi
if $SUDO test -e /etc/rancher/k3s; then
  echo "error: /etc/rancher/k3s is still present after uninstall" >&2
  failed=1
fi
if $SUDO test -e /var/lib/rancher/k3s; then
  echo "error: /var/lib/rancher/k3s is still present after uninstall" >&2
  failed=1
fi
if systemctl is-active --quiet k3s; then
  echo "error: k3s service is still active after uninstall" >&2
  failed=1
fi
if systemctl is-active --quiet k3s-agent; then
  echo "error: k3s-agent service is still active after uninstall" >&2
  failed=1
fi
if [ "$failed" -ne 0 ]; then
  exit 1
fi
echo "worker uninstall verified"
REMOTE_DELETE_WORKER
}

delete_control_plane() {
  local node="$1"
  local host=""

  host="$(node_host "$node")"
  print_status "Uninstalling k3s control plane from ${host}"
  ssh_run "$node" "bash -s" <<'REMOTE_DELETE_CONTROL_PLANE'
set -u
if [ "$(id -u)" -eq 0 ]; then
  SUDO=""
else
  SUDO="sudo"
fi

if [ ! -x /usr/local/bin/k3s-uninstall.sh ]; then
  echo "error: no k3s control plane installation found" >&2
  exit 1
fi

if ! $SUDO /usr/local/bin/k3s-uninstall.sh; then
  echo "error: k3s uninstall script failed" >&2
  exit 1
fi

failed=0
if $SUDO test -e /usr/local/bin/k3s; then
  echo "error: /usr/local/bin/k3s is still present after uninstall" >&2
  failed=1
fi
if $SUDO test -e /etc/rancher/k3s; then
  echo "error: /etc/rancher/k3s is still present after uninstall" >&2
  failed=1
fi
if $SUDO test -e /var/lib/rancher/k3s; then
  echo "error: /var/lib/rancher/k3s is still present after uninstall" >&2
  failed=1
fi
if systemctl is-active --quiet k3s; then
  echo "error: k3s service is still active after uninstall" >&2
  failed=1
fi
if systemctl is-active --quiet k3s-agent; then
  echo "error: k3s-agent service is still active after uninstall" >&2
  failed=1
fi
if [ "$failed" -ne 0 ]; then
  exit 1
fi
echo "control plane uninstall verified"
REMOTE_DELETE_CONTROL_PLANE
}

delete_cluster() {
  local node=""
  local host=""
  local answer=""

  print_warning "This will uninstall k3s from all nodes: ${NODES_RAW}"
  if [[ "$AUTO_YES" != "yes" ]]; then
    printf 'Type "yes" to continue: ' >&2
    read -r answer
    [[ "$answer" == "yes" ]] || fail "delete aborted"
  fi

  for node in "${WORKER_NODES[@]}"; do
    host="$(node_host "$node")"
    if ! delete_worker "$node"; then
      print_error "k3s uninstall failed on worker ${host}"
      exit 1
    fi
  done

  if ! delete_control_plane "$CONTROL_PLANE_NODE"; then
    print_error "k3s uninstall failed on control plane $(node_host "$CONTROL_PLANE_NODE")"
    exit 1
  fi

  print_success "k3s uninstall completed and verified on all nodes"
  print_status "Any generated kubeconfig was left in place: ${KUBECONFIG_PATH:-<not set for delete mode>}"
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --nodes)
        require_option_value "$1" "${2-}"
        NODES_RAW="${2-}"
        shift 2
        ;;
      --context)
        require_option_value "$1" "${2-}"
        CONTEXT="${2-}"
        shift 2
        ;;
      --ssh-key)
        require_option_value "$1" "${2-}"
        SSH_KEY="${2-}"
        shift 2
        ;;
      --user)
        require_option_value "$1" "${2-}"
        SSH_USER="${2-}"
        shift 2
        ;;
      --ssh-port)
        require_option_value "$1" "${2-}"
        SSH_PORT="${2-}"
        shift 2
        ;;
      --k3s-version)
        require_option_value "$1" "${2-}"
        K3S_VERSION="${2-}"
        shift 2
        ;;
      --k3sup-version)
        require_option_value "$1" "${2-}"
        K3SUP_VERSION="${2-}"
        shift 2
        ;;
      --namespace)
        require_option_value "$1" "${2-}"
        NAMESPACE="${2-}"
        shift 2
        ;;
      --tls-san)
        require_option_value "$1" "${2-}"
        TLS_SAN="${2-}"
        shift 2
        ;;
      --k3s-extra-args)
        require_option_value "$1" "${2-}"
        K3S_EXTRA_ARGS="${2-}"
        shift 2
        ;;
      --force)
        FORCE="yes"
        shift
        ;;
      --skip-preflight)
        SKIP_PREFLIGHT="yes"
        shift
        ;;
      --delete)
        DELETE_MODE="yes"
        shift
        ;;
      --yes)
        AUTO_YES="yes"
        shift
        ;;
      --help)
        usage
        exit 0
        ;;
      *)
        fail "unknown argument: $1"
        ;;
    esac
  done
}

main() {
  parse_args "$@"
  check_local_prerequisites
  finalize_inputs

  if [[ "$DELETE_MODE" == "yes" ]]; then
    if [[ "$SKIP_PREFLIGHT" != "yes" ]]; then
      check_delete_prerequisites
    else
      print_warning "preflight checks disabled; attempting uninstall without reachability checks"
    fi
    delete_cluster
    return
  fi

  ensure_local_k3sup

  if [[ "$SKIP_PREFLIGHT" == "yes" ]]; then
    print_warning "preflight checks disabled; existing k3s detection is skipped"
    if [[ "$FORCE" == "yes" ]]; then
      print_warning "--force has no effect when --skip-preflight is used; existing k3s nodes and their versions are not checked"
    fi
    CONTROL_PLANE_REUSE="no"
    WORKERS_TO_JOIN=("${WORKER_NODES[@]}")
  else
    preflight_all
    check_preflight_results
    evaluate_existing_k3s
  fi

  ensure_kubeconfig_path
  install_control_plane
  wait_for_control_plane_ready
  check_worker_reachability
  join_workers
  verify_cluster
  create_namespace
  print_summary
}

main "$@"
