#!/bin/bash
# Canary Deployment Strategy
# Gradually rolls out new version to a subset of traffic

set -e

ENVIRONMENT=$1
VERSION=$2
PERCENTAGE=${3:-10}  # Default 10% traffic

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

echo "Starting canary deployment for $ENVIRONMENT (version $VERSION, $PERCENTAGE% traffic)"

# 1. Deploy canary version
echo "Deploying canary version..."
kubectl apply -f k8s/base/validators/statefulset.yaml \
    --namespace=besu-network \
    --set="image.tag=$VERSION" \
    --set="deployment.type=canary" \
    --set="replicas=1"

# 2. Configure traffic splitting (using Istio VirtualService)
cat <<EOF | kubectl apply -f -
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: besu-validator
  namespace: besu-network
spec:
  hosts:
  - besu-validator
  http:
  - match:
    - headers:
        canary:
          exact: "true"
    route:
    - destination:
        host: besu-validator
        subset: canary
      weight: $PERCENTAGE
  - route:
    - destination:
        host: besu-validator
        subset: stable
      weight: $((100 - PERCENTAGE))
EOF

# 3. Monitor canary metrics
echo "Monitoring canary deployment..."
./scripts/monitor-canary.sh $ENVIRONMENT

# 4. Gradually increase canary traffic
for percentage in 25 50 75 100; do
    echo "Increasing canary traffic to $percentage%..."
    
    # Update VirtualService with new weights
    kubectl patch virtualservice besu-validator -n besu-network \
        --type=merge -p "{\"spec\":{\"http\":[{\"route\":[{\"destination\":{\"subset\":\"canary\"},\"weight\":$percentage},{\"destination\":{\"subset\":\"stable\"},\"weight\":$((100 - percentage))}]}]}}"
    
    # Wait and monitor
    sleep 300  # 5 minutes per stage
    
    # Check error rates
    ERROR_RATE=$(./scripts/get-error-rate.sh canary)
    if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then
        echo "Error rate too high ($ERROR_RATE), rolling back..."
        kubectl scale statefulset besu-validator-canary --replicas=0 -n besu-network
        exit 1
    fi
done

# 5. Promote canary to stable
echo "Promoting canary to stable..."
kubectl patch statefulset besu-validator-stable -n besu-network \
    --type=merge -p "{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"besu\",\"image\":\"hyperledger/besu:$VERSION\"}]}}}}"

# 6. Remove canary
echo "Removing canary deployment..."
kubectl delete statefulset besu-validator-canary -n besu-network

echo "Canary deployment completed successfully!"

