#!/bin/sh
#
# build.sh
#
# Uses the `turtle` command to build standalone iOS and Android binaries.
#
# The following must be defined in `.env` or as environment
# variables in order for the script to run successfully:
#
#  Required:
#    * ENV - the environment to which to deploy (additional config in config.json)
#    * EXPO_USERNAME - the username of the Expo account with which to deploy
#    * EXPO_PASSWORD - the password of the Expo account with which to deploy
#
#  Required (iOS):
#    * APPLE_TEAM_ID - the team ID of the developer account
#    * EXPO_IOS_DIST_P12_PASSWORD - the password for the distribution p12 certificate
#    * EXPO_IOS_PUSH_P12_PASSWORD - the password for the push p12 certificate
#
#  Required (Android):
#    * ANDROID_KEYSTORE_ALIAS - alias for the Android keystore
#    * EXPO_ANDROID_KEYSTORE_PASSWORD - password for the Android keystore
#    * EXPO_ANDROID_KEY_PASSWORD - password for the Android key
#

# 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

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

## Verify that the correct certificates and environment variables are set
node scripts/build/verify.js $1

export EXPO_USERNAME=$EXPO_USERNAME
export EXPO_PASSWORD=$EXPO_PASSWORD
export EXPO_IOS_DIST_P12_PASSWORD=$EXPO_IOS_DIST_P12_PASSWORD
export EXPO_IOS_PUSH_P12_PASSWORD=$EXPO_IOS_PUSH_P12_PASSWORD
export EXPO_ANDROID_KEYSTORE_PASSWORD=$EXPO_ANDROID_KEYSTORE_PASSWORD
export EXPO_ANDROID_KEY_PASSWORD=$EXPO_ANDROID_KEY_PASSWORD

## Generate turtle cli command and run it
`node scripts/build/createCommand.js $1`
