#!/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 "Do you want to configure TLS certificates now? (y/N): " configure_certs

if [[ "$configure_certs" =~ ^[Yy]$ ]]; then
    echo ""
    echo -e "${YELLOW}Please provide paths to your certificate files:${NC}"

    read -p "Path to rpi-master.pem: " master_cert
    read -p "Path to rpi-worker-1.pem: " worker1_cert
    read -p "Path to rpi-worker-2.pem: " worker2_cert
    read -p "Path to rpi-worker-3.pem: " worker3_cert

    # Verify files exist
    for cert in "$master_cert" "$worker1_cert" "$worker2_cert" "$worker3_cert"; do
        if [ ! -f "$cert" ]; then
            echo -e "${RED}Error: Certificate file not found: $cert${NC}"
            exit 1
        fi
    done

    echo ""
    echo -e "${YELLOW}Creating secret with TLS certificates...${NC}"
    kubectl create secret generic socktop-webterm-certs \
        --from-file=rpi-master.pem="$master_cert" \
        --from-file=rpi-worker-1.pem="$worker1_cert" \
        --from-file=rpi-worker-2.pem="$worker2_cert" \
        --from-file=rpi-worker-3.pem="$worker3_cert" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | 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 ""

# Apply manifests in order
echo -e "${BLUE}Applying ConfigMap...${NC}"
kubectl apply -f "$SCRIPT_DIR/01-configmap.yaml" -n "$NAMESPACE"
echo -e "${GREEN}✓ ConfigMap applied${NC}"
echo ""

echo -e "${BLUE}Applying Secret...${NC}"
kubectl apply -f "$SCRIPT_DIR/02-secret.yaml" -n "$NAMESPACE"
echo -e "${GREEN}✓ Secret applied${NC}"
echo ""

echo -e "${BLUE}Applying Deployment...${NC}"
kubectl apply -f "$SCRIPT_DIR/03-deployment.yaml" -n "$NAMESPACE"
echo -e "${GREEN}✓ Deployment applied${NC}"
echo ""

echo -e "${BLUE}Applying Service...${NC}"
kubectl apply -f "$SCRIPT_DIR/04-service.yaml" -n "$NAMESPACE"
echo -e "${GREEN}✓ Service applied${NC}"
echo ""

echo -e "${BLUE}Applying Ingress...${NC}"
kubectl apply -f "$SCRIPT_DIR/05-ingress.yaml" -n "$NAMESPACE"
echo -e "${GREEN}✓ Ingress applied${NC}"
echo ""

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; 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}"
