#!/bin/bash

# Deployment script voor Kubernetes

set -e

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

# Functies
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Variabelen
NAMESPACE="snauw-counter"
IMAGE_TAG="${IMAGE_TAG:-latest}"
CONTEXT="${KUBE_CONTEXT:-default}"

# Help functie
show_help() {
    cat << EOF
Snauw Counter Kubernetes Deployment Script

USAGE:
    $0 [COMMAND] [OPTIONS]

COMMANDS:
    deploy      Deploy application to Kubernetes
    status      Show deployment status
    logs        Show application logs
    scale       Scale deployment
    rollback    Rollback to previous version
    cleanup     Remove deployment

OPTIONS:
    -t, --tag       Docker image tag (default: latest)
    -c, --context   Kubernetes context (default: default)
    -n, --namespace Kubernetes namespace (default: snauw-counter)
    -h, --help      Show this help

EXAMPLES:
    $0 deploy -t v1.0.0
    $0 scale 5
    $0 logs -f
    $0 rollback
EOF
}

# Deploy functie
deploy() {
    log_info "Deploying Snauw Counter to Kubernetes..."

    # Check if namespace exists
    if ! kubectl get namespace $NAMESPACE &> /dev/null; then
        log_info "Creating namespace $NAMESPACE"
        kubectl apply -f k8s/namespace.yaml
    fi

    # Apply manifests
    log_info "Applying ConfigMap and Secrets..."
    kubectl apply -f k8s/configmap.yaml

    log_info "Creating SQLite PVC..."
    kubectl apply -f k8s/sqlite-pvc.yaml

    log_info "Deploying application..."
    export IMAGE_TAG=$IMAGE_TAG
    envsubst < k8s/deployment.yaml | kubectl apply -f -
    kubectl apply -f k8s/service.yaml
    kubectl apply -f k8s/ingress.yaml
    kubectl apply -f k8s/scaling.yaml

    # Wait for deployment
    log_info "Waiting for deployment to be ready..."
    kubectl rollout status deployment/snauw-counter -n $NAMESPACE --timeout=300s

    log_success "Deployment completed successfully!"
}

# Status functie
status() {
    log_info "Checking deployment status..."

    echo "=== NAMESPACE ==="
    kubectl get namespace $NAMESPACE

    echo -e "\n=== DEPLOYMENTS ==="
    kubectl get deployments -n $NAMESPACE

    echo -e "\n=== PODS ==="
    kubectl get pods -n $NAMESPACE

    echo -e "\n=== SERVICES ==="
    kubectl get services -n $NAMESPACE

    echo -e "\n=== INGRESS ==="
    kubectl get ingress -n $NAMESPACE

    echo -e "\n=== HPA ==="
    kubectl get hpa -n $NAMESPACE
}

# Logs functie
logs() {
    FOLLOW_FLAG=""
    if [[ "$1" == "-f" ]]; then
        FOLLOW_FLAG="-f"
    fi

    log_info "Showing application logs..."
    kubectl logs -l app.kubernetes.io/name=snauw-counter -n $NAMESPACE $FOLLOW_FLAG
}

# Scale functie
scale() {
    REPLICAS=${1:-2}
    log_info "Scaling deployment to $REPLICAS replicas..."
    kubectl scale deployment/snauw-counter --replicas=$REPLICAS -n $NAMESPACE
    kubectl rollout status deployment/snauw-counter -n $NAMESPACE
    log_success "Scaled to $REPLICAS replicas"
}

# Rollback functie
rollback() {
    log_info "Rolling back to previous version..."
    kubectl rollout undo deployment/snauw-counter -n $NAMESPACE
    kubectl rollout status deployment/snauw-counter -n $NAMESPACE
    log_success "Rollback completed"
}

# Cleanup functie
cleanup() {
    log_warning "This will remove all Snauw Counter resources from Kubernetes"
    read -p "Are you sure? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "Removing deployment..."
        kubectl delete namespace $NAMESPACE
        log_success "Cleanup completed"
    else
        log_info "Cleanup cancelled"
    fi
}

# Main script
case "$1" in
    deploy)
        shift
        while [[ $# -gt 0 ]]; do
            case $1 in
                -t|--tag)
                    IMAGE_TAG="$2"
                    shift 2
                    ;;
                -c|--context)
                    CONTEXT="$2"
                    kubectl config use-context $CONTEXT
                    shift 2
                    ;;
                -n|--namespace)
                    NAMESPACE="$2"
                    shift 2
                    ;;
                *)
                    log_error "Unknown option: $1"
                    show_help
                    exit 1
                    ;;
            esac
        done
        deploy
        ;;
    status)
        status
        ;;
    logs)
        shift
        logs "$@"
        ;;
    scale)
        shift
        scale "$@"
        ;;
    rollback)
        rollback
        ;;
    cleanup)
        cleanup
        ;;
    -h|--help)
        show_help
        ;;
    *)
        log_error "Unknown command: $1"
        show_help
        exit 1
        ;;
esac
