#!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-cluster-config-generate [options]"
    echo ""
    echo "Generate initial Talos cluster configuration using talosctl gen config."
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo ""
    echo "This script will:"
    echo "  - Generate initial cluster secrets and configurations"
    echo "  - Create base controlplane.yaml and worker.yaml templates"
    echo "  - Set up the foundation for node-specific machine configs"
    echo ""
    echo "Requirements:"
    echo "  - Must be run from a Wild Cloud home directory"
    echo "  - talosctl must be available in PATH"
}

# Parse arguments
FORCE=false
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            usage
            exit 1
            ;;
    esac
done

# 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

# =============================================================================
# CLUSTER CONFIGURATION GENERATION
# =============================================================================

print_header "Talos Cluster Configuration Generation"

# Ensure required directories exist
NODE_SETUP_DIR="${WC_HOME}/setup/cluster-nodes"
mkdir -p "${NODE_SETUP_DIR}/generated"

# Generate cluster secrets

if [ -f "${NODE_SETUP_DIR}/generated/secrets.yaml" ] && [ "$FORCE" = false ]; then
    print_success "Cluster secrets already exists in ${NODE_SETUP_DIR}/generated/"
    exit 0
fi

# Prepare directory for generated secrets
print_info "Generating new cluster secrets..."
if [ -d "${NODE_SETUP_DIR}/generated" ]; then
    print_warning "Removing existing secrets directory..."
    rm -rf "${NODE_SETUP_DIR}/generated"
fi
mkdir -p "${NODE_SETUP_DIR}/generated"
talosctl gen secrets
print_info "New secrets will be generated in ${NODE_SETUP_DIR}/generated/"

# Ensure we have the configuration we need.     

prompt_if_unset_config "cluster.name" "Cluster name" "wild-cluster"
CLUSTER_NAME=$(wild-config "cluster.name")

prompt_if_unset_config "cluster.nodes.control.vip" "Control plane virtual IP (VIP)"
VIP=$(wild-config "cluster.nodes.control.vip")

# Generate cluster configuration
print_info "Generating initial cluster configuration..."
print_info "Cluster name: $CLUSTER_NAME"
print_info "Control plane endpoint: https://$VIP:6443"

cd "${NODE_SETUP_DIR}/generated"
talosctl gen config --with-secrets secrets.yaml "$CLUSTER_NAME" "https://$VIP:6443"
cd - >/dev/null

# Verify generated files

print_success "Cluster configuration generation completed!"