#!/bin/bash
#
# Copyright 2015 Theke Solutions
#
# This file is part of Koha.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -e

. /lib/lsb/init-functions

export PERL5LIB={{ koha_install_dir }}/lib

usage()
{
    local scriptname=$(basename $0)

    cat <<EOF
$scriptname

This script lets you manage the plack daemons for your Koha instances.

Usage:
$scriptname --start|--stop|--restart [--quiet|-q] instancename1 [instancename2...]
$scriptname --enable|--disable instancename1 [instancename2]
$scriptname -h|--help

    --start               Start the plack daemon for the specified instances
    --stop                Stop the plack daemon for the specified instances
    --restart             Restart the plack daemon for the specified instances
    --quiet|-q            Make the script quiet about non existent instance names
                          (useful for calling from another scripts).
    --help|-h             Display this help message

EOF
}

start_plack()
{
    local instancename=$1

    local PIDFILE="{{ koha_install_dir }}/var/run/plack.pid"
    local PLACKSOCKET="{{ koha_install_dir }}/var/run/plack.sock"
    local PSGIFILE="{{ koha_install_dir }}/bin/plack/koha.psgi"
    local NAME="${instancename}-koha-plack"

    if [ -e "/etc/koha/plack.psgi" ]; then
        # pick instance-specific psgi file
        PSGIFILE="/etc/koha/plack.psgi"
    fi # else stick with the default one

    _check_and_fix_perms $instancename

    STARMANOPTS="-M FindBin --max-requests 50 --workers 8 \
                 --user=www-data --group www-data \
                 --pid ${PIDFILE} \
                 --daemonize \
                 --access-log /var/log/koha/plack.log \
                 --error-log /var/log/koha/plack-error.log \
                 -E deployment --socket ${PLACKSOCKET} ${PSGIFILE}"

    if ! is_plack_running ${instancename}; then
        export KOHA_CONF="{{ koha_install_dir }}/etc/koha-conf.xml"
        if [ -e "/etc/koha/koha-conf.xml" ]; then
            # pick instance-specific psgi file
            KOHA_CONF="/etc/koha/koha-conf.xml"
        fi # else stick with the default one

        log_daemon_msg "Starting Plack daemon for ${instancename}"

        if ${STARMAN} ${STARMANOPTS}; then
            log_end_msg 0
        else
            log_end_msg 1
        fi
    else
        log_daemon_msg "Error: Plack already running for ${instancename}"
        log_end_msg 1
    fi
}

stop_plack()
{
    local instancename=$1

    local PIDFILE="{{ koha_install_dir }}/var/run/plack.pid"

    if is_plack_running ${instancename}; then

        log_daemon_msg "Stopping Plack daemon for ${instancename}"

        if start-stop-daemon --pidfile ${PIDFILE} --stop --retry=TERM/30/KILL/5; then
            rm -f ${PIDFILE}
            log_end_msg 0
        else
            log_end_msg 1
        fi
    else
        log_daemon_msg "Error: Plack not running for ${instancename}"
        log_end_msg 1
    fi
}

restart_plack()
{
    local instancename=$1
    local PIDFILE="{{ koha_install_dir }}/var/run/plack.pid"

    if is_plack_running ${instancename}; then

        log_daemon_msg "Restarting Plack daemon for ${instancename}"

        if stop_plack $instancename && start_plack $instancename; then
            log_end_msg 0
        else
            log_end_msg 1
        fi
    else
        log_daemon_msg "Error: Plack not running for ${instancename}"
        log_end_msg 1
    fi
}

check_env_and_warn()
{
    local apache_version_ok="no"
    local required_modules="headers proxy_http"
    local missing_modules=""

    if /usr/sbin/apache2ctl -v | grep -q "Server version: Apache/2.4"; then
        apache_version_ok="yes"
    fi

    for module in ${required_modules}; do
        if ! /usr/sbin/apachectl -M 2> /dev/null | grep -q ${module}; then
            missing_modules="${missing_modules}${module} "
        fi
    done

    if [ "${apache_version_ok}" != "yes" ]; then
        echo "WARNING: koha-plack requires Apache 2.4.x and you don't have that."
    fi

    if [ "${missing_modules}" != "" ]; then
        cat 1>&2 <<EOM
WARNING: koha-plack requires some Apache modules that you are missing.
You can install them with:

    sudo a2enmod ${missing_modules}

EOM

    fi
}

_check_and_fix_perms()
{
    local instance=$1

    local files="/var/log/koha/plack.log \
                 /var/log/koha/plack-error.log"

    for file in ${files}
    do
        if [ ! -e "${file}" ]; then
            touch ${file}
        fi
        chown "koha":"koha" ${file}
    done
}

set_action()
{
    if [ "$op" = "" ]; then
        op=$1
    else
        echo  "Error: only one action can be specified." ; exit 1 ;
    fi
}

#################Functions from koha_functions.sh##################

is_plack_running()
{
    local instancename=$1

    if start-stop-daemon --pidfile "{{ koha_install_dir }}/var/run/plack.pid" \
            --status ; then
        return 0
    else
        return 1
    fi
}

###################################################################

STARMAN=$(which starman)
op=""
quiet="no"

# Read command line parameters
while [ $# -gt 0 ]; do

    case "$1" in
        -h|--help)
            usage ; exit 0 ;;
        -q|--quiet)
            quiet="yes"
            shift ;;
        --start)
            set_action "start"
            shift ;;
        --stop)
            set_action "stop"
            shift ;;
        --restart)
            set_action "restart"
            shift ;;
        --enable)
            set_action "enable"
            shift ;;
        --disable)
            set_action "disable"
            shift ;;
        -*)
            echo  "Error: invalid option switch ($1)" ; exit 5  ;;
        *)
            # We expect the remaining stuff are the instance names
            break ;;
    esac

done

if [ -z $PERL5LIB ]; then
    PERL5LIB="/usr/share/koha/lib"
fi

export PERL5LIB

[ "${quiet}" != "yes" ] && check_env_and_warn

if [ $# -gt 0 ]; then
    # We have at least one instance name
    for name in "$@"; do
        case $op in
            "start")
                start_plack $name
                ;;
            "stop")
                stop_plack $name
                ;;
            "restart")
                restart_plack $name
                ;;
            *)
                usage
                ;;
        esac
    done
else
    if [ "$quiet" = "no" ]; then
        echo "Error: you must provide at least one instance name"
    fi
fi

exit 0
