#!/bin/bash
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== kubectl Configuration Setup for k3s ===${NC}"
echo ""
echo "This script will help you configure kubectl to connect to your k3s cluster."
echo ""

# Check if kubectl is installed
if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}Error: kubectl is not installed${NC}"
    echo ""
    echo "Install kubectl first:"
    echo "  https://kubernetes.io/docs/tasks/tools/"
    exit 1
fi

echo -e "${GREEN}✓ kubectl is installed${NC}"
echo ""

# Ask for k3s server details
echo -e "${YELLOW}Step 1: k3s Server Information${NC}"
echo ""
read -p "Enter k3s server IP address: " K3S_SERVER_IP

if [ -z "$K3S_SERVER_IP" ]; then
    echo -e "${RED}Error: Server IP cannot be empty${NC}"
    exit 1
fi

read -p "Enter SSH username for k3s server (default: ubuntu): " SSH_USER
SSH_USER=${SSH_USER:-ubuntu}

echo ""
echo -e "${YELLOW}Step 2: Retrieving kubeconfig from k3s server${NC}"
echo ""

# Check if we can SSH to the server
if ! ssh -q -o ConnectTimeout=5 -o BatchMode=yes ${SSH_USER}@${K3S_SERVER_IP} exit 2>/dev/null; then
    echo -e "${YELLOW}⚠ Cannot SSH with key-based auth to ${SSH_USER}@${K3S_SERVER_IP}${NC}"
    echo -e "${YELLOW}  You may need to enter password...${NC}"
    echo ""
fi

# Get the kubeconfig from k3s server
echo "Fetching kubeconfig from k3s server..."
KUBECONFIG_CONTENT=$(ssh ${SSH_USER}@${K3S_SERVER_IP} "sudo cat /etc/rancher/k3s/k3s.yaml" 2>/dev/null)

if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Failed to retrieve kubeconfig from server${NC}"
    echo ""
    echo "Please check:"
    echo "  - SSH access to ${K3S_SERVER_IP}"
    echo "  - k3s is installed on the server"
    echo "  - You have sudo access"
    exit 1
fi

echo -e "${GREEN}✓ Retrieved kubeconfig from server${NC}"
echo ""

# Modify the server IP in the kubeconfig
echo "Modifying server IP from 127.0.0.1 to ${K3S_SERVER_IP}..."
MODIFIED_KUBECONFIG=$(echo "$KUBECONFIG_CONTENT" | sed "s|server: https://127.0.0.1:6443|server: https://${K3S_SERVER_IP}:6443|g")

echo -e "${GREEN}✓ Server IP updated${NC}"
echo ""

# Ask where to save the config
echo -e "${YELLOW}Step 3: Save Configuration${NC}"
echo ""
echo "Choose how to save the kubeconfig:"
echo "  1) Replace ~/.kube/config (WARNING: This will overwrite existing config!)"
echo "  2) Save as ~/.kube/config-k3s (separate file, safer)"
echo "  3) Merge with existing ~/.kube/config (recommended if you have other clusters)"
echo ""
read -p "Enter choice (1/2/3, default: 2): " SAVE_CHOICE
SAVE_CHOICE=${SAVE_CHOICE:-2}

case $SAVE_CHOICE in
    1)
        # Replace existing config
        mkdir -p ~/.kube

        # Backup existing config if it exists
        if [ -f ~/.kube/config ]; then
            BACKUP_FILE=~/.kube/config.backup.$(date +%Y%m%d-%H%M%S)
            echo "Backing up existing config to $BACKUP_FILE"
            cp ~/.kube/config "$BACKUP_FILE"
        fi

        echo "$MODIFIED_KUBECONFIG" > ~/.kube/config
        chmod 600 ~/.kube/config

        echo -e "${GREEN}✓ Saved to ~/.kube/config${NC}"
        KUBECONFIG_PATH="~/.kube/config"
        ;;

    2)
        # Save as separate file
        mkdir -p ~/.kube
        echo "$MODIFIED_KUBECONFIG" > ~/.kube/config-k3s
        chmod 600 ~/.kube/config-k3s

        echo -e "${GREEN}✓ Saved to ~/.kube/config-k3s${NC}"
        echo ""
        echo "To use this config, run:"
        echo -e "  ${YELLOW}export KUBECONFIG=~/.kube/config-k3s${NC}"
        echo ""
        echo "Or add to your shell profile (~/.bashrc, ~/.zshrc, ~/.config/fish/config.fish):"
        echo -e "  ${YELLOW}export KUBECONFIG=~/.kube/config-k3s${NC}"

        KUBECONFIG_PATH="~/.kube/config-k3s"
        export KUBECONFIG=~/.kube/config-k3s
        ;;

    3)
        # Merge with existing config
        mkdir -p ~/.kube

        if [ ! -f ~/.kube/config ]; then
            echo "No existing config found, creating new one..."
            echo "$MODIFIED_KUBECONFIG" > ~/.kube/config
            chmod 600 ~/.kube/config
            echo -e "${GREEN}✓ Saved to ~/.kube/config${NC}"
        else
            echo "Merging with existing config..."

            # Save k3s config to temp file
            echo "$MODIFIED_KUBECONFIG" > /tmp/k3s-config.yaml

            # Backup existing config
            BACKUP_FILE=~/.kube/config.backup.$(date +%Y%m%d-%H%M%S)
            echo "Backing up existing config to $BACKUP_FILE"
            cp ~/.kube/config "$BACKUP_FILE"

            # Merge configs
            KUBECONFIG=~/.kube/config:/tmp/k3s-config.yaml kubectl config view --flatten > /tmp/config-merged.yaml

            # Replace original config
            mv /tmp/config-merged.yaml ~/.kube/config
            chmod 600 ~/.kube/config

            # Clean up
            rm /tmp/k3s-config.yaml

            echo -e "${GREEN}✓ Merged and saved to ~/.kube/config${NC}"
        fi

        KUBECONFIG_PATH="~/.kube/config"
        ;;

    *)
        echo -e "${RED}Invalid choice${NC}"
        exit 1
        ;;
esac

echo ""
echo -e "${YELLOW}Step 4: Testing Connection${NC}"
echo ""

# Test the connection
if kubectl cluster-info &> /dev/null; then
    echo -e "${GREEN}✓ Successfully connected to k3s cluster!${NC}"
    echo ""

    # Show cluster info
    echo -e "${BLUE}Cluster Information:${NC}"
    kubectl cluster-info
    echo ""

    # Show nodes
    echo -e "${BLUE}Nodes:${NC}"
    kubectl get nodes
    echo ""

    # Show contexts
    echo -e "${BLUE}Available Contexts:${NC}"
    kubectl config get-contexts
    echo ""

else
    echo -e "${RED}✗ Failed to connect to k3s cluster${NC}"
    echo ""
    echo "Troubleshooting:"
    echo "  - Verify k3s server IP: ${K3S_SERVER_IP}"
    echo "  - Check if port 6443 is accessible"
    echo "  - Test with: nc -zv ${K3S_SERVER_IP} 6443"
    exit 1
fi

echo -e "${GREEN}=== Setup Complete! ===${NC}"
echo ""
echo "Your kubectl is now configured to connect to k3s at ${K3S_SERVER_IP}"
echo ""
echo "Useful commands:"
echo -e "  ${BLUE}kubectl get nodes${NC}              - List cluster nodes"
echo -e "  ${BLUE}kubectl get pods --all-namespaces${NC} - List all pods"
echo -e "  ${BLUE}kubectl config get-contexts${NC}    - View available contexts"
echo -e "  ${BLUE}kubectl config current-context${NC} - View current context"
echo ""

if [ "$SAVE_CHOICE" = "2" ]; then
    echo "Remember to set KUBECONFIG environment variable:"
    echo -e "  ${YELLOW}export KUBECONFIG=~/.kube/config-k3s${NC}"
    echo ""
fi

echo "Next steps:"
echo "  1. Run: cd kubernetes"
echo "  2. Run: ./setup-registry.sh (configure registry on all nodes)"
echo "  3. Run: ./deploy.sh (deploy Socktop WebTerm)"
echo ""
echo -e "${GREEN}Done!${NC}"
