#!/bin/sh
#
# deploy.sh
#
# Uses the `exp` command to deploy the project to Expo.
#
# The following must be defined in `.env` or as environment
# variables in order for the script to run successfully:
#
#  Required:
#    * CI_BUILD - required to be true if the build is being deployed via continuous integration
#    * ENV - the environment to which to deploy (additional config in config.json)
#    * EXP_USERNAME - the username of the Expo account with which to deploy
#    * EXP_PASSWORD - the password of the Expo account with which to deploy
#    * OAUTH_CLIENT_ID - OAuth client id for the application
#    * OAUTH_CLIENT_SECRET - OAuth secret for the application
#    * FRONTEND_AUTH_BASE - the endpoint for `frontend-auth` for authentication
#    * API_BASE - the base Orchard API to use in order to make API calls
#
#  Optional (Sentry):
#    * SENTRY_APP_NAME
#    * SENTRY_PROJECT_NAME
#    * SENTRY_AUTH_TOKEN
#
dangerous_envs=("prod" "qa")

# Clean up `app.json` file if it exists
function removeAppJson {
    if [ -f app.json ]; then
        rm app.json
    fi
}

trap removeAppJson EXIT

if [ -f .env ]; then
    # If a `.env` file exists, `source` it to environment variables
    source .env
else
    # If no `.env` file exists, generate it from environment variables
    scripts/createDotEnv.js > env
    mv env .env
fi

if [ -z "$ENV" ]; then
    echo 'ENV not defined!'
    exit 1
fi

if [[ -z "$CI_BUILD" ]]; then
    for env in "${dangerous_envs[@]}"
    do
        if [ "$env" == "$ENV" ] ; then
            cat scripts/deployment-warning.txt
            read -r -p "Are you sure you want to deploy to $ENV? [y/N] " response
            case "$response" in
                [yY][eE][sS]|[yY])
                    ;;
                *)
                    exit 1
                    ;;
            esac
        fi
    done
fi

## Sync locale translations with POEditor
node scripts/poEditor.js

## Generate `app.json` file used for Expo publishing
scripts/createAppJson.js $ENV > app.json

### If `expo whoami` exits with 1, we're not logged in, so log in
if ! ./node_modules/.bin/expo whoami; then
    ./node_modules/.bin/expo login -u $EXPO_USERNAME -p $EXPO_PASSWORD --non-interactive
fi

### Call the `expo deploy` command with the temporary `app.json` file
./node_modules/.bin/expo publish --config=app.json --clear
