#!/usr/bin/env bash

set -Eeo pipefail

echo "--- INSTALL JQ"
if command -v jq 2>/dev/null; then
  echo "jq is already installed."
else
  apt-get update -q && apt-get install -y -q jq
fi

echo "--- :aws-cli:INSTALL AWS CLI v2"
if command -v aws 2>/dev/null; then
  echo "aws-cli is already installed."
else
  curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
  unzip -qq awscliv2.zip
  ./aws/install
  aws --version
fi

echo "--- INSTALL AWSudo"
if command -v awsudo 2>/dev/null; then
  echo "AWSudo is already installed."
else
  npm install -g awsudo --quiet
fi

echo "--- Retrieve parameters using AWSudo"
# Retrieving Parameter Variables that starts with the path "/$ENVIRONMENT/", for example: "/staging/"
# AWSudo will allow us to assume an IAM Role from another AWS account, and run the aws-ssm-env-linux command
# with those permissions. We will dump the output to a file, as we need to do some sanitization in some parameters:
if [ ! -z $1 ]
then
    REPONAME=$1
else
    REPONAME=bt-member-site
fi

FILENAME="${REPONAME}-${BUILDKITE_BUILD_NUMBER}.txt"

AWS_PARAMETERS=$(awsudo ${OLD_NA_ROLE} aws ssm get-parameters-by-path \
    --path "/${ENVIRONMENT}/" \
    --region ${CLUSTER_AWS_REGION} \
    --recursive \
    --with-decryption \
    --output json \
    --query "Parameters[*].{Name:Name,Value:Value}")

# Iterate through all the variables retrieved in the previous step
# We need to use the @base64 to encode the parameters due to parameters with spaces and multiple lines
for param in $(echo -E "${AWS_PARAMETERS}" | jq -r -c ".[] | @base64"); do
    # Sanitize the parameters:
    # - param name: Decode the name (with 'base64 --decode' command, remove the path from the
    #     beginning of the name, substitute '/' for '_' and make the name all Uppercase)
    # - param value: Decode the name (with 'base64 --decode' command) and add double quotes to it
    param_name=$(echo -E "${param}" | base64 --decode | jq -r -c ".Name")
    sanitized_name=$(echo -E "${param_name}" \
      | sed "s/\(\/$ENVIRONMENT\/*\)\(.*\)/\2/" \
      | sed "s/\//_/g" \
      | tr a-z A-Z)
    sanitized_value=$(echo -E "${param}" | base64 --decode | jq -r -c ".Value")

    # Push the pair 'PARAMETER_NAME=VALUE' to a temp text file
    echo -E ${sanitized_name}="\"${sanitized_value}\"" >> $FILENAME
done

# Retrieving Parameter Variables that starts with the path "/test/" (similar to the above)
AWS_PARAMETERS=$(awsudo ${OLD_NA_ROLE} aws ssm get-parameters-by-path \
    --path "/test/" \
    --region ${CLUSTER_AWS_REGION} \
    --recursive \
    --with-decryption \
    --output json \
    --query "Parameters[*].{Name:Name,Value:Value}")

for param in $(echo -E "${AWS_PARAMETERS}" | jq -r -c ".[] | @base64"); do
    param_name=$(echo -E "${param}" | base64 --decode | jq -r -c ".Name")
    sanitized_name=$(echo -E "${param_name}" \
      | sed "s/\(\/test\/*\)\(.*\)/\2/" \
      | sed "s/\//_/g" \
      | tr a-z A-Z)
    sanitized_value=$(echo -E "${param}" | base64 --decode | jq -r -c ".Value")

    echo -E ${sanitized_name}="\"${sanitized_value}\"" >> $FILENAME
done

# Remove Variables with `-` in the name
sed -i '/-.*=/d' $FILENAME

# Sanitize Variable value of JWT_SECRET: escape ` and !
sed -i 's/\(JWT_SECRET.*NE\)\(.*\)/\1\\\2/' $FILENAME
# This might be needed in some versions of bash
# sed -i 's/\(JWT_SECRET.*Zr\)\(.*\)/\1\\\2/' $FILENAME

echo "--- Uploading file to S3 bucket"
aws s3 cp $FILENAME s3://bt-buildkite-secrets/pipeline-secrets/

echo "✅"