#!/bin/bash
if [ $ENVIRONMENT == "production" -o $ENVIRONMENT == "staging" ]; then
	echo "Environment: $ENVIRONMENT is not allowed..."
    exit 1
fi
echo "Creating AWS Secrets Manager Secrets for environment '$ENVIRONMENT'..."
echo "Getting all Parameters from SSM"
databaseurl=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/DATABASE_URI"       | sed -E "s@(\?ssl)@p81-$ENVIRONMENT\1@")
mongodburl=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_DB_URL"       | sed -E "s@(\?ssl)@activitylog-$ENVIRONMENT\1@") 
mongodbsaferxurl=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_DB_SAFERX_BE" | sed -E "s@(\?ssl)@saferx-backend-$ENVIRONMENT\1@")
mongopasswordsaferxbe=$(aws ssm get-parameter  --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_PASSWORD_SAFERX_BE")
mongojarvis="EMPTY_FOR_NOW" #$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_JARVIS"       | sed -E "s@(\?ssl)@jarvis-$ENVIRONMENT\1@")
mongosdpc=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_SDPC"       | sed -E "s@(\?ssl)@sdpc-$ENVIRONMENT\1@")
mongo_db_legacy=$(aws ssm get-parameter  --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_DB_SAFERX_BE")
mongo_db_svpn=$(aws ssm get-parameter  --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/devops-qa/common/MONGO_DB_SAFERX_BE")
vaulttoken=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/VAULT_TOKEN")
vaultp0token=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id global/cicd --query 'SecretString' --output text | jq -r '.VAULT_P81ZERO_TOKEN')
mysqldsn=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/MYSQL_DSN")
messagebrokerhost=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/MESSAGE_BROKER_HOST")
consulencryptionkey=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/CONSUL_ENCRYPTION_KEY")
active_session_db_uri=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/DATABASE_URI")
snowflake_prv_key=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id global/cicd --query 'SecretString' --output text | jq -r '.SNOWFLAKE_TF_PRV_KEY')
do_token=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id global/core_env_tokens --query 'SecretString' --output text | jq -r ".$ENVIRONMENT")
mysql_radius_password=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id mysql/radius/pasword --query 'SecretString' --output text)
redis_url=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/REDIS_URL")
redis_sxdns_url=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/sxdns/REDIS_URL" | sed 's/redis:\/\///')
infraP0ca_cert_enc=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id global/certificates --query 'SecretString' --output text | jq -r '.VAULT_INFRAP0_CA' | base64)
infraP0_cert_enc=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id global/certificates --query 'SecretString' --output text | jq -r '.VAULT_INFRAP0_CERT' | base64)
infraP0_key_enc=$(aws secretsmanager get-secret-value --region $AWS_SECRET_REGION --secret-id global/keys --query 'SecretString' --output text | jq -r '.VAULT_INFRAP0_KEY' | base64)

#tcpcacert=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/TCP_CA_CERT")
#tcpservercert=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/TCP_SERVER_CERT")
#tcpserverkey=$(aws ssm get-parameter --with-decryption --region $AWS_REGION --query "Parameter.{Name:Value}" --output text --name "/$ENVIRONMENT/common/TCP_SERVER_KEY")
echo "Creating sx-dns secrets"
echo "Creating NS_TSIG key"
if [ "${env_prefix}" == "qa" ]; then
  dnssec-keygen -a HMAC-MD5 -b 128 -n HOST pzero.p81-${ENV}.com.
  sx_dns_ns_tsig=$(cat Kpzero.p81-${ENV}.com.*.key | awk '{print $7}')
else
  dnssec-keygen -a HMAC-MD5 -b 128 -n HOST pzero.perimeter81-${ENV}.com.
  sx_dns_ns_tsig=$(cat Kpzero.perimeter81-${ENV}.com.*.key | awk '{print $7}')
fi
echo "Creating Vault parameters"
sx_vault={"url":"https://vault1.p81zero.int.safersoftware.net:8200","token":"$vaultp0token","ca_file":"/app/ssl/ca.crt","cert_file":"/app/ssl/public.crt","cert_key_file":"/app/ssl/private.key"}
echo "Retrieving certs"

echo "Done getting all params..."

engine="$ENVIRONMENT"
tags='[{"Key": "folder", "Value": "'"$engine"'"}]'
keys=("common" "saferx-backend" "radius-api" "lambdas")

# Create the JSON-formatted secret string for common
common_secret_json='{
  "DATABASE_URI": "'$databaseurl'",
  "MONGO_DB_URL": "'$mongodburl'",
  "MONGO_DB_SAFERX_BE": "'$mongodbsaferxurl'",
  "MONGO_PASSWORD_SAFERX_BE": "'$mongopasswordsaferxbe'",
  "MONGO_JARVIS": "EMPTY_FOR_NOW",
  "MONGO_SDPC": "'$mongosdpc'",
  "VAULT_TOKEN": "'$vaulttoken'",
  "MYSQL_DSN": "'$mysqldsn'",
  "MESSAGE_BROKER_HOST": "'$messagebrokerhost'",
  "REDIS_URL": "'$redis_url'"
}'
# Create the JSON-formatted secret string for saferx-backend
saferx_backend_secret_json='{
  "SX_VAULT_TOKEN": "'$vaulttoken'",
  "SX_CONSUL_P0_ENCRYPTION_KEY": "'$consulencryptionkey'",
  "SX_LOKI_PUSH_URL": "",
  "SX_PSK": ""
}'
# Create the JSON-formatted secret string for radius-api
radius_api_secret_json='{
  "MONGO_DB_LEGACY": "'$mongo_db_legacy'",
  "MONGO_DB_SVPN": "'$mongo_db_svpn'",
  "MYSQL_RADIUS_PASSWORD": "'$mysql_radius_password'"
}'
# Create the JSON-formatted secret string for lambdas
lambdas_secret_json='{
  "active_session_db_uri": "'$active_session_db_uri'",
  "snowflake_prv_key": "'$snowflake_prv_key'"
}'
# Create the JSON-formatted secret string for sx-core-dns-private
# sx_core_dns_secret_json='{
#   "SX_NS_TSIG": "'$sx_dns_ns_tsig'",
#   "SX_VAULT": "'$sx_vault'",
#   "SX_REDIS_ADDRESS": "'$redis_sxdns_url'",
#   "SX_PUBLIC_CRT": "'$infraP0_cert_enc'",
#   "SX_PRIVATE_KEY": "'$infraP0_key_enc'",
#   "SX_CA_CERT": "'$infraP0ca_cert_enc'"
# }'

echo "Insert secret strings to AWS Secrets Manager..."

for key in "${keys[@]}"; do
    echo $key
    if [ "$key" != "common" ]; then
        # Check secret exist
        aws secretsmanager describe-secret --region "$AWS_SECRET_REGION" --secret-id "env/$engine/$key" > /dev/null 2>&1
        if [ $? -eq 0 ]; then
        # Secret exists, so update it
        aws secretsmanager update-secret \
            --kms-key-id "$KMS_KEY_ID" \
            --region "$AWS_SECRET_REGION" \
            --secret-id "env/$engine/$key" \
            --secret-string "$(eval echo \$${key//-/_}_secret_json)" \
            --description "$description"  > /dev/null
        else
        # Secret doesn't exist, so create it
        aws secretsmanager create-secret \
            --kms-key-id "$KMS_KEY_ID" \
            --region "$AWS_SECRET_REGION" \
            --name "env/$engine/$key" \
            --description "$description" \
            --secret-string "$(eval echo \$${key//-/_}_secret_json)" \
            --tags "$tags"  > /dev/null
        fi
    else
        aws secretsmanager describe-secret --region "$AWS_SECRET_REGION" --secret-id "env/$engine" > /dev/null 2>&1
        if [ $? -eq 0 ]; then
        # Secret exists, so update it
        aws secretsmanager update-secret \
            --kms-key-id "$KMS_KEY_ID"\
            --region "$AWS_SECRET_REGION" \
            --secret-id "env/$engine" \
            --secret-string "$(eval echo \$${key//-/_}_secret_json)" \
            --description "$description"   > /dev/null
        else
        # Secret doesn't exist, so create it
        aws secretsmanager create-secret \
            --kms-key-id "$KMS_KEY_ID" \
            --region "$AWS_SECRET_REGION" \
            --name "env/$engine" \
            --description "$description" \
            --secret-string "$(eval echo \$${key//-/_}_secret_json)" \
            --tags "$tags"  > /dev/null
        fi
    fi
done

echo "Inserting DO token to SSM"
aws ssm put-parameter --name "/$ENVIRONMENT/common/DIGITAL_OCEAN_API_TOKEN" --value "$do_token" --key-id "$KMS_KEY_ID" --type "SecureString" --tier "Advanced" --overwrite