#!/usr/bin/env bash

set -o errexit          # Exit on most errors (see the manual)
set -o errtrace         # Make sure any error trap is inherited
set -o nounset          # Disallow expansion of unset variables
set -o pipefail         # Use last non-zero exit code in a pipeline
# set -o xtrace          # Trace the execution of the script (debug)

if [ "$AWS_PROFILE" = "" ]; then
  echo "No AWS_PROFILE set"
  exit 1
fi


function main() {
  for region in $(aws ec2 describe-regions --region us-east-1 | jq -r .Regions[].RegionName); 
  do
    printf "Region: %s\n" "${region}"

    vpc=$(aws ec2 --region ${region} describe-vpcs --filter Name=isDefault,Values=true | jq -r .Vpcs[0].VpcId)
    if [[ "${vpc}" = "null" ]];
    then
      echo "No default VPC"
      continue
    fi
    printf "Found default VPC: %s\n" "${vpc}"

    igw=$(aws ec2 --region ${region} describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} | jq -r .InternetGateways[0].InternetGatewayId)
    if [ "${igw}" != "null" ]; 
    then
      printf "Detaching IGW: %s\n" "${igw}"
      aws ec2 --region ${region} detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}

      printf "Deleting IGW: %s\n" "${igw}"
      aws ec2 --region ${region} delete-internet-gateway --internet-gateway-id ${igw}
    fi

    subnets=$(aws ec2 --region ${region} describe-subnets --filters Name=vpc-id,Values=${vpc} | jq -r .Subnets[].SubnetId)
    if [ "${subnets}" != "null" ]; 
    then
      for subnet in ${subnets}; do
        printf "Deleting subnet: %s\n" "${subnet}"
        aws ec2 --region ${region} delete-subnet --subnet-id ${subnet}
      done
    fi

    printf "Deleting VPC: %s\n" "${vpc}"
    aws ec2 --region ${region} delete-vpc --vpc-id ${vpc}
  done
}

main "$@"
