#! /bin/bash -e
#-----
# Pre-reqs: AWSCLI tool (python, pip) installed and configured. -DC 28.1.15
# v1.1: Added parameter/value checks. -DC 23.2.15
#-----
StackName=$1
Profile=$3
Creds=$HOME/.aws/credentials

[ $# -lt 3 ] && (echo "Usage: $0 <stack-name> {on|off} <profile>"; exit 1)

[ $(grep -ce "\[${Profile:-null}\]" ${Creds}) -eq 0 ] && (echo 'Profile not found. Available profiles are:'; grep "\[" ${Creds}; echo "Usage: $0 <stack-name> {on|off} <profile>"; exit 1)

function listacks
{
 echo Profile ${Profile} found!
 aws cloudformation list-stacks --profile ${Profile} --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE UPDATE_ROLLBACK_COMPLETE|grep StackName|awk -F'[:",]' '{print $5}'
}

[ $(listacks | grep -ce ${StackName:-null}) -eq 0 ] && (echo -e "Stack: ${StackName:-null} does NOT exist! Use any of the following stacks:" ; listacks; exit 1)

case $2 in

on|ON)
  aws cloudformation set-stack-policy --profile ${Profile} --stack-name ${StackName} --stack-policy-body '{
  "Statement" : [
    {
      "Effect" : "Allow",
      "Action" : "Update:Modify",
      "Principal": "*",
      "Resource" : "*",
        "Condition" : {
          "StringEquals" : {
            "ResourceType" : ["AWS::IAM::User","AWS::IAM::AccessKey","AWS::S3::BucketPolicy","AWS::EC2::EIPAssociation","AWS::EC2::Route","AWS::EC2::Instance","AWS::EC2::Volume","AWS::EC2::SecurityGroupIngress","AWS::EC2::SecurityGroup"]
          }
       }
    }
  ]
}'
;;

off|OFF)
  aws cloudformation set-stack-policy --profile ${Profile} --stack-name ${StackName} --stack-policy-body '{
  "Statement" : [
    {
      "Effect" : "Allow",
      "Action" : "Update:*",
      "Principal": "*",
      "Resource" : "*",
        "Condition" : {
          "StringEquals" : {
            "ResourceType" : ["AWS::IAM::User","AWS::IAM::AccessKey","AWS::S3::BucketPolicy","AWS::EC2::EIPAssociation","AWS::EC2::Route","AWS::EC2::Instance","AWS::EC2::Volume","AWS::EC2::SecurityGroupIngress","AWS::EC2::SecurityGroup"]
          }
       }
    }
  ]
}'
;;

*)
  echo "Usage: $0 <stack-name> {on|off} <profile>"
  exit 1

esac