#!/bin/bash

set -ex

UPDATED_TERRAFORMER_VERSION="$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d '"' -f 4)"
if [ "$CURRENT_TERRAFORMER_VERSION" != "$UPDATED_TERRAFORMER_VERSION" ]; then
    echo "WARNING: Newer terraformer version available";
fi;

# Checking if all the necessary environment variables are set
if [ "$PROVIDER" = "aws" ]
then
    test -n "$AWS_ACCESS_KEY_ID"
    test -n "$AWS_SECRET_ACCESS_KEY"
    test -n "$REGIONS"
    # Comment here: Normally, any AWS SDK is using primarily the environment variables.
    # Terraformer seems to insist on that credentials file, and we are writing it here
    # using the environment variables.
    echo -e "[default]\naws_access_key_id=$AWS_ACCESS_KEY_ID\naws_secret_access_key=$AWS_SECRET_ACCESS_KEY" > /home/terraformerUser/.aws/credentials
elif [ "$PROVIDER" = "gcp" ]
then
    test -n "$PROJECTS";
    test -n "$REGIONS";
    test -n "$CREDENTIALS";
    echo "$CREDENTIALS" > /opt/tmp/gcp_creds.json;
    GOOGLE_APPLICATION_CREDENTIALS=/opt/tmp/gcp_creds.json;
    export GOOGLE_APPLICATION_CREDENTIALS;
elif [ "$PROVIDER" = "azure" ]
then
    ARM_SUBSCRIPTION_ID=$(az account show | jq -r '.id');
    export ARM_SUBSCRIPTION_ID
else
    echo "No supported provider used: $PROVIDER";
    exit 1;
fi

# The import function is creating a folder for each resource, even when there is
# nothing to export on. This function cleans up the folders where there was nothing
# exported from
# The input parameters are
# - region: a specific region that is done being explored
cleanup () {
    region="$1";
    # shellcheck disable=SC2045
    for service in $(ls "$TERRAFORMER_EXPORT_DATA"/"$region"/"$PROVIDER"); do
        DELETE_IT="$TERRAFORMER_EXPORT_DATA"/"$region"/"$PROVIDER"/"$service"
        for tf_file in $(find "$TERRAFORMER_EXPORT_DATA"/"$region"/"$PROVIDER"/"$service" -type f \
                              -not -iname "provider.tf" -and -not -iname "variables.tf" \
                              -and -not -iname "terraform.tfstate" -print0 | \
                             xargs -0 dirname | sort | uniq); do
            if [ "$TERRAFORMER_EXPORT_DATA"/"$region"/"$PROVIDER"/"$service" = "$tf_file" ]
            then
                DELETE_IT="";
            fi
        done;
        if [ -n "$DELETE_IT" ]
        then
            rm -rf "$DELETE_IT";
        fi
    done;
}

# In the case where the export data was already there, we should empty its contents
rm -rf "${TERRAFORMER_EXPORT_DATA:-?}"/*
cp /opt/tmp/versions.tf "$TERRAFORMER_EXPORT_DATA"
terraform init
for region in ${REGIONS//,/ }; do
    if [ "$PROVIDER" = "aws" ]
    then
        terraformer import "$PROVIDER" --resources=* --regions="$region";
    elif [ "$PROVIDER" = "gcp" ]
    then
        terraformer import google --resources=* --regions="$region" --projects="$PROJECTS";
    elif [ "$PROVIDER" = "azure" ]
    then
        terraformer import azure -r "$(az group list | jq -r 'map(.name) | join(",")')";
    fi
    mv generated "$region";
    cleanup "$region";
done
