#!/usr/bin/env bash
#
# blame(ken)
#
# this runs this project with Maven i.e. "mvn spring-boot:run" with appropriate environment, params, AWS credentials, etc...


set -e          # raise exception if error
set -u          # raise exception if unset
set -o pipefail # raise exceptions in pipes

BASENAME=$(basename $0)
WORKDIR=$(cd $(dirname $0);pwd -P;)
cd $WORKDIR

# secrets come from AWS Parameter Store, see mop-utils/mop_dev_scripts/dev-secrets
for f in aws-credentials config/application-development.properties; do
  [[ -f $f ]] || { echo "ERROR: $f is missing. Run ${MOP_SOURCE_ROOT:-\$MOP_SOURCE_ROOT}/mop-utils/mop_dev_scripts/dev-secrets/fetch-dev-secrets.sh $(basename $WORKDIR)" >&2; exit 1; }
done

unset   AWS_SECURITY_TOKEN \
        AWS_SESSION_TOKEN \
        AWS_ACCESS_KEY \
        AWS_SECRET_KEY \
        AWS_ACCESS_KEY_ID \
        AWS_SECRET_ACCESS_KEY \
        AWS_SHARED_CREDENTIALS_FILE \
        AWS_CREDENTIAL_PROFILES_FILE \
        AWS_CONFIG_FILE

# use existing value or assign default
: ${TMPDIR:=/tmp}
export  AWS_SHARED_CREDENTIALS_FILE=$WORKDIR/aws-credentials \
        SPRING_PROFILES_ACTIVE=development \
        TZ=etc/UTC \
        AWS_REGION=us-east-1 \
        TMPDIR \
        ANSIBLE_WORK_DIR=$WORKDIR/tools/ansible

export  AWS_PROFILE=${AWS_PROFILE:-default}

# Credentials come from ./aws-credentials. The SDK builds a profile by merging the
# credentials file with the config file, so a `login_session` key in ~/.aws/config's
# [default] profile makes it reject the merged default outright ("the 'signin' service
# module must be on the class path") and the valid static keys here go down with it.
# Reading config from /dev/null keeps that merge from happening; region is already set
# above, so nothing is lost by skipping the real config file.
#
# Set AWS_PROFILE to use ~/.aws/config instead — e.g. an SSO profile after
# `aws sso login --profile <name>`. That path additionally needs the awssdk `sso` and
# `ssooidc` artifacts on the classpath, which this project does not depend on today.
[[ "$AWS_PROFILE" == "default" ]] && export AWS_CONFIG_FILE=/dev/null

echo "INFO: using AWS_PROFILE=$AWS_PROFILE (config=${AWS_CONFIG_FILE:-~/.aws/config})" >&2

[[ $# -gt 0 ]] && {
        echo "WARN: Passing JVM options: $*" >&2
}
# Run with Maven and pass additional params through to the JVM
./mvnw spring-boot:run -Dspring-boot.run.arguments="$*"
