#!/bin/bash
# Blue-Green Deployment Strategy
# Deploys new version alongside existing, then switches traffic

set -e

ENVIRONMENT=$1
VERSION=$2

if [ -z "$ENVIRONMENT" ] || [ -z "$VERSION" ]; then
    echo "Usage: $0 <environment> <version>"
    exit 1
fi

echo "Starting blue-green deployment for $ENVIRONMENT (version $VERSION)"

# 1. Deploy green environment (new version)
echo "Deploying green environment..."
kubectl apply -f k8s/base/validators/statefulset.yaml \
    --namespace=besu-network \
    --set="image.tag=$VERSION" \
    --set="deployment.color=green"

# 2. Wait for green to be ready
echo "Waiting for green deployment to be ready..."
kubectl wait --for=condition=ready pod \
    -l app=besu-validator,color=green \
    -n besu-network \
    --timeout=600s

# 3. Run health checks on green
echo "Running health checks on green deployment..."
./scripts/health-check.sh green

# 4. Switch traffic to green
echo "Switching traffic to green..."
kubectl patch service besu-validator -n besu-network \
    -p '{"spec":{"selector":{"color":"green"}}}'

# 5. Wait for traffic to stabilize
echo "Waiting for traffic to stabilize..."
sleep 30

# 6. Scale down blue (old version)
echo "Scaling down blue deployment..."
kubectl scale statefulset besu-validator-blue \
    --replicas=0 \
    -n besu-network

echo "Blue-green deployment completed successfully!"

