#!/usr/bin/env bash

set -euo pipefail

# Usage message
usage() {
  echo "Usage: $0 --instance-id <INSTANCE_ID>"
  exit 1
}

# Parse arguments
INSTANCE_ID=""
while [[ $# -gt 0 ]]; do
  case "$1" in
  --instance-id)
    INSTANCE_ID="$2"
    shift 2
    ;;
  *)
    echo "Unknown argument: $1"
    usage
    ;;
  esac
done

# Validate input
if [[ -z $INSTANCE_ID ]]; then
  echo "Error: --instance-id is required"
  usage
fi

# Describe security groups
SG_IDS=$(aws ec2 describe-instances \
  --instance-ids "$INSTANCE_ID" \
  --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' \
  --output text)

for sg_id in $SG_IDS; do
  echo "Security Group ID: $sg_id"
  aws ec2 describe-security-groups \
    --group-ids "$sg_id" \
    --query 'SecurityGroups[*].[GroupId,GroupName,IpPermissions,IpPermissionsEgress]' \
    --output json
  echo "-------------------------------------"
done
