#!/usr/bin/env bash
set -eux
PROJECT_PATH="${PROJECT_PATH-$(dirname "$(readlink -f "$0")")}"  # The full project path
WEB2PY_PATH="$(dirname $(dirname "$PROJECT_PATH"))"
ADMIN_PATH="${WEB2PY_PATH}/applications/admin"
WEB2PY_NAME="${WEB2PY_NAME-$(basename ${WEB2PY_PATH})}"  # Directory web2py lives in, will be unique per installation
DEPLOY_USER="$(stat -c '%U' install-supervisord.sh 2>/dev/null || stat -f '%Su' install-supervisord.sh 2>/dev/null)"

APP_USER="www"
APP_GROUP="www"
WWW_SERVER_NAME="${WEB2PY_NAME}"

# The APP_USER (webserver process) needs to be able to write to some
# directories in any installed web2py apps, so make a list here to chown
DIRS_TO_CHOWN=("/var/run/uwsgi")
for APP_PATH in "${PROJECT_PATH}" "${ADMIN_PATH}"; do
    # NB: Yan says we should write to
    # web2py_path & gluon but seems risky, so just pick specific directories
    for DIR in "${APP_PATH}/errors" \
            "${APP_PATH}/databases" \
            "${APP_PATH}/sessions" \
            "${APP_PATH}/languages" \
            "${APP_PATH}/uploads" \
            "${APP_PATH}/logs" \
            "${APP_PATH}/deposit"; do
        DIRS_TO_CHOWN+=("${DIR}")
    done
done

for DIR in "${DIRS_TO_CHOWN[@]}"; do
    mkdir -p -- "${DIR}"
    chown -R ${APP_USER} "${DIR}"
    chmod g+w "${DIR}"
done

# This dir needs to exist, but does not need to be writable by the APP_USER
for APP_PATH in "${WEB2PY_PATH}" "${ADMIN_PATH}"; do
    mkdir -p -- "${APP_PATH}/private"
    chown -R ${DEPLOY_USER} "${APP_PATH}/private"
done


[ -d "/etc/supervisor" ] && SUPERVISORD_CONF_PATH="/etc/supervisor"
[ -e "/usr/local/etc/supervisord.conf.sample" ] && SUPERVISORD_CONF_PATH="/usr/local/etc"
mkdir -p "${SUPERVISORD_CONF_PATH}/supervisord.conf.d/"
mkdir -p "/var/run/supervisor"

SUPERVISORD_LOG_PATH="/var/log/supervisord"
mkdir -p "${SUPERVISORD_LOG_PATH}"

cat <<EOF > "${SUPERVISORD_CONF_PATH}/supervisord.conf"
; **** Generated by $0 - DO NOT EDIT
;
[unix_http_server]
file=/var/run/supervisor/supervisor.sock   ; (the path to the socket file)

[supervisord]
logfile=${SUPERVISORD_LOG_PATH}/supervisord.log ; (main log file)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;default 10)
loglevel=info               ; (log level;default info; others: debug,warn,trace)
pidfile=/var/run/supervisor/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false              ; (start in foreground if true;default false)
minfds=1024                 ; (min. avail startup file descriptors;default 1024)
minprocs=200                ; (min. avail process descriptors;default 200)

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.sock ; use a unix:// URL  for a unix socket

[include]
files = supervisord.conf.d/*.conf
EOF

cat <<EOF > "${SUPERVISORD_CONF_PATH}/supervisord.conf.d/${WEB2PY_NAME}.conf"
; **** Generated by $0 - DO NOT EDIT
;
[group:${WEB2PY_NAME}]
programs=${WEB2PY_NAME}_uwsgi,${WEB2PY_NAME}_background_tasks,${WEB2PY_NAME}_session_cleanup

[program:${WEB2PY_NAME}_uwsgi]
directory=${WEB2PY_PATH}
command=${WEB2PY_PATH}/bin/uwsgi
    -s /var/run/uwsgi/%(program_name)s%(process_num)d.sock
    --chmod-socket=666
    --need-app
    --disable-logging
    --master
    --home=${WEB2PY_PATH}
    --wsgi-file handler.py
    --processes 1
    --threads 10
    --uid "${APP_USER}"
    --gid "${APP_GROUP}"
stdout_logfile=${SUPERVISORD_LOG_PATH}/%(program_name)s_stdout.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=10
stderr_logfile=${SUPERVISORD_LOG_PATH}/%(program_name)s_stderr.log
stderr_logfile_maxbytes=10MB
stderr_logfile_backups=10
startsecs=10
stopsignal=QUIT
stopasgroup=true
killasgroup=true
process_name=%(program_name)s%(process_num)d
numprocs=5

[program:${WEB2PY_NAME}_background_tasks]
; includes sending email autoreminders. Stop this specific task via:
;   supervisorctl stop ${WEB2PY_NAME}_background_tasks
directory=${WEB2PY_PATH}
user=${APP_USER}
group=${APP_GROUP}
command=$(which bash) -c "${WEB2PY_PATH}/bin/python web2py.py -S OZtree/default -M -e -R applications/OZtree/private/background_tasks.py --args ${WWW_SERVER_NAME} verbose && /bin/sleep 86400"
stdout_logfile=${SUPERVISORD_LOG_PATH}/%(program_name)s_stdout.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=10
stderr_logfile=${SUPERVISORD_LOG_PATH}/%(program_name)s_stderr.log
stderr_logfile_maxbytes=10MB
stderr_logfile_backups=10
startsecs=10
stopsignal=QUIT
autorestart=true

[program:${WEB2PY_NAME}_session_cleanup]
directory=${WEB2PY_PATH}
user=${APP_USER}
group=${APP_GROUP}
command=${WEB2PY_PATH}/bin/python web2py.py -S OZtree -M -R scripts/sessions2trash.py
stdout_logfile=${SUPERVISORD_LOG_PATH}/%(program_name)s_stdout.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=10
stderr_logfile=${SUPERVISORD_LOG_PATH}/%(program_name)s_stderr.log
stderr_logfile_maxbytes=10MB
stderr_logfile_backups=10
startsecs=10
stopsignal=QUIT
autorestart=true
EOF
