#! /bin/bash
#
# iamhere(1) 
#
# by erik@easytocloud.com configure bastion-host security group for travelling users
#
# Usage:
# 	iamhere [-c]
#
# Description
# 	Opens ports listed in $PORTS for securitygroup name in $MYSG
# Options
# 	-c clean/close all (inboud) ports
#
# Attach the SecurityGroup to your bastion host
# When arriving at a new location run 'iamhere'
# When leaving run 'iamhere -c'
#
# Before running iamhere, make sure your aws config is correct
# you might want to set your AWS_DEFAULT_PROFILE env var
# using awsprofile(1)
#

## CONFIG

MYSG=ErikIsHere  				# your security group name
PORTS="udp:500 udp:4500 tcp:4500 tcp:22"	# the ports to open/close

## END CONFIG

SG=$(aws ec2 describe-security-groups --query 'SecurityGroups[?GroupName==`'$MYSG'`].GroupId' --output text)
OLDIP=$(aws ec2 describe-security-groups --query 'SecurityGroups[?GroupName==`'$MYSG'`].IpPermissions[0].IpRanges[0].CidrIp' --output text)

# Are there old ip addresses to remove?

if test -n "$OLDIP"
then
  doclean=true
else
  doclean=false
fi

# Do we need to whitelist a new range?

if test "$1" = "-c" # only cleanup?
then
  makenew=false
else
  makenew=true
fi

# If we need to make new whitelist, what IP address to use

if $makenew 
then
  NEWIP="$(dig +short myip.opendns.com @resolver1.opendns.com)"

  if [ "$OLDIP" = "${NEWIP}/32" ]
  then
    echo 'Nothing changed'
    exit 1
  fi
fi

! $makenew && ! $doclean && echo 'No change required' && exit 1

for P in ${PORTS}
do
  port=${P#*:}
  prot=${P%:*}

  $doclean && aws ec2 revoke-security-group-ingress --group-id ${SG} --protocol ${prot} --port ${port} --cidr ${OLDIP}
  $makenew && aws ec2 authorize-security-group-ingress --group-id ${SG} --protocol ${prot} --port ${port} --cidr ${NEWIP}/32
done
