#!/usr/bin/env bash
###############################################################################
# install-k3s.sh — Install k3s single-node on the tsys-awx VM.
#
# Intended to run ON the target VM (tsys-awx.knel.net) as root or via sudo.
# Installs k3s without Traefik (we use NodePort/LoadBalancer directly).
#
# Usage:  sudo bash install-k3s.sh
###############################################################################
set -euo pipefail

NODE_NAME="${NODE_NAME:-tsys-awx}"

echo "=========================================================="
echo " k3s single-node install — ${NODE_NAME}"
echo "=========================================================="

if command -v k3s >/dev/null 2>&1 && k3s kubectl get nodes >/dev/null 2>&1; then
    echo "k3s already installed and running. Skipping."
    k3s kubectl get nodes
    exit 0
fi

echo ""
echo "=== Installing k3s (this takes 1-2 minutes) ==="
curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--disable=traefik --write-kubeconfig-mode=644" sh -

echo ""
echo "=== Waiting for k3s node to be Ready ==="
export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
for i in $(seq 1 30); do
    if k3s kubectl get nodes 2>/dev/null | grep -q ' Ready'; then
        echo "Node is Ready!"
        k3s kubectl get nodes
        break
    fi
    echo "  waiting... (${i}/30)"
    sleep 5
done

echo ""
echo "=== k3s install complete ==="
echo "kubeconfig: /etc/rancher/k3s/k3s.yaml"
echo "kubectl:    k3s kubectl  (or set KUBECONFIG=/etc/rancher/k3s/k3s.yaml)"
