#!/bin/env zx


const regions = JSON.parse(await $`aws ec2 describe-regions`).Regions.map(r => r.RegionName).filter(r => r.startsWith("us-") || r.startsWith("eu-"));

for (const region of regions) {
    let instances = JSON.parse(await $`aws ec2 describe-instances --filters Name=instance-state-name,Values=running --region ${region}`).Reservations.flatMap(r => r.Instances);

    for (const instance of instances) {
        console.log("Instance ID:", instance.InstanceId, "in region", region);

        // Check if instance already has an alarm
        const existingAlarms = JSON.parse(await $`aws cloudwatch describe-alarms-for-metric --metric-name "CPUUtilization" --namespace "AWS/EC2" --dimensions Name=InstanceId,Value=${instance.InstanceId} --region ${region}`);
        if (existingAlarms.MetricAlarms.length > 0) {
            console.log(`Instance ${instance.InstanceId} already has an alarm in region ${region}. Skipping...`);
            continue;
        }

        const instanceId = instance.InstanceId;
        const alarmName = `AutoShutdown-${instanceId}`;
        const alarmDescription = `Alarm on instance ${instanceId}: Triggered when CPUUtilization <= 3 for 1 consecutive 1-minute period.`;
        const alarmActions = ["arn:aws:automate:" + region + ":ec2:terminate"];

        await $`aws cloudwatch put-metric-alarm --alarm-actions ${alarmActions.join(" ")} --alarm-description ${alarmDescription} --alarm-name ${alarmName} --comparison-operator "LessThanOrEqualToThreshold" --dimensions Name=InstanceId,Value=${instanceId} --evaluation-periods 1 --metric-name "CPUUtilization" --namespace "AWS/EC2" --period "60" --statistic "Average" --threshold 3 --region ${region}`;

        console.log(`Created alarm: ${alarmName} for instance ${instanceId} in region ${region}`);
    }
}