#! /bin/bash
#
# Creates the XDR DLM Policy to backup AMIs daily and copy them cross-region.
#
# NOTE: If you create a new policy, the old policy will remain. Use the modify
# script instead. And even if you delete the old policy, the images created by
# it will remain and continue to incur charges.
set -euo pipefail

PARTITION=$1
REGION=$2
ACCOUNT=$3
ACCOUNT_NAME=$4

# Fix for some accounts having -gov already appended and some not.
# Accounts in gov will get it appended.
ACCOUNT_NAME=${ACCOUNT_NAME%%-gov}

if [[ ${REGION} == "us-gov-east-1" ]]; then
  PROFILE=${ACCOUNT_NAME}-gov
  TARGET_REGION="us-gov-west-1"
elif [[ ${REGION} == "us-gov-west-1" ]]; then
  PROFILE=${ACCOUNT_NAME}-gov
  TARGET_REGION="us-gov-east-1"
elif [[ ${REGION} == "us-east-1" ]]; then
  PROFILE=${ACCOUNT_NAME}
  TARGET_REGION="us-west-1"
elif [[ ${REGION} == "us-west-1" ]]; then
  PROFILE=${ACCOUNT_NAME}
  TARGET_REGION="us-east-1"
else
  >&2 echo ERROR: Could not determine target region from source region \"${REGION}\"
  exit -1
fi

# Fix the accounts that we foolish prepended 'afs-' to.
PROFILE=${PROFILE##afs-}

# Find the target region key ARN, since we can't use aliases here
KMS_KEY_ID=$(aws --profile ${PROFILE} --region ${TARGET_REGION} kms list-aliases | jq -r '.Aliases[] | select(.AliasName=="alias/ami_backup_key") | .TargetKeyId')
KMS_ARN=$(aws --profile ${PROFILE} --region ${TARGET_REGION} kms describe-key --key-id ${KMS_KEY_ID} | jq -r '.KeyMetadata.Arn')

tmpfile=$(mktemp /tmp/create_dlm_policy.XXXXXXX)
cat > ${tmpfile} <<EOF
{
    "PolicyType": "IMAGE_MANAGEMENT",
    "ResourceTypes": [
        "INSTANCE"
    ],
    "TargetTags": [
        {
            "Key": "Snapshot",
            "Value": "Daily"
        }
    ],
    "Schedules": [
        {
            "Name": "XDR AMI Backups with Cross Region Replication",
            "CopyTags": true,
            "TagsToAdd": [
                {
                    "Key": "SnapshotPolicy",
                    "Value": "Daily"
                },
                {
                    "Key": "SnapshotCreator",
                    "Value": "XDR AMI Backups with Cross Region Replication"
                }
            ],
            "VariableTags": [
                {
                    "Key": "instance-id",
                    "Value": "\$(instance-id)"
                }
            ],
            "CreateRule": {
                "Interval": 24,
                "IntervalUnit": "HOURS",
                "Times": [
                    "03:30"
                ]
            },
            "RetainRule": {
                "Count": 2
            },
            "CrossRegionCopyRules": [
                {
                    "TargetRegion": "${TARGET_REGION}",
                    "Encrypted": true,
                    "CmkArn": "${KMS_ARN}",
                    "CopyTags": true,
                    "RetainRule": {
                        "Interval": 2,
                        "IntervalUnit": "DAYS"
                    }
                }
            ]
        }
    ],
    "Parameters": {
        "NoReboot": true
    }
}
EOF

aws --profile ${PROFILE} --region ${REGION} dlm create-lifecycle-policy \
  --execution-role-arn arn:${PARTITION}:iam::${ACCOUNT}:role/dlm-lifecycle-role \
  --description "XDR AMI Backups with Cross Region Replication" \
  --state ENABLED \
  --tags '{ "Name": "XDR-AMI-XRegion", "SnapshotPolicy": "Daily" }' \
  --policy-details file://${tmpfile}

rm $tmpfile
