#!/bin/bash

NAMESPACE="map-pressure"
TOTAL_PODS=300

echo "=== Unique Pod Generator ==="
echo "Creating $TOTAL_PODS unique Deployments in namespace: $NAMESPACE"
echo "Each pod will have a unique label combination to force Cilium identity creation"
echo

# Label components for generating unique combinations
APPS=("web" "api" "db" "cache" "queue" "worker" "proxy" "auth" "monitor" "logging" "batch")
TIERS=("frontend" "backend" "data" "infra" "security" "ops" "test" "staging" "prod" "dev")
VERSIONS=("v1" "v2" "v3" "v4" "v5" "v6" "v7" "v8" "v9" "v10" "v11" "v12" "v13" "v14" "v15" "v16" "v17" "v18" "v19" "v20")
ENVIRONMENTS=("prod" "staging" "dev" "test" "qa" "uat" "demo" "sandbox" "preview" "beta")
REGIONS=("us-east" "us-west" "eu-central" "ap-south" "ca-central" "sa-east" "af-south" "me-central" "ap-east" "eu-west" "eu-north" "ap-northeast" "ap-southeast")

# Create namespace if it doesn't exist
kubectl create namespace $NAMESPACE --dry-run=client -o yaml | kubectl apply -f -

# Generate $TOTAL_PODS unique deployments
for POD_INDEX in $(seq 0 $((TOTAL_PODS - 1))); do
    # Generate unique label combinations with better distribution
    # Use different prime-like divisors to avoid pattern overlap
    APP=${APPS[$(( POD_INDEX % ${#APPS[@]} ))]}
    TIER=${TIERS[$(( (POD_INDEX / 11) % ${#TIERS[@]} ))]}
    VERSION=${VERSIONS[$(( (POD_INDEX / 7) % ${#VERSIONS[@]} ))]}
    ENV=${ENVIRONMENTS[$(( (POD_INDEX / 17) % ${#ENVIRONMENTS[@]} ))]}
    REGION=${REGIONS[$(( (POD_INDEX / 23) % ${#REGIONS[@]} ))]}
    
    # Additional unique labels with different cycles
    COMPONENT="component-$(( (POD_INDEX / 3) % 25 ))"
    TEAM="team-$(( (POD_INDEX / 5) % 18 ))"
    OWNER="owner-$(( (POD_INDEX / 13) % 16 ))"
    
    # Add more differentiating labels for higher uniqueness
    BUILD="build-$(( POD_INDEX % 100 ))"
    SHARD="shard-$(( (POD_INDEX / 25) % 8 ))"
    
    DEPLOYMENT_NAME="unique-pod-${POD_INDEX}"
    
    echo "[$POD_INDEX/$TOTAL_PODS] Creating Deployment: $DEPLOYMENT_NAME"
    
    # Create the deployment with unique labels
    cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
  name: $DEPLOYMENT_NAME
  namespace: $NAMESPACE
  labels:
    generator: unique-pods
    pod-index: "$POD_INDEX"
spec:
  replicas: 1
  selector:
    matchLabels:
      generator: unique-pods
      app: $APP
      tier: $TIER
      pod-index: "$POD_INDEX"
  template:
    metadata:
      labels:
        generator: unique-pods
        app: $APP
        tier: $TIER
        version: $VERSION
        environment: $ENV
        region: $REGION
        component: $COMPONENT
        team: $TEAM
        owner: $OWNER
        build: $BUILD
        shard: $SHARD
        pod-index: "$POD_INDEX"
        unique-id: "uid-$POD_INDEX"
    spec:
      containers:
      - name: fqdn-stressor
        image: nicolaka/netshoot
        command: ["/bin/bash", "-c"]
        args:
        - |
          #!/bin/bash
          # Array of URLs to stress FQDN cache
          URLS=(
            "https://login.microsoftonline.com"
            "https://login.microsoft.com"
            "https://www.office.com"
            "https://www.google.com"
            "https://googleapis.com"
            "https://gstatic.com"
            "https://api.github.com"
            "https://github.com"
            "https://raw.githubusercontent.com"
            "https://s3.amazonaws.com"
            "https://ec2.us-east-1.amazonaws.com"
            "https://sts.amazonaws.com"
            "https://cdn.jsdelivr.net"
            "https://unpkg.com"
            "https://cdnjs.cloudflare.com"
            "https://fastly.com"
            "https://amazonaws.com"
            "https://graph.facebook.com"
            "https://api.twitter.com"
            "https://api.instagram.com"
            "https://linkedin.com"
            "https://youtube.com"
            "https://googlevideo.com"
            "https://ytimg.com"
            "https://netflix.com"
            "https://nflximg.net"
            "https://cnn.com"
            "https://bbc.com"
            "https://reuters.com"
            "https://reddit.com"
            "https://hackernews.com"
            "https://amazon.com"
            "https://ebay.com"
            "https://shopify.com"
            "https://azure.com"
            "https://cloudflare.com"
            "https://digitalocean.com"
            "https://weather.com"
            "https://openweathermap.org"
          )
          
          echo "Starting FQDN cache stress test - Pod: $HOSTNAME"
          echo "Will curl random URLs every 10 seconds to stress Cilium's FQDN cache"
          
          while true; do
            # Pick a random URL from the array
            RANDOM_INDEX=\$RANDOM
            ARRAY_SIZE=\${#URLS[@]}
            URL_INDEX=\$((RANDOM_INDEX % ARRAY_SIZE))
            SELECTED_URL=\${URLS[URL_INDEX]}
            
            echo "[\$(date)] Pod \$HOSTNAME: Curling \$SELECTED_URL"
            
            # Curl with timeout and error handling
            curl -s --connect-timeout 5 --max-time 10 "\$SELECTED_URL" > /dev/null 2>&1
            CURL_EXIT_CODE=\$?
            
            if [ \$CURL_EXIT_CODE -eq 0 ]; then
              echo "[\$(date)] Pod \$HOSTNAME: Successfully accessed \$SELECTED_URL"
            else
              echo "[\$(date)] Pod \$HOSTNAME: Failed to access \$SELECTED_URL (exit code: \$CURL_EXIT_CODE)"
            fi
            
            # Wait 10 seconds before next request
            sleep 10
          done
EOF
    
    # Add small delay to avoid overwhelming the API server
    if [ $(( POD_INDEX % 10 )) -eq 9 ]; then
        echo "=== Batch of 10 deployments created, checking most recent ==="
        # Show the last 5 deployments from this batch
        START_IDX=$((POD_INDEX - 4))
        for i in $(seq $START_IDX $POD_INDEX); do
            kubectl get deployment unique-pod-$i -n $NAMESPACE --no-headers 2>/dev/null || true
        done
        sleep 2
    fi
done

echo
echo "=== Pod Generation Complete ==="
echo "Created $TOTAL_PODS unique Deployments in namespace: $NAMESPACE"
echo
echo "Final statistics:"
echo "- Total Deployments: $(kubectl get deployments -n $NAMESPACE --no-headers | wc -l)"
echo "- Total Pods: $(kubectl get pods -n $NAMESPACE --no-headers | wc -l)"
echo "- Total CiliumIdentities: $(kubectl get ciliumidentities --no-headers | wc -l)"
echo
echo "Wait for all pods to be running, then use: ./generate-network-policies.sh"
