#!/usr/bin/env bash
set -euo pipefail

# Script variables - customize these as needed
WORKING_DIR="/home/klbfadmin/installation-file/visionx"
POD_LABEL_SELECTOR="app=elvasoft-ris-v1"
POD_NAMESPACE="ris-elvasoft"
TRAEFIK_LINES='
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
  name: 'elvasoft-ris-v1-route'
  namespace: ris-elvasoft
spec:
  entryPoints:
    - ris
  routes:
    - match: PathPrefix(`/`)
      kind: Rule
      services:
        - name: 'elvasoft-ris-v1'
          port: 3000
'

# Multiple find-and-replace pairs (format: "find1|replace1|find2|replace2|...")
# Use '|' as delimiter between find/replace pairs. Escape special sed characters if needed.
REPLACEMENTS="app: 'elvasoft-ris'|app: 'elvasoft-ris-v1'|name: 'elvasoft-ris'|name: 'elvasoft-ris-v1'|type: NodePort|type: ClusterIP"

# Lines/patterns to DELETE before find/replace (one per line, exact match or regex)
LINES_TO_DELETE="\
      protocol: TCP
      nodePort: 30000
"

# Change to working directory
echo "Changing to working directory: $WORKING_DIR"
cd "$WORKING_DIR" || {
    echo "Error: Working directory '$WORKING_DIR' does not exist or is not accessible"
    exit 1
}

# Verify ris.yaml exists
if [ ! -f "ris.yaml" ]; then
    echo "Error: ris.yaml not found in $WORKING_DIR"
    exit 1
fi

# Copy and perform multiple replacements
echo "Copying ris.yaml to ris-v1.yaml..."
cp ris.yaml ris-v1.yaml

# Delete specified lines/patterns FIRST
echo "Deleting specified lines/patterns from ris-v1.yaml..."
printf '%s\n' "$LINES_TO_DELETE" | while IFS= read -r pattern; do
    if [ -n "$pattern" ]; then
        echo "  Deleting lines matching: '$pattern'"
        sed -i "/^${pattern}$/d" ris-v1.yaml
    fi
done

