#!/usr/bin/env bash

# The purpose of this script is to wrap up the necessary environment for the
# per-user NGINX (PUN) processes to run under. The PUN requires the following
# software in its environment:
#
# - nginx 1.6
# - passenger 4.0
# - ruby 2.2
# - node.js 0.10
# - git 1.9
#

# Allow admin to override the environment the PUN runs in
#
NGINX_PROFILE=${NGINX_PROFILE:-/etc/ood/profile}
if [[ -f "${NGINX_PROFILE}" ]]; then
  # Source in the custom environment
  source "${NGINX_PROFILE}"
else
  # For Software Collections 2.0
  #
  # 1. Read in environment variable SCL_PKGS which may be set in `sudo` call
  #    otherwise fallback to default software collection packages.
  #
  # 2. Check if Software Collections is installed, then source the defined
  #    package scripts.
  #
  SCL_PKGS=${SCL_PKGS:-"nginx16 rh-passenger40 rh-ruby22 nodejs010 git19"}
  SCL_SOURCE="$(command -v scl_source)"
  [[ "${SCL_SOURCE}" ]] && source "${SCL_SOURCE}" enable ${SCL_PKGS}
fi

# Root directory for this library
#
ROOT_DIR="$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")"

# Environment is set, so call Ruby now
#
exec \
  /usr/bin/env ruby \
    -I"${ROOT_DIR}/lib" \
    -rnginx_stage \
    -e "NginxStage::Application.start" \
    -- "${@}"
