#!/bin/bash

# Usage: $0 [-r]
# -d: Remove all current ingress rules
# -o: Add rules for OpenVPN
# -r: Add rules for RDP
# -p: Add rules for ICMP (including ping)
# -s <SG name>: Use a different SG name. (Note that if the SG contains spaces, it needs to be quoted!

#
# Defaults
#
mySGname='Wouter is here'
remove=0
openvpn=0
rdp=0
icmp=0

#
# Extract command arguments
#
while getopts ":dpros:" opt; do
  case $opt in
    d)
      remove=1
      ;;
    o)
      openvpn=1
      ;;
    r)
      rdp=1
      ;;
    p)
      icmp=1
      ;;
    s)
      mySGname="$OPTARG"
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

#
# Here we go
#
myip=`curl -s http://whatismyip.akamai.com/`
regions="$(aws ec2 describe-regions --output text | awk '{print $3}')"

for region in $regions
do
  echo "Region: $region"

  sgs=$(aws ec2 describe-security-groups --region $region --filter "Name=group-name,Values=\"$mySGname\"" --query 'SecurityGroups[*].{Name:GroupId}' --output text)
  for sg in $sgs
  do
    echo "  SG: $sg"

    if [ "$remove" == "1" ]
    then
      # Figure out current rules && delete
      rules=$(aws ec2 describe-security-groups --region $region --filter "Name=group-id,Values=$sg" --query 'SecurityGroups[*].{Name:IpPermissions}[0].Name' )
      aws ec2 revoke-security-group-ingress --region $region --group-id $sg --ip-permissions "$rules"
    fi

    # Add a new rule for my IP, for SSH
    aws ec2 authorize-security-group-ingress --region $region --group-id $sg --protocol tcp --port 22 --cidr $myip/32

    if [ "$openvpn" == 1 ]
    then 
      # Add a new rule for my IP, for OpenVPN
      # Note that best practice is to use UDP port 1194 for OpenVPN. However, if firewall restrictions apply, you may want to change this to TCP port 443
      aws ec2 authorize-security-group-ingress --region $region --group-id $sg --protocol udp --port 1194 --cidr $myip/32
      #aws ec2 authorize-security-group-ingress --region $region --group-id $sg --protocol tcp --port 443 --cidr $myip/32
    fi

    if [ "$rdp" == 1 ]
    then 
      # Add a new rule for my IP, for OpenVPN
      aws ec2 authorize-security-group-ingress --region $region --group-id $sg --protocol tcp --port 3389 --cidr $myip/32
    fi

    if [ "$icmp" == 1 ]
    then 
      # Add a new rule for my IP, for ICMP
      aws ec2 authorize-security-group-ingress --region $region --group-id $sg --protocol icmp --port -1 --cidr $myip/32
    fi


  done
done
