#!/usr/bin/env bash
set -u

# NiceOS Kubernetes dynamic login banner.
# Fast checks only. No kubectl calls here, because login banner must never hang.

KUBEADM_CONFIG="/etc/kubernetes/niceos-kubeadm-init.yaml"
ADMIN_CONF="/etc/kubernetes/admin.conf"
KUBELET_CONF="/etc/kubernetes/kubelet.conf"
KUBELET_CONFIG="/var/lib/kubelet/config.yaml"
APISERVER_MANIFEST="/etc/kubernetes/manifests/kube-apiserver.yaml"

DEFAULT_PROFILE="flannel"
DEFAULT_KUBECONFIG="/etc/kubernetes/admin.conf"

is_tty() {
    [ -t 1 ] || return 1
    case "${TERM:-}" in
        ""|dumb) return 1 ;;
    esac
    return 0
}

have_cmd() {
    command -v "$1" >/dev/null 2>&1
}

unit_active() {
    local unit="$1"
    if have_cmd systemctl; then
        systemctl is-active "$unit" 2>/dev/null || true
    else
        echo "unknown"
    fi
}

unit_enabled() {
    local unit="$1"
    if have_cmd systemctl; then
        systemctl is-enabled "$unit" 2>/dev/null || true
    else
        echo "unknown"
    fi
}

cluster_initialized() {
    # Control-plane initialized by kubeadm.
    [ -f "$ADMIN_CONF" ] && [ -f "$APISERVER_MANIFEST" ] && return 0

    # Joined node initialized by kubeadm.
    [ -f "$KUBELET_CONF" ] && [ -f "$KUBELET_CONFIG" ] && return 0

    return 1
}

control_plane_initialized() {
    [ -f "$ADMIN_CONF" ] && [ -f "$APISERVER_MANIFEST" ]
}

node_joined() {
    [ -f "$KUBELET_CONF" ] && [ -f "$KUBELET_CONFIG" ]
}

detect_profile() {
    if [ -f "$KUBEADM_CONFIG" ]; then
        # Simple and safe detection. Do not require yq/python.
        if grep -q '10\.244\.0\.0/16' "$KUBEADM_CONFIG" 2>/dev/null; then
            echo "flannel"
            return 0
        fi
    fi

    echo "$DEFAULT_PROFILE"
}

detect_k8s_version() {
    if have_cmd kubeadm; then
        kubeadm version -o short 2>/dev/null || true
    fi
}

color() {
    local code="$1"
    shift
    if [ -t 1 ] && [ "${NO_COLOR:-}" = "" ]; then
        printf '\033[%sm%s\033[0m' "$code" "$*"
    else
        printf '%s' "$*"
    fi
}

line() {
    printf '%s\n' '================================================================================'
}

show_uninitialized_banner() {
    local profile
    local containerd_state
    local kubelet_state
    local firewall_state
    local kubeadm_version

    profile="$(detect_profile)"
    containerd_state="$(unit_active containerd.service)"
    kubelet_state="$(unit_active kubelet.service)"
    firewall_state="$(unit_active niceos-kubernetes-firewall.service)"
    kubeadm_version="$(detect_k8s_version)"

    line
    printf ' %s\n' "$(color '1;36' 'NiceOS Kubernetes Node')"
    line
    echo
    printf '%s\n' "$(color '1;33' 'This node is Kubernetes-ready, but the cluster is not initialized yet.')"
    echo
    echo "Current state:"
    printf '  %-13s %s\n' "containerd:" "$containerd_state"
    printf '  %-13s %s\n' "kubelet:" "$kubelet_state"
    printf '  %-13s %s\n' "firewall:" "$firewall_state"
    printf '  %-13s %s\n' "profile:" "$profile"

    if [ -n "$kubeadm_version" ]; then
        printf '  %-13s %s\n' "kubeadm:" "$kubeadm_version"
    fi

    echo
    printf '%s\n' "$(color '1;32' 'Initialize first control-plane node:')"
    echo
    echo "  niceos-kubeadm-config images-pull --profile ${profile}"
    echo "  niceos-kubeadm-config init --profile ${profile}"
    echo
    printf '%s\n' "$(color '1;32' 'After initialization:')"
    echo
    echo "  export KUBECONFIG=${DEFAULT_KUBECONFIG}"
    echo "  niceos-flannel-addon apply"
    echo "  niceos-flannel-addon wait"
    echo "  niceos-k8s-doctor --deep"
    echo
    printf '%s\n' "$(color '1;32' 'For worker nodes:')"
    echo
    echo "  Generate join command on the control-plane node:"
    echo "    niceos-k8s join-command --role worker"
    echo
    echo "  Then run the printed kubeadm join command on this node."
    echo
    line
}

show_initialized_hint() {
    # Keep initialized banner intentionally short.
    # Admins should not get a wall of text on every login.
    if control_plane_initialized; then
        printf '%s\n' "$(color '1;36' 'NiceOS Kubernetes: control-plane initialized.') Run: niceos-k8s-doctor --deep"
    elif node_joined; then
        printf '%s\n' "$(color '1;36' 'NiceOS Kubernetes: node joined to a cluster.') Run: niceos-core-node-status"
    fi
}

main() {
    is_tty || exit 0

    # Allow admins to silence the dynamic banner globally.
    [ -f /etc/niceos/kubernetes/disable-motd ] && exit 0

    # Avoid repeated output in nested interactive shells.
    if [ "${NICEOS_K8S_MOTD_SHOWN:-0}" = "1" ]; then
        exit 0
    fi
    export NICEOS_K8S_MOTD_SHOWN=1

    if cluster_initialized; then
        # By default show only a compact hint.
        # To fully silence initialized-state hint, create:
        #   /etc/niceos/kubernetes/disable-initialized-motd
        [ -f /etc/niceos/kubernetes/disable-initialized-motd ] && exit 0
        show_initialized_hint
    else
        show_uninitialized_banner
    fi
}

main "$@"