#!/bin/bash

# Step 1: Identify the exact standalone instance
INSTANCE_NAME=$(gcloud compute instances list --filter="name=('cstv-prod')" --format="value(name)")
INSTANCE_ZONE=$(gcloud compute instances list --filter="name=('cstv-prod')" --format="value(zone)")

if [ -z "$INSTANCE_NAME" ] || [ -z "$INSTANCE_ZONE" ]; then
    echo "Error: No instance named 'cstv-prod' found."
    exit 1
fi

echo "Using instance: $INSTANCE_NAME in zone: $INSTANCE_ZONE"

# Step 2: Get the disk name
DISK_NAME=$(gcloud compute instances describe $INSTANCE_NAME --zone=$INSTANCE_ZONE --format="value(disks[0].source)" | awk -F'/' '{print $NF}')

# Step 3: Create a **RAW DISK IMAGE** instead of snapshot
IMAGE_NAME="cstv-prod-image-$(date +%Y%m%d-%H%M%S)"

echo "Creating full disk image: $IMAGE_NAME"
gcloud compute images create $IMAGE_NAME \
    --source-disk=$DISK_NAME \
    --source-disk-zone=$INSTANCE_ZONE \
    --force \
    --family="cstv-prod"

# Step 4: Create a new instance template with the full disk image
TEMPLATE_NAME="cstv-prod-template-$(date +%Y%m%d-%H%M%S)"

echo "Creating new instance template: $TEMPLATE_NAME"
gcloud compute instance-templates create $TEMPLATE_NAME \
    --machine-type=e2-standard-4 \
    --image=$IMAGE_NAME \
    --boot-disk-size=400GB \
    --boot-disk-type=pd-ssd \
    --tags=http-server,https-server

# Step 5: Handle Managed Instance Group (MIG)
MIG_NAME="cstv-prod-mig"
MIG_ZONE="northamerica-northeast2-c"

MIG_EXISTS=$(gcloud compute instance-groups managed list --filter="name=${MIG_NAME}" --format="value(name)")

if [ -z "$MIG_EXISTS" ]; then
    echo "Creating Managed Instance Group: $MIG_NAME"
    gcloud compute instance-groups managed create $MIG_NAME \
        --base-instance-name=cstv-prod-auto \
        --size=1 \
        --template=$TEMPLATE_NAME \
        --zone=$MIG_ZONE

    echo "Enabling auto-scaling for MIG: $MIG_NAME"
    gcloud compute instance-groups managed set-autoscaling $MIG_NAME \
        --zone=$MIG_ZONE \
        --min-num-replicas=1 \
        --max-num-replicas=5 \
        --target-cpu-utilization=0.6 \
        --cool-down-period=60
else
    echo "MIG exists. Rolling update with new template: $TEMPLATE_NAME"
    gcloud compute instance-groups managed rolling-action start-update $MIG_NAME \
        --version=template=$TEMPLATE_NAME \
        --zone=$MIG_ZONE
fi

# Step 6: Cleanup old instance templates (keep only the latest 3)
echo "Cleaning up old instance templates..."
OLD_TEMPLATES=$(gcloud compute instance-templates list --filter="name~'cstv-prod-template-'" --format="value(name)" | sort | head -n -3)

for TEMPLATE in $OLD_TEMPLATES; do
    echo "Deleting old template: $TEMPLATE"
    gcloud compute instance-templates delete $TEMPLATE --quiet
done

# Step 7: Cleanup old images (keep only the latest 3)
echo "Cleaning up old images..."
OLD_IMAGES=$(gcloud compute images list --filter="name~'cstv-prod-image-'" --sort-by="~creationTimestamp" --format="value(name)" | tail -n +4)

for IMAGE in $OLD_IMAGES; do
    echo "Deleting old image: $IMAGE"
    gcloud compute images delete $IMAGE --quiet
done

echo "Script execution completed successfully."
