#!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-cluster-node-patch-generate <node-name>"
    echo ""
    echo "Generate Talos machine configuration patches for a specific registered node."
    echo ""
    echo "Arguments:"
    echo "  node-name           Name of the registered node"
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo ""
    echo "Examples:"
    echo "  wild-cluster-node-patch-generate control-1"
    echo "  wild-cluster-node-patch-generate worker-1"
    echo ""
    echo "This script will:"
    echo "  - Compile patch templates for the specified node"
    echo "  - Generate node-specific patch files in WC_HOME/setup/cluster-nodes/patch/"
    echo "  - Use hardware details from the node registration"
    echo ""
    echo "Requirements:"
    echo "  - Must be run from a wild-cloud directory"
    echo "  - Node must be registered (hardware detected) first"
    echo "  - Basic cluster configuration must be completed"
    echo "  - Patch templates must exist in WC_ROOT/setup/cluster-nodes/"
}

# Parse arguments
NODE_NAME=""
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "$NODE_NAME" ]; then
                NODE_NAME="$1"
            else
                echo "Unexpected argument: $1"
                usage
                exit 1
            fi
            shift
            ;;
    esac
done

# Check if node name was provided
if [ -z "$NODE_NAME" ]; then
    echo "Error: Node name is required"
    usage
    exit 1
fi

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    print "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

prompt_if_unset_config "cluster.name" "Cluster name" "local.example.com"

# Function to ensure required directories exist in WC_HOME
ensure_required_directories() {
    # Create output directories in WC_HOME for patch configs
    mkdir -p "${WC_HOME}/setup/cluster-nodes/patch"
}

# =============================================================================
# PATCH GENERATION
# =============================================================================

print_header "Talos Machine Config Patch Generation"

# Ensure required directories exist in WC_HOME
ensure_required_directories

# Define directories
TEMPLATE_SOURCE_DIR="${WC_ROOT}/setup/cluster-nodes"
NODE_SETUP_DIR="${WC_HOME}/setup/cluster-nodes"

# Check if cluster has been initialized
if [ ! -f "${NODE_SETUP_DIR}/generated/secrets.yaml" ]; then
    print_error "Cluster not initialized. Base cluster configuration is required."
    print_info "Run 'wild-cluster-config-generate' first to generate cluster secrets and base configs"
    exit 1
fi

# Get cluster configuration from config.yaml
CLUSTER_NAME=$(wild-config cluster.name)

print_info "Generating patch for node: $NODE_NAME"
print_info "Cluster: $CLUSTER_NAME"

# Check if the specified node is registered
NODE_INTERFACE=$(yq eval ".cluster.nodes.active.\"${NODE_NAME}\".interface" "${WC_HOME}/config.yaml" 2>/dev/null)
NODE_DISK=$(yq eval ".cluster.nodes.active.\"${NODE_NAME}\".disk" "${WC_HOME}/config.yaml" 2>/dev/null)
NODE_ROLE=$(yq eval ".cluster.nodes.active.\"${NODE_NAME}\".role" "${WC_HOME}/config.yaml" 2>/dev/null)
NODE_CURRENT_IP=$(yq eval ".cluster.nodes.active.\"${NODE_NAME}\".currentIp" "${WC_HOME}/config.yaml" 2>/dev/null)

if [ -z "$NODE_INTERFACE" ] || [ "$NODE_INTERFACE" = "null" ]; then
    print_error "Node $NODE_NAME is not registered in config.yaml"
    print_info "Please register the node first by running node hardware detection"
    print_info "Or run 'wild-setup-cluster' to register nodes interactively"
    exit 1
fi

# Get current IP for the node
if [ -z "$NODE_CURRENT_IP" ] || [ "$NODE_CURRENT_IP" = "null" ]; then
    print_error "Node $NODE_NAME has no current IP address set"
    exit 1
fi

# Determine node type
if [ "$NODE_ROLE" = "controlplane" ]; then
    NODE_TYPE="control"
    print_success "Registered control plane node: $NODE_NAME"
else
    NODE_TYPE="worker" 
    print_success "Registered worker node: $NODE_NAME"
fi

print_info "Node details:"
print_info "  - Name: $NODE_NAME"
print_info "  - Current IP: $NODE_CURRENT_IP"
print_info "  - Interface: $NODE_INTERFACE"
print_info "  - Disk: $NODE_DISK"
print_info "  - Type: $NODE_TYPE"

# Compile patch template for the specified node
print_info "Compiling patch template for $NODE_TYPE node $NODE_NAME..."

if [ "$NODE_TYPE" = "control" ]; then
    TEMPLATE_FILE="${TEMPLATE_SOURCE_DIR}/patch.templates/controlplane.yaml"
else
    TEMPLATE_FILE="${TEMPLATE_SOURCE_DIR}/patch.templates/worker.yaml" 
fi

# Use node name as the patch name
PATCH_FILE="${NODE_SETUP_DIR}/patch/${NODE_NAME}.yaml"

# Create a temporary template with the node name and IP for gomplate processing
TEMP_TEMPLATE="/tmp/${NODE_NAME//\//_}-$(date +%s).yaml"
sed -e "s/{{NODE_NAME}}/${NODE_NAME}/g" -e "s/{{NODE_IP}}/${NODE_CURRENT_IP}/g" "$TEMPLATE_FILE" > "$TEMP_TEMPLATE"
cat "$TEMP_TEMPLATE" | wild-compile-template > "$PATCH_FILE"
rm -f "$TEMP_TEMPLATE"

print_success "Patch generated successfully!"
echo ""
print_info "Generated patch file:"
print_info "  - $PATCH_FILE"
echo ""
print_info "Template used: ${TEMPLATE_FILE}"

print_success "Patch generation completed!"