#!/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}=== Socktop WebTerm - Kubernetes Deployment Script ===${NC}"
echo ""

# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}Error: kubectl is not installed or not in PATH${NC}"
    exit 1
fi

# Check if we can connect to the cluster
if ! kubectl cluster-info &> /dev/null; then
    echo -e "${RED}Error: Cannot connect to Kubernetes cluster${NC}"
    echo "Make sure your kubeconfig is set up correctly"
    echo ""
    echo "Available contexts:"
    kubectl config get-contexts
    exit 1
fi

# Show current context
CURRENT_CONTEXT=$(kubectl config current-context)
echo -e "${GREEN}✓ Connected to Kubernetes cluster${NC}"
echo -e "${BLUE}Current context:${NC} $CURRENT_CONTEXT"
echo ""

# Ask for namespace
read -p "Enter namespace to deploy to (default: default): " NAMESPACE
NAMESPACE=${NAMESPACE:-default}

echo -e "${BLUE}Target namespace:${NC} $NAMESPACE"
echo ""

# Create namespace if it doesn't exist
if ! kubectl get namespace "$NAMESPACE" &> /dev/null; then
    echo -e "${YELLOW}Namespace '$NAMESPACE' does not exist.${NC}"
    read -p "Create it? (y/N): " create_ns
    if [[ "$create_ns" =~ ^[Yy]$ ]]; then
        kubectl create namespace "$NAMESPACE"
        echo -e "${GREEN}✓ Namespace created${NC}"
    else
        echo -e "${RED}Deployment cancelled${NC}"
        exit 1
    fi
fi

echo ""

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Check if manifest files exist
REQUIRED_FILES=(
    "01-configmap.yaml"
    "02-secret.yaml"
    "03-deployment.yaml"
    "04-service.yaml"
    "05-ingress.yaml"
)

echo -e "${YELLOW}Checking for required manifest files...${NC}"
for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "$SCRIPT_DIR/$file" ]; then
        echo -e "${RED}Error: Missing required file: $file${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓${NC} Found $file"
done
echo ""

# Ask user if they want to configure TLS certificates
echo -e "${YELLOW}=== TLS Certificate Configuration ===${NC}"
echo "Do you have TLS certificates for your Raspberry Pi nodes?"
echo "(If not, the deployment will work but won't be able to connect to Pi nodes via TLS)"
echo ""
read -p "Path to folder containing .pem certificates (or press Enter to skip): " CERT_FOLDER

if [ -n "$CERT_FOLDER" ]; then
    # Remove trailing slash if present
    CERT_FOLDER="${CERT_FOLDER%/}"

    # Check if folder exists
    if [ ! -d "$CERT_FOLDER" ]; then
        echo -e "${RED}Error: Directory not found: $CERT_FOLDER${NC}"
        exit 1
    fi

    # Find all .pem files in the folder
    PEM_FILES=$(find "$CERT_FOLDER" -maxdepth 1 -name "*.pem" -type f)

    if [ -z "$PEM_FILES" ]; then
        echo -e "${RED}Error: No .pem files found in $CERT_FOLDER${NC}"
        exit 1
    fi

    echo ""
    echo -e "${YELLOW}Found certificates:${NC}"
    echo "$PEM_FILES" | while read file; do
        echo "  - $(basename "$file")"
    done
    echo ""

    echo -e "${YELLOW}Creating secret with TLS certificates...${NC}"

    # Build kubectl command with all .pem files
    CMD="kubectl create secret generic socktop-webterm-certs --namespace=$NAMESPACE --dry-run=client -o yaml"
    while IFS= read -r file; do
        filename=$(basename "$file")
        CMD="$CMD --from-file=$filename=$file"
    done <<< "$PEM_FILES"

    # Execute and apply
    eval "$CMD" | kubectl apply -f -

    echo -e "${GREEN}✓ TLS certificates configured${NC}"
else
    echo -e "${YELLOW}Skipping TLS certificate configuration${NC}"
    echo "The deployment will use the placeholder secret from 02-secret.yaml"
fi

echo ""
echo -e "${YELLOW}=== Deploying to Kubernetes ===${NC}"
echo ""

# Function to apply manifest with namespace override
apply_manifest() {
    local file=$1
    local description=$2

    echo -e "${BLUE}Applying $description...${NC}"
    # Use kubectl apply with namespace flag - this overrides any namespace in the manifest
    kubectl apply -f "$SCRIPT_DIR/$file" -n "$NAMESPACE"
    echo -e "${GREEN}✓ $description applied${NC}"
    echo ""
}

# Apply manifests in order
apply_manifest "01-configmap.yaml" "ConfigMap"
apply_manifest "02-secret.yaml" "Secret"
apply_manifest "03-deployment.yaml" "Deployment"
apply_manifest "04-service.yaml" "Service"
apply_manifest "05-ingress.yaml" "Ingress"

echo -e "${GREEN}=== Deployment Complete! ===${NC}"
echo ""

# Wait for pods to be ready
echo -e "${YELLOW}Waiting for pods to be ready...${NC}"
echo "(This may take a minute while images are pulled)"
echo ""

if kubectl wait --for=condition=ready pod -l app=socktop-webterm -n "$NAMESPACE" --timeout=300s 2>/dev/null; then
    echo ""
    echo -e "${GREEN}✓ All pods are ready!${NC}"
else
    echo ""
    echo -e "${YELLOW}Warning: Pods took longer than expected to start${NC}"
    echo "Check status with: kubectl get pods -l app=socktop-webterm -n $NAMESPACE"
fi

echo ""
echo -e "${GREEN}=== Deployment Status ===${NC}"
echo ""

# Show deployment status
echo -e "${BLUE}Pods:${NC}"
kubectl get pods -l app=socktop-webterm -n "$NAMESPACE"
echo ""

echo -e "${BLUE}Service:${NC}"
kubectl get svc socktop-webterm -n "$NAMESPACE"
echo ""

echo -e "${BLUE}Ingress:${NC}"
kubectl get ingress socktop-webterm -n "$NAMESPACE"
echo ""

echo -e "${GREEN}=== Access Information ===${NC}"
echo ""
echo "Your application will be available at:"
echo -e "  ${YELLOW}https://socktop.io${NC}"
echo -e "  ${YELLOW}https://www.socktop.io${NC}"
echo -e "  ${YELLOW}https://origin.socktop.io${NC}"
echo ""
echo "Note: SSL is terminated at your external NGINX Proxy Manager."
echo "Configure your proxy hosts to forward traffic to k3s on port 8080."
echo "See NGINX-PROXY-MANAGER.md for details."
echo ""

echo -e "${GREEN}=== Useful Commands ===${NC}"
echo ""
echo "View logs:"
echo -e "  ${BLUE}kubectl logs -l app=socktop-webterm -n $NAMESPACE -f${NC}"
echo ""
echo "Check pod status:"
echo -e "  ${BLUE}kubectl get pods -l app=socktop-webterm -n $NAMESPACE${NC}"
echo ""
echo "Describe deployment:"
echo -e "  ${BLUE}kubectl describe deployment socktop-webterm -n $NAMESPACE${NC}"
echo ""
echo "Scale deployment:"
echo -e "  ${BLUE}kubectl scale deployment socktop-webterm --replicas=5 -n $NAMESPACE${NC}"
echo ""
echo "Update image:"
echo -e "  ${BLUE}kubectl set image deployment/socktop-webterm webterm=192.168.1.208:3002/jason/socktop-webterm:0.2.0 -n $NAMESPACE${NC}"
echo ""
echo "Delete deployment:"
echo -e "  ${BLUE}kubectl delete -f $SCRIPT_DIR -n $NAMESPACE${NC}"
echo ""

echo -e "${GREEN}Done!${NC}"
