#!/bin/bash

set -e # exit immediately if a simple command exits with a non-zero status set -u # report the usage of uninitialized variables

# Setup env vars and folders for the webapp_ctl script source /var/vcap/jobs/<%= job_name %>/bin/ctl_setup.sh

export PORT=${PORT:-5000} export LANG=en_US.UTF-8

# Setup HTTP_PROXY, HTTPS_PROXY, NO_PROXY as necessary source $JOB_DIR/bin/ctl_nginx.sh

# Setup for Rails application source $JOB_DIR/bin/rails_ctl_setup.sh

# Helpers for PostgresDB source $JOB_DIR/bin/ctl_db_utils.sh

# Helpers for Redis source $JOB_DIR/bin/ctl_redis_utils.sh

case $1 in

start)
  pid_guard $PIDFILE $JOB_NAME

  cd $WEBAPP_DIR

  # link database.yml config to application
  link_sql_db_config

  # if redis enabled, link it to application
  link_redis_config yaml config/redis.yml

  # Migrations, if requested
  run_migrations $WEBAPP_DIR

  # TODO what is 'ulimit -c unlimited' for; when not to use it?
  ulimit -c unlimited

  # Start the rack app using requested appstack
  source $JOB_DIR/bin/ctl_start.sh

  echo "Running $JOB_NAME on $PORT"
  ;;

stop)
  kill_and_wait $PIDFILE

  ;;
*)
  echo "Usage: <%= job_name %>_rack_ctl {start|stop}"

  ;;

esac exit 0