#!/bin/sh
# SPDX-FileCopyrightText: Copyright (C) 2025 Bruce Ashfield
# SPDX-License-Identifier: MIT
#
# k3s-role-setup.sh — Configure k3s role from kernel cmdline
#
# Reads k3s.role= from /proc/cmdline and configures the system
# to run as either a k3s server or agent.
#
# Kernel cmdline parameters:
#   k3s.role=server  — run k3s server (default if not specified)
#   k3s.role=agent   — disable k3s server, enable k3s agent
#   k3s.server=IP    — server address for agent mode
#   k3s.token=TOKEN  — join token for agent mode
#   k3s.node-name=N  — override node name (useful when multiple VMs
#                       boot from the same image)
#   k3s.node-ip=IP   — set node IP address
#   k3s.iface=IFACE  — flannel interface (default: eth1)

CMDLINE=$(cat /proc/cmdline)

get_param() {
    echo "$CMDLINE" | tr ' ' '\n' | grep "^$1=" | cut -d= -f2-
}

ROLE=$(get_param k3s.role)
SERVER=$(get_param k3s.server)
TOKEN=$(get_param k3s.token)
NODE_NAME=$(get_param k3s.node-name)
NODE_IP=$(get_param k3s.node-ip)
IFACE=$(get_param k3s.iface)

# Default role is server
ROLE="${ROLE:-server}"
IFACE="${IFACE:-eth1}"

# Configure cluster network interface IP via networkd drop-in.
# The base 10-k3s-cluster.network (installed by virt_networking bbclass)
# claims eth1 and disables DHCP. This drop-in adds the static address.
if [ -n "$NODE_IP" ] && [ -n "$IFACE" ]; then
    echo "Configuring $IFACE with $NODE_IP/24 via networkd drop-in"
    DROPIN_DIR="/etc/systemd/network/10-k3s-cluster.network.d"
    mkdir -p "$DROPIN_DIR"
    cat > "$DROPIN_DIR/address.conf" << EOF
[Network]
Address=${NODE_IP}/24
EOF
    networkctl reload 2>/dev/null || true
fi

case "$ROLE" in
    server)
        # Server is the default — k3s.service is already enabled.
        # Mask the agent service to prevent it from starting.
        systemctl mask k3s-agent.service 2>/dev/null || true
        echo "k3s role: server"
        ;;

    agent)
        # Mask the server service to prevent it from starting
        systemctl mask k3s.service 2>/dev/null || true

        # Wipe any server state from previous boot
        rm -rf /var/lib/rancher/k3s/server/tls \
               /var/lib/rancher/k3s/server/cred \
               /var/lib/rancher/k3s/server/token \
               /var/lib/rancher/k3s/server/agent-token \
               /var/lib/rancher/k3s/server/node-token \
               /var/lib/rancher/k3s/server/db \
               /etc/rancher/k3s/k3s.yaml

        # Remove server-only config (disable-cloud-controller is
        # server-only and crashes the agent)
        rm -f /etc/rancher/k3s/config.yaml

        # Build agent environment file with cmdline parameters
        mkdir -p /etc/default
        {
            echo "# Generated by k3s-role-setup from kernel cmdline"
            [ -n "$SERVER" ] && echo "K3S_URL=https://${SERVER}:6443"
            [ -n "$TOKEN" ] && echo "K3S_TOKEN=${TOKEN}"
        } > /etc/default/k3s-agent

        # Build extra args
        AGENT_ARGS=""
        [ -n "$NODE_NAME" ] && AGENT_ARGS="$AGENT_ARGS --node-name $NODE_NAME"
        [ -n "$NODE_IP" ] && AGENT_ARGS="$AGENT_ARGS --node-ip $NODE_IP"
        [ -n "$IFACE" ] && AGENT_ARGS="$AGENT_ARGS --flannel-iface $IFACE"

        if [ -n "$AGENT_ARGS" ]; then
            # Create systemd override for extra args
            mkdir -p /run/systemd/system/k3s-agent.service.d
            cat > /run/systemd/system/k3s-agent.service.d/cmdline.conf << EOF
[Service]
ExecStart=
ExecStart=/usr/local/bin/k3s agent $AGENT_ARGS
EOF
        fi

        # Reload systemd to pick up overrides, then unmask and start
        # the agent. --no-block queues the start without waiting,
        # avoiding deadlock with the After= ordering.
        systemctl daemon-reload
        systemctl unmask k3s-agent.service 2>/dev/null || true
        systemctl start k3s-agent.service --no-block

        echo "k3s role: agent (server: ${SERVER:-not set})"
        ;;

    *)
        echo "Unknown k3s.role=$ROLE, defaulting to server"
        ;;
esac
