#!/usr/bin/env bash

set -e

# NOTE: The canonical source for this file is in the metabase/metabase repository.
# Please update it there then copy to the metabase/metabase-deploy repository.

# Translate various Heroku environment variables to Metabase equivalents

if [ "$PORT" ]; then
    export MB_JETTY_PORT="$PORT"
fi

# Heroku Postgres
if [ "$DATABASE_URL" ]; then
    if [[ $string == *"?"* ]]; then
        # if DATABASE_URL already has a query string don't mess with it
        export MB_DB_CONNECTION_URI="$DATABASE_URL"
    else
        # otherwise add the SSL parameters to ensure upgraded databases work on Heroku
        export MB_DB_CONNECTION_URI="$DATABASE_URL?ssl=true&sslmode=require&sslfactory=org.postgresql.ssl.NonValidatingFactory"
    fi
fi

# Mailgun (Heroku)
if [ "$MAILGUN_SMTP_LOGIN" ]; then
    export MB_EMAIL_SMTP_HOST="$MAILGUN_SMTP_SERVER"
    export MB_EMAIL_SMTP_PORT="$MAILGUN_SMTP_PORT"
    export MB_EMAIL_SMTP_USERNAME="$MAILGUN_SMTP_LOGIN"
    export MB_EMAIL_SMTP_PASSWORD="$MAILGUN_SMTP_PASSWORD"
fi

# SendGrid (Heroku)
if [ "$SENDGRID_USERNAME" ]; then
    export MB_EMAIL_SMTP_HOST="smtp.sendgrid.net"
    export MB_EMAIL_SMTP_PORT="587"
    export MB_EMAIL_SMTP_USERNAME="$SENDGRID_USERNAME"
    export MB_EMAIL_SMTP_PASSWORD="$SENDGRID_PASSWORD"
    export MB_EMAIL_SMTP_SECURITY="tls"
fi

# Mandrill (Heroku)
if [ "$MANDRILL_USERNAME" ]; then
    export MB_EMAIL_SMTP_HOST="smtp.mandrillapp.com"
    export MB_EMAIL_SMTP_PORT="587"
    export MB_EMAIL_SMTP_USERNAME="$MANDRILL_USERNAME"
    export MB_EMAIL_SMTP_PASSWORD="$MANDRILL_APIKEY"
fi

# Postmark (Heroku)
# NOTE: requires configuring sender signature for "from" address
if [ "$POSTMARK_API_TOKEN" ]; then
    export MB_EMAIL_SMTP_HOST="$POSTMARK_SMTP_SERVER"
    export MB_EMAIL_SMTP_PORT="25"
    export MB_EMAIL_SMTP_USERNAME="$POSTMARK_API_TOKEN"
    export MB_EMAIL_SMTP_PASSWORD="$POSTMARK_API_TOKEN"
    export MB_EMAIL_SMTP_SECURITY="tls"
fi

# SparkPost (Heroku)
# NOTE: requires additional configuration
if [ "$SPARKPOST_SMTP_USERNAME" ]; then
    export MB_EMAIL_SMTP_HOST="$SPARKPOST_SMTP_HOST"
    export MB_EMAIL_SMTP_PORT="$SPARKPOST_SMTP_PORT"
    export MB_EMAIL_SMTP_USERNAME="$SPARKPOST_SMTP_USERNAME"
    export MB_EMAIL_SMTP_PASSWORD="$SPARKPOST_SMTP_PASSWORD"
fi

# AWS Elastic Beanstalk w/ RDS
if [ ! -z "$RDS_HOSTNAME" ]; then
    # EEK: this is a bit fragile.  if user picks a non-standard port for their db we are screwed :(
    if [ "$RDS_PORT" == "3306" ]; then
        export MB_DB_TYPE=mysql
    else
        export MB_DB_TYPE=postgres
    fi

    export MB_DB_DBNAME=$RDS_DB_NAME
    export MB_DB_USER=$RDS_USERNAME
    export MB_DB_PASS=$RDS_PASSWORD
    export MB_DB_HOST=$RDS_HOSTNAME
    export MB_DB_PORT=$RDS_PORT
fi

exec java -Dfile.encoding=UTF-8 $JAVA_OPTS -jar ./target/uberjar/metabase.jar