#!/bin/bash

# Stop instances based on a label
LABEL="env=dev"

echo "Searching for instances with label $LABEL..."

# Get list of instances (name and zone)
INSTANCES=$(gcloud compute instances list --filter="labels.$LABEL" --format="value(name,zone)")

if [ -z "$INSTANCES" ]; then
    echo "No instances found with label $LABEL"
    exit 0
fi

# Read line by line
echo "$INSTANCES" | while read NAME ZONE; do
    echo "Stopping instance: $NAME in $ZONE"
    gcloud compute instances stop "$NAME" --zone "$ZONE" --quiet
done

echo "Stop commands issued."
