#! /bin/bash
# Gets the current dlm policies, if any.
#
# WARNING: THIS IS RUN DURRING A 'PLAN' STEP. Do not make changes. Read-only in this script.
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
elif [[ ${REGION} == "us-gov-west-1" ]]; then
  PROFILE=${ACCOUNT_NAME}-gov
elif [[ ${REGION} == "us-east-1" ]]; then
  PROFILE=${ACCOUNT_NAME}
elif [[ ${REGION} == "us-west-1" ]]; then
  PROFILE=${ACCOUNT_NAME}
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-}

POLICIES=$(aws --profile ${PROFILE} --region ${REGION} dlm get-lifecycle-policies)

# Extracts the policy IDs of IMAGE_MANAGEMENT policye
POLICY_IDS=$(echo $POLICIES | jq -r '[.Policies[] | select(.PolicyType=="IMAGE_MANAGEMENT") | select(.Tags.SnapshotPolicy=="Daily")] | first | .PolicyId')

# jq ensures a safe json output
# Will return 'null' if no matching policy
jq -n --arg policy $POLICY_IDS '{ "PolicyId": $policy }'
