#!/bin/sh
#
# rc.d script for the vrobbler Django web app, served by gunicorn.
#
# PROVIDE: vrobbler
# REQUIRE: NETWORKING postgresql redis
# KEYWORD: shutdown
#
# Installation (on the FreeBSD jail):
#
#   install -m 0555 rc.d/vrobbler /usr/local/etc/rc.d/vrobbler
#   sysrc vrobbler_enable="YES"
#   service vrobbler start
#
# Configuration (via sysrc or /etc/rc.conf):
#
#   vrobbler_bind     - gunicorn bind address      (default: 0.0.0.0:8014)
#   vrobbler_workers  - number of gunicorn workers (default: 4)
#   vrobbler_gunicorn - path to gunicorn           (default: /usr/local/bin/gunicorn)
#   vrobbler_user     - user to run as             (default: root)
#   vrobbler_flags    - extra daemon(8) flags
#
# NOTE: do not name this knob "${name}_program" (e.g. vrobbler_program).
# FreeBSD's rc.subr(8) overrides $command with ${name}_program whenever it
# is set, which would replace our daemon(8) wrapper with gunicorn itself.
#
# The command is run under daemon(8) with a supervisor pidfile (-P) and
# restart-on-crash (-R), so gunicorn is automatically restarted if it dies,
# in the same way immortal used to.  Sending SIGTERM to the supervisor (which
# is what `service vrobbler stop` does) forwards the signal to gunicorn and
# lets it shut down gracefully.
#
# Environment variables (database URL, Redis URL, API keys, ...) are read by
# Django itself from /usr/local/etc/vrobbler.conf, so no shell env is needed.
#
# If you run gunicorn as a non-root user, make sure it can write its pidfile
# and log files (e.g. chown /var/run/vrobbler.pid's directory and the
# /var/log/vrobbler_*.log files).
#
. /etc/rc.subr

name="vrobbler"
rcvar="vrobbler_enable"

load_rc_config ${name}

: ${vrobbler_enable:="NO"}
: ${vrobbler_bind:="0.0.0.0:8014"}
: ${vrobbler_workers:="4"}
: ${vrobbler_gunicorn:="/usr/local/bin/gunicorn"}
: ${vrobbler_log_dir:="/var/log"}

pidfile="/var/run/${name}.pid"

command="/usr/sbin/daemon"
command_args="-f -P ${pidfile} -R 5 -t ${name} ${vrobbler_gunicorn} vrobbler.wsgi:application --bind ${vrobbler_bind} --workers ${vrobbler_workers} --access-logfile ${vrobbler_log_dir}/${name}_access.log --error-logfile ${vrobbler_log_dir}/${name}_error.log"

run_rc_command "$1"
