#!/bin/bash
set -e

export LC_ALL=en_US.UTF-8

export HOME=/app
cd

if [ -f /app/tmp/pids/delayed_job.pid ]; then
  rm /app/tmp/pids/delayed_job.pid
fi

# DATABASE_URL takes the highest precedence.
if [[ -n "$DATABASE_URL" ]]; then
    case "${DATABASE_URL%%://*}" in
        mysql)
            DATABASE_ADAPTER=mysql2
            DATABASE_URL="$DATABASE_ADAPTER${DATABASE_URL#mysql}" ;;
        postgres)
            DATABASE_ADAPTER=postgresql ;;
        *)
            DATABASE_ADAPTER="${DATABASE_URL%%://*}" ;;
    esac
    eval "$(ruby -ruri -rshellwords -e 'u = URI(ARGV[0]); {
      HOST: u.hostname,
      PORT: u.port,
      USERNAME: u.user,
      PASSWORD: u.password,
      NAME: u.path[%r{[^/]+}]
    }.each {|k,v| puts "HUGINN_DATABASE_#{k}=#{v.to_s.shellescape}" }' "$DATABASE_URL")"
# is a mysql or postgresql database linked?
# requires that the mysql or postgresql containers have exposed
# port 3306 and 5432 respectively.
elif [[ -n "${MYSQL_PORT_3306_TCP_ADDR}" || ("${DATABASE_ADAPTER}" == "mysql2" && -n "${DATABASE_HOST}") ]]; then
    DATABASE_ADAPTER=${DATABASE_ADAPTER:-mysql2}
    DATABASE_HOST=${DATABASE_HOST:-${MYSQL_PORT_3306_TCP_ADDR}}
    DATABASE_PORT=${DATABASE_PORT:-${MYSQL_PORT_3306_TCP_PORT:-3306}}
elif [[ -n "${POSTGRES_PORT_5432_TCP_ADDR}" || ("${DATABASE_ADAPTER}" == "postgresql" && -n "${DATABASE_HOST}") ]]; then
    DATABASE_ADAPTER=${DATABASE_ADAPTER:-postgresql}
    DATABASE_HOST=${DATABASE_HOST:-${POSTGRES_PORT_5432_TCP_ADDR}}
    DATABASE_PORT=${DATABASE_PORT:-${POSTGRES_PORT_5432_TCP_PORT:-5432}}
else
    START_MYSQL=${START_MYSQL:-true}
    DATABASE_ADAPTER=${DATABASE_ADAPTER:-mysql2}
fi

USE_GRAPHVIZ_DOT=${HUGINN_USE_GRAPHVIZ_DOT:-${USE_GRAPHVIZ_DOT:-dot}}
DATABASE_HOST=${HUGINN_DATABASE_HOST:-${DATABASE_HOST:-localhost}}
DATABASE_PORT=${HUGINN_DATABASE_PORT:-${DATABASE_PORT}}
case "$DATABASE_ADAPTER" in
    mysql*)
        DATABASE_ENCODING=${HUGINN_DATABASE_ENCODING:-${DATABASE_ENCODING:-utf8mb4}} ;;
    *)
        DATABASE_ENCODING=${HUGINN_DATABASE_ENCODING:-${DATABASE_ENCODING:-utf8}} ;;
esac
DATABASE_USERNAME=${HUGINN_DATABASE_USERNAME:-${DATABASE_USERNAME}}
DATABASE_PASSWORD=${HUGINN_DATABASE_PASSWORD:-${DATABASE_PASSWORD:-password}}
DATABASE_NAME=${HUGINN_DATABASE_NAME:-${DATABASE_NAME:-huginn_production}}
RAILS_ENV=${HUGINN_RAILS_ENV:-${RAILS_ENV:-production}}
RAILS_LOG_TO_STDOUT=${RAILS_LOG_TO_STDOUT:-true}
RAILS_SERVE_STATIC_FILES=${RAILS_SERVE_STATIC_FILES:-true}
IP="${IP:-0.0.0.0}"
PORT=${HUGINN_PORT:-${PORT:-3000}}
PORT="$(echo $PORT|awk -F ':' '{print $NF}')"
HUGINN_PORT=${PORT}

cp -a /app/.env.example /tmp/

# Do we have a Rails secret yet?
# If not, generate one, but persist it for the container's lifetime.
if [ -z "$APP_SECRET_TOKEN" ] && grep -q ^APP_SECRET_TOKEN=REPLACE_ME_NOW /tmp/.env.example; then
    [ -e '/tmp/secret' ] && secret="$(cat /tmp/secret)"
    if [ -z "$secret" ]; then
        echo 'Generating random APP_SECRET_TOKEN.'
        secret=$(dd if=/dev/urandom bs=36 count=1 | openssl base64)
        echo "$secret" > /tmp/secret
    fi
    sed -i "s:REPLACE_ME_NOW!:$secret:" /tmp/.env.example
fi

# Add ENV variables to .env.example which are not present in it but usable
cat >> /tmp/.env.example <<EOF
ASSET_HOST=
DEFAULT_SCENARIO_FILE=
IP=
RAILS_ENV=
RAILS_LOG_TO_STDOUT=
RAILS_SERVE_STATIC_FILES=
SEED_EMAIL=
SEED_PASSWORD=
SEED_USERNAME=
SMTP_OPENSSL_CA_FILE=
SMTP_OPENSSL_CA_PATH=
SMTP_OPENSSL_VERIFY_MODE=
START_MYSQL=
EOF

[ -e '/app/.env' ] && cat /app/.env >> /tmp/.env.example

quote_if_necessary() {
  if grep -q -E -e '^".*" *$' -e "^'.*' *$" <<<"$*"; then
    # preserve single or double quotes if they are provided
    echo "$*";
  else
    # otherwise double quote the string after escaping \, $, `
    echo "\"$(sed -e 's/\\/\\\\/g' -e 's/\$/\\\$/g' -e 's/`/\\`/g' <<<"$*")\""
  fi
}

# Default to the environment variable values set in .env.example
sed -n -r -e 's/^#?([A-Za-z0-9_]+=.*)/\1/p' /tmp/.env.example | \
  while IFS='=' read var value ; do
    huginn_var="HUGINN_$var"
    val="${!huginn_var:-${!var:-$value}}"
    echo "$var=$(quote_if_necessary $val)"
  done > /tmp/.env

source /tmp/.env

if [ "${START_MYSQL}" = "true" ]; then
  echo 'DATABASE_SOCKET=/app/tmp/sockets/mysqld.sock' >> /tmp/.env
  DATABASE_SOCKET='/app/tmp/sockets/mysqld.sock'
fi

[ -e '/app/.env' ] || cp -a /tmp/.env /app/
chmod ugo+r /app/.env
rm -f /tmp/.env.example

# use default port number if it is still not set
case "${DATABASE_ADAPTER}" in
  mysql2) DATABASE_PORT=${DATABASE_PORT:-3306} ;;
  postgresql) DATABASE_PORT=${DATABASE_PORT:-5432} ;;
  *) echo "Unsupported database adapter. Available adapters are mysql2, and postgresql." && exit 1 ;;
esac

bundle config set --local path vendor/bundle
bundle config set --local without 'test development'
bundle install

# Configure the unicorn server
sed -r config/unicorn.rb.example \
    -e "s/^ *listen .+/listen '$IP:$PORT'/" \
    -e 's;^ *stderr_path .+;stderr_path "/dev/stderr";' \
    -e 's;^ *stdout_path .+;stdout_path "/dev/stdout";' \
    -e '/^ *pid .+/d' > config/unicorn.rb

mkdir -p tmp/pids tmp/cache tmp/sockets log
