#!/bin/bash

source_check()
{
  # We need to try and check if we're sourced, 
  # so that we can stop ourselves if we're not.
  # Unfortunately we can only really do this in Bash-like shells, not a standard posix shell.
    # $BASH not null && func source is not external
  if  [ ! -z $BASH ] && [ ${FUNCNAME[1]} != "source" ];
  then
        echo "
docker-env:
"
        usage
        init_env
        echo "
=== Please source me as above next time; Have a good day!
  "
        exit 1;
  else
    echo "
docker-env:
"
  fi
  return 0
}

#1. Let the user know what we're working with
init_env()
{
# Clobber the existing APP_* info so we can be sure we don't 
# end up in a weird state with mismatched values
unset APP_AWS_ACCESS_KEY_ID APP_AWS_SECRET_ACCESS_KEY APP_AWS_SESSION_TOKEN

# Let the runner know what the current configuration for the run looks like
echo "
=== Config Status & Priority Order:
    Using AWS_PROFILE         : ${AWS_PROFILE:-False}
    Using AWS_ACCESS_KEY_ID   : $(if [ -n "$AWS_ACCESS_KEY_ID" -a -z "$AWS_PROFILE" ]; then echo 'True'; else echo 'False'; fi; )
    Using AWS CLI Default key : $(if [ -z "$AWS_ACCESS_KEY_ID" -a -z "$AWS_PROFILE" ]; then echo 'True'; else echo 'False'; fi; )
"
}

# Generic error handler
handle_result()
{
# If the most recent exit code isn't 0, something threw an error.
if [ $? -ne 0 ]; then
  echo "
=== An error was encountered while attempting to fetch credentials:

  -----
  ${APP_AWS_ACCESS_KEY_ID:-(Access key could not be determined. Is AWS CLI configured?)}
  -----"
  # Unset all of the vars ( which now contain error messaging )
  # so that our final check fails and exits instead.
  unset APP_AWS_ACCESS_KEY_ID APP_AWS_SECRET_ACCESS_KEY APP_AWS_SESSION_TOKEN
  return 1
else 
  echo "
=== Success!"
  return 0
fi
}

usage(){
echo "
=== Usage: 
    
    Profile AWS Credentials: 
      AWS_PROFILE=twitch-admin-panel-dev/admin . "$0"

    Default AWS Credentials: 
      . "$0"

    Environment Credentials: 
      AWS_ACCESS_KEY_ID=ASIAGOL2WVIOHLATTE AWS_SECRET_ACCESS_KEY=ayylmao . "$0""
}

fetch_from_default()
{
  # if ENV AccessKeyID is null, and ENV Profile is null, get the default key
  if [ -z "$AWS_ACCESS_KEY_ID" -a -z "$AWS_PROFILE" ]
  then
    echo "
=== AWS_ACCESS_KEY_ID & AWS_PROFILE not set: 
    Fetching key for DEFAULT profile via AWS CLI"
    APP_AWS_ACCESS_KEY_ID="$(aws configure get aws_access_key_id 2>&1 | tail -n 1)"
    APP_AWS_SECRET_ACCESS_KEY="$(aws configure get aws_secret_access_key 2>&1)"
    handle_result
  fi
}

fetch_from_env()
{
  # if ENV AccessKeyID env is not empty, and ENV Profile isn't set, 
  # use that Key and Secret instead of using the AWS CLI to figure out.
  if [ -n "$AWS_ACCESS_KEY_ID" -a -z "$AWS_PROFILE" ]
  then
    echo "
=== AWS_ACCESS_KEY_ID set via env vars: 
    Utilizing"
    APP_AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID"
    APP_AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY"
    if [ -n "$AWS_SESSION_TOKEN" ]
    then
      APP_AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN"
    fi
  fi
}

fetch_from_profile()
{
  # if profile is not empty, use the aws cli to fetch its details
  if [ -n "$AWS_PROFILE" ]
  then
    echo "
=== AWS_PROFILE set: 
    Fetching key for profile $AWS_PROFILE via AWS CLI"
    unset APP_AWS_ACCESS_KEY_ID
    unset APP_AWS_SECRET_ACCESS_KEY

    APP_AWS_ACCESS_KEY_ID="$(aws configure get aws_access_key_id 2>&1 | tail -n 1)"
    APP_AWS_SECRET_ACCESS_KEY="$(aws configure get aws_secret_access_key 2>&1)"
    APP_AWS_SESSION_TOKEN="$(aws configure get aws_session_token 2>&1)"
    handle_result
  fi
}

cleanup_and_die()
{
  if [ -z "$APP_AWS_SESSION_TOKEN" ]
  then
    unset APP_AWS_SESSION_TOKEN
  fi

  if [ -z "$APP_AWS_ACCESS_KEY_ID" -o -z "$APP_AWS_SECRET_ACCESS_KEY" ]
  then
    unset APP_AWS_ACCESS_KEY_ID
    unset APP_AWS_SECRET_ACCESS_KEY
    unset APP_AWS_SESSION_TOKEN
    echo "
=== Access Key ID or Secret Access Key are unset; Aborting.
    Please consult the error message above for clues toward cause.
    I hope this helps!

"
    return 1
  fi
}

donezo()
{
  # If we don't have any errors, export all of our relevant vars
  if [ $? -eq 0 ]; then
    export APP_AWS_ACCESS_KEY_ID
    export APP_AWS_SECRET_ACCESS_KEY
    export APP_AWS_SESSION_TOKEN

    echo "
=== Exported APP_AWS_*; Finished! Have a good one!

"
    return 0
  else
    return 1
  fi
}

source_check
init_env
fetch_from_default
fetch_from_env
fetch_from_profile
cleanup_and_die
donezo
