#!/bin/bash

# Ensure AWS CLI is available (needed for new Auto Scaling instances that don't have it yet)
if ! command -v aws &> /dev/null; then
  echo "AWS CLI not found — installing..."
  cd /tmp
  curl -s "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
  unzip -q -o awscliv2.zip
  sudo ./aws/install
fi

TG_ARN="arn:aws:elasticloadbalancing:ap-southeast-1:135808914208:targetgroup/Connector-TG/3ccc502af478c20e"
REGION="ap-southeast-1"
MAX_WAIT=1000
waited=0

while true; do
  HEALTHY_COUNT=$(aws elbv2 describe-target-health \
    --target-group-arn "$TG_ARN" \
    --region "$REGION" \
    --query "length(TargetHealthDescriptions[?TargetHealth.State=='healthy'])" \
    --output text)

  if [ "$HEALTHY_COUNT" -ge 2 ]; then
    echo "$HEALTHY_COUNT servers currently healthy — safe to take this one out of rotation."
    break
  fi

  if [ $waited -ge $MAX_WAIT ]; then
    echo "Waited 16.7 minutes, still only $HEALTHY_COUNT healthy server(s). Proceeding anyway to avoid a stuck deployment."
    break
  fi

  echo "Only $HEALTHY_COUNT healthy server(s) right now — waiting so we don't take down the last one..."
  sleep 15
  waited=$((waited + 15))
done