echo "Performing multiple find-and-replace operations in ris-v1.yaml..."
IFS='|' read -ra PAIRS <<< "$REPLACEMENTS"
i=0
while [ $i -lt ${#PAIRS[@]} ]; do
    FIND_STR="${PAIRS[$i]:-}"
    if [ $((i + 1)) -lt ${#PAIRS[@]} ]; then
        REPLACE_STR="${PAIRS[$((i + 1))]:-}"
        if [ -n "$FIND_STR" ] && [ -n "$REPLACE_STR" ]; then
            echo "  Replacing '$FIND_STR' -> '$REPLACE_STR'"
            sed -i "s|${FIND_STR}|${REPLACE_STR}|g" ris-v1.yaml
        fi
    fi
    i=$((i + 2))
done

echo "Copying ris-v1.yaml to ris-v1-no-traefik.yaml..."
cp ris-v1.yaml ris-v1-no-traefik.yaml

# Apply without Traefik
echo "Applying ris-v1-no-traefik.yaml to Kubernetes cluster..."
kubectl apply -f ris-v1-no-traefik.yaml

# Delete old Traefik IngressRoute from 11-ingress-custom-port.yaml
echo "Copying 11-ingress-custom-port.yaml to 11-ingress-custom-port-backup.yaml..."
cp 11-ingress-custom-port.yaml 11-ingress-custom-port-backup.yaml
echo "Cleaning up old Traefik IngressRoute from 11-ingress-custom-port.yaml..."
if [ -f "11-ingress-custom-port.yaml" ]; then
    # Delete the entire IngressRoute block by matching the unique kind/apiVersion
    sed -i '/^---$/N;/^---\napiVersion: traefik.io\/v1alpha1$/,/services:$/d' 11-ingress-custom-port.yaml || {
        echo "  Warning: Could not delete IngressRoute block (file may already be clean)"
    }
    echo "  Deleted old ris-route-3000 IngressRoute from 11-ingress-custom-port.yaml"
else
    echo "  Warning: 11-ingress-custom-port.yaml not found (skipping cleanup)"
fi

# Append Traefik configuration
echo "Appending Traefik configuration to ris-v1.yaml..."
printf '%s\n' "$TRAEFIK_LINES" >> ris-v1.yaml

# Get the pod name using label selector
echo "Looking for pod with label selector '$POD_LABEL_SELECTOR' in namespace '$POD_NAMESPACE'..."
get_pod_name() {
    kubectl get pods \
        --namespace="$POD_NAMESPACE" \
        --selector="$POD_LABEL_SELECTOR" \
        --sort-by='.metadata.creationTimestamp' \
        --no-headers \
        -o custom-columns=":metadata.name" | tail -n 1
}
POD_NAME=$(get_pod_name)
if [ -z "$POD_NAME" ]; then
    echo "Error: No pod found with selector '$POD_LABEL_SELECTOR' in namespace '$POD_NAMESPACE'"
    exit 1
fi
echo "Found pod: $POD_NAME"

# Wait for pod to be ready before streaming logs
wait_for_pod_ready() {
    local pod_name="$1"
    local namespace="$2"
    local max_wait=300  # 5 minutes max
    
    echo "Waiting for pod '$pod_name' to be Ready (max $max_wait seconds)..."
    for ((wait=0; wait<max_wait; wait+=5)); do
        local status=$(kubectl get pod "$pod_name" -n "$namespace" -o jsonpath='{.status.phase}')
        local ready=$(kubectl get pod "$pod_name" -n "$namespace" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}')
        local containers=$(kubectl get pod "$pod_name" -n "$namespace" -o jsonpath='{.status.containerStatuses[*].state.waiting.reason}')
        
        echo "  Pod status: $status, Ready: $ready, Containers: $containers (waited ${wait}s)"
        
        if [ "$status" = "Running" ] && [ "$ready" = "True" ]; then
            echo "✓ Pod '$pod_name' is Ready!"
            return 0
        fi
        
        sleep 5
    done
    
    echo "✗ Pod '$pod_name' not ready after $max_wait seconds"
    return 1
}

# Function to wait for startup confirmation in logs
wait_for_startup_logs() {
    local pod_name="$1"
    local namespace="$2"
    local max_wait=600  # 10 minutes max
    
    echo "Waiting for '✓ Starting...' in pod logs (max $max_wait seconds)..."
    kubectl logs "$pod_name" -n "$namespace" --tail=100 | grep -q "✓ Starting..." && {
        echo "✓ Found startup confirmation in logs!"
        return 0
    }
    
    for ((wait=0; wait<max_wait; wait+=10)); do
        if kubectl logs "$pod_name" -n "$namespace" --tail=200 2>/dev/null | grep -q "✓ Starting..."; then
            echo "✓ Found '✓ Starting...' in logs after ${wait}s!"
            return 0
        fi
        echo "  Still waiting for startup confirmation... (${wait}s)"
        sleep 10
    done
    
    echo "✗ Startup confirmation not found after $max_wait seconds"
    return 1
}

# Enhanced prompt_apply with 4 interactive options
prompt_apply() {
    echo -e "\n🎯 CHOOSE ACTION FOR ris-v1.yaml (with Traefik):"
    echo "  1) ✅ YES - Apply now"
    echo "  2) ⏭️  NO - Skip"
    echo "  3) 🔄 ROLLBACK - Delete ris-v1-no-traefik.yaml"
    echo "  4) 📋 SHOW - Preview ris-v1.yaml diff"
    
    select choice in "Yes (apply)" "No (skip)" "Rollback" "Show diff"; do
        case $REPLY in
            1|Y|y|"")
                echo "     🗑️ DELETING ris-route-3000 IngressRoute..."
                kubectl delete ingressroute ris-route-3000 -n ris-elvasoft
                echo "     🚀 APPLYING ris-v1.yaml with Traefik configuration..."
                kubectl apply -f ris-v1.yaml
                echo "     ✅ Applied successfully!"
                exit 0
                ;;
            2|N|n)
                echo "     ⏭️  Skipping ris-v1.yaml application"
                exit 0
                ;;
            3|R|r)
                echo "     🗑️  ROLLBACK - Deleting ris-v1-no-traefik.yaml..."
                kubectl delete -f ris-v1-no-traefik.yaml --ignore-not-found=true
                kubectl apply -f 11-ingress-custom-port-backup.yaml
                echo "     ✅ Rollback complete!"
                exit 0
                ;;
            4|D|d|S|s)
                echo "     📋 PREVIEW - Diff between original and Traefik version:"
                echo "     (Lines with + are Traefik config added)"
                diff -u ris-v1-no-traefik.yaml ris-v1.yaml || true
                echo ""
                # Ask again after preview
                prompt_apply
                return 0
                ;;
            *)
                echo "     ⏰ Invalid → SKIP"
                exit 0
                ;;
        esac
    done < /dev/tty
}

# Wait for pod to be ready first
wait_for_pod_ready "$POD_NAME" "$POD_NAMESPACE" || {
    echo "Warning: Pod not ready, but continuing..."
}

# Wait for application startup confirmation in logs
wait_for_startup_logs "$POD_NAME" "$POD_NAMESPACE" || {
    echo "Warning: Startup confirmation not found, but continuing to prompt..."
}

echo -e "\n"  # Visual separator

# Now safely prompt (no log interference)
prompt_apply