#!/bin/sh
#
# koha-functions.sh -- shared library of helper functions for koha-* scripts
# Copyright 2014 - Tomas Cohen Arazi
#                  Universidad Nacional de Cordoba
#
# 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 <https://www.gnu.org/licenses/>.


die()
{
    echo "$@" 1>&2
    exit 1
}

warn()
{
    echo "$@" 1>&2
}

get_apache_config_for()
{
    local site=$1
    local sitefile="/etc/apache2/sites-available/$site"

    if is_instance $site; then
        if [ -f "$sitefile.conf" ]; then
            echo "$sitefile.conf"
        elif [ -f "$sitefile" ]; then
            echo "$sitefile"
        fi
    fi
}

get_opacdomain_for()
{
    local site=$1

    if [ -e /etc/koha/koha-sites.conf ]; then
        . /etc/koha/koha-sites.conf
    else
        echo "Error: /etc/koha/koha-sites.conf not present." 1>&2
        exit 1
    fi
    local opacdomain="$OPACPREFIX$site$OPACSUFFIX$DOMAIN"
    echo "$opacdomain"
}

get_intradomain_for()
{
    local site=$1

    if [ -e /etc/koha/koha-sites.conf ]; then
        . /etc/koha/koha-sites.conf
    else
        echo "Error: /etc/koha/koha-sites.conf not present." 1>&2
        exit 1
    fi
    local intradomain="$INTRAPREFIX$site$INTRASUFFIX$DOMAIN"
    echo "$intradomain"
}

letsencrypt_get_opacdomain_for()
{
    local site=$1

    if [ -e /var/lib/koha/$site/letsencrypt.enabled ]; then
        . /var/lib/koha/$site/letsencrypt.enabled
    else
        local opacdomain=$(get_opacdomain_for $site)
    fi
    echo "$opacdomain"
}

is_enabled()
{
    local site=$1
    local instancefile=$(get_apache_config_for $site)

    if [ "$instancefile" = "" ]; then
        return 1
    fi

    if grep -q '^[[:space:]]*Include /etc/koha/apache-shared-disable.conf' \
            "$instancefile" ; then
        return 1
    else
        return 0
    fi
}

is_instance()
{
    local instancename=$1

    if find -L /etc/koha/sites -mindepth 1 -maxdepth 1 \
                         -type d -printf '%f\n'\
          | grep -q -x "$instancename" ; then
        return 0
    else
        return 1
    fi
}

is_email_enabled()
{
    local instancename=$1

    if [ -e /var/lib/koha/$instancename/email.enabled ]; then
        return 0
    else
        return 1
    fi
}

is_letsencrypt_enabled()
{
    local instancename=$1

    if [ -e /var/lib/koha/$instancename/letsencrypt.enabled ]; then
        return 0
    else
        return 1
    fi
}

is_sip_enabled()
{
    local instancename=$1

    if [ -e /var/lib/koha/$instancename/sip.enabled ]; then
        return 0
    else
        return 1
    fi
}

is_sitemap_enabled()
{
    local instancename=$1

    if [ -e /var/lib/koha/$instancename/sitemap.enabled ]; then
        return 0
    else
        return 1
    fi
}

is_sip_running()
{
    local instancename=$1

    if daemon --name="$instancename-koha-sip" \
            --pidfiles="/var/run/koha/$instancename/" \
            --user="$instancename-koha.$instancename-koha" \
            --running ; then
        return 0
    else
        return 1
    fi
}

is_zebra_running()
{
    local instancename=$1

    if daemon --name="$instancename-koha-zebra" \
            --pidfiles="/var/run/koha/$instancename/" \
            --user="$instancename-koha.$instancename-koha" \
            --running ; then
        return 0
    else
        return 1
    fi
}

is_indexer_running()
{
    local instancename=$1

    if daemon --name="$instancename-koha-indexer" \
            --pidfiles="/var/run/koha/$instancename/" \
            --user="$instancename-koha.$instancename-koha" \
            --running ; then
        return 0
    else
        return 1
    fi
}

is_es_indexer_running()
{
    local instancename=$1

    if daemon --name="$instancename-koha-es-indexer" \
            --pidfiles="/var/run/koha/$instancename/" \
            --user="$instancename-koha.$instancename-koha" \
            --running ; then
        return 0
    else
        return 1
    fi
}

is_worker_running()
{
    local instancename=$1
    local queue=$2

    local name=`get_worker_name $instancename $queue`

    if daemon --name="$name" \
            --pidfiles="/var/run/koha/$instancename/" \
            --user="$instancename-koha.$instancename-koha" \
            --running ; then
        return 0
    else
        return 1
    fi
}

get_worker_name()
{
    local name=$1
    local queue=$2

    if [ "$queue" = "" ] || [ "$queue" = "default" ]; then
        echo "${name}-koha-worker"
    else
        echo "${name}-koha-worker-${queue}"
    fi
}

get_worker_queues()
{
    for queue in default long_tasks; do
        echo $queue
    done;
}

is_plack_enabled_opac()
{
    local instancefile=$1

    if [ "$instancefile" = "" ]; then
        return 1
    fi

    # remember 0 means success/true in bash.
    if grep -q '^[[:space:]]*Include /etc/koha/apache-shared-opac-plack.conf' \
            "$instancefile" ; then
        return 0
    else
        return 1
    fi
}

is_plack_enabled_intranet()
{
    local instancefile=$1

    if [ "$instancefile" = "" ]; then
        return 1
    fi

    # remember 0 means success/true in bash.
    if grep -q '^[[:space:]]*Include /etc/koha/apache-shared-intranet-plack.conf' \
            "$instancefile" ; then
        return 0
    else
        return 1
    fi
}

is_plack_enabled()
{
    local site=$1
    local instancefile=$(get_apache_config_for $site)

    if [ "$instancefile" = "" ]; then
        return 1
    fi

    if is_plack_enabled_opac $instancefile ; then
        enabledopac=1
    else
        enabledopac=0
    fi
    if is_plack_enabled_intranet $instancefile ; then
        enabledintra=1
    else
        enabledintra=0
    fi

    # remember 0 means success/true in bash.
    if [ "$enabledopac" != "$enabledintra" ] ; then
        echo "$site has a plack configuration error. Enable or disable plack to correct this."
        return 0
    elif [ "$enabledopac" = "1" ] ; then
        return 0
    else
        return 1
    fi
}

is_plack_running()
{
    local instancename=$1

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

is_z3950_enabled()
{
    local instancename=$1

    if [ -e /etc/koha/sites/$instancename/z3950/config.xml ]; then
        return 0
    else
        return 1
    fi
}

is_z3950_running()
{
    local instancename=$1

    if start-stop-daemon --pidfile "/var/run/koha/${instancename}/z3950-responder.pid" \
            --user="$instancename-koha" \
            --status ; then
        return 0
    else
        return 1
    fi
}

is_elasticsearch_enabled()
{
    local instancename=$1

    # is querying the DB fails then $searching won't match 'Elasticsearch'. Ditching STDERR
    search_engine=$(koha-shell $instancename -c "/usr/share/koha/bin/admin/koha-preferences get SearchEngine 2> /dev/null")

    if [ "$search_engine" = "Elasticsearch" ]; then
        return 0
    else
        return 1
    fi
}

adjust_paths_git_install()
{
# Adjust KOHA_HOME, PERL5LIB, KOHA_BINDIR for git installs

    local instancename=$1

    if is_git_install $instancename; then
        KOHA_HOME=$(run_safe_xmlstarlet $instancename intranetdir)
        PERL5LIB="$KOHA_HOME:$KOHA_HOME/lib"
        KOHA_BINDIR=misc
    else
        KOHA_BINDIR=bin
    fi
}

is_git_install()
{
    local instancename=$1 git_install

    # env var GIT_INSTALL overrules koha-conf entry
    if [ -n "$GIT_INSTALL" ]; then
        if [ "$GIT_INSTALL" != "0" ]; then return 0; else return 1; fi
    fi

    # now check koha-conf; looking at dev_install as historical fallback
    if [ "$instancename" != "" ] && is_instance $instancename; then
        git_install=$(run_safe_xmlstarlet $instancename git_install)
        if [ -z "$git_install" ]; then git_install=$(run_safe_xmlstarlet $instancename dev_install); fi
    fi
    if [ -n "$git_install" ] && [ "$git_install" != "0" ]; then
        return 0; # true
    else
        return 1
    fi
}

is_debug_mode()
{
    local instancename=$1 debug_mode

    # env var DEBUG_MODE overrules koha-conf entry
    if [ -n "$DEBUG_MODE" ]; then
        if [ "$DEBUG_MODE" != "0" ]; then return 0; else return 1; fi
    fi

    # now check koha-conf
    if [ "$instancename" != "" ] && is_instance $instancename; then
        debug_mode=$(run_safe_xmlstarlet $instancename debug_mode)
    fi
    if [ -n "$debug_mode" ] && [ "debug_mode" != "0" ]; then
        return 0; # true
    else
        return 1
    fi
}

get_instances()
{
    find -L /etc/koha/sites -mindepth 1 -maxdepth 1\
                         -type d -printf '%f\n' | sort
}

get_loglevels()
{
    local instancename=$1
    local retval=$(run_safe_xmlstarlet $instancename zebra_loglevels)
    if [ "$retval" != "" ]; then
        echo "$retval"
    else
        echo "none,fatal,warn"
    fi
}

get_max_record_size()
{
    local instancename=$1
    local retval=$(xmlstarlet sel -t -v 'yazgfs/config/zebra_max_record_size' /etc/koha/sites/$instancename/koha-conf.xml)
    if [ "$retval" != "" ]; then
        echo "$retval"
    else
        echo "1024"
    fi
}

get_tmp_path()
{
    local instancename=$1
    local retval=$(run_safe_xmlstarlet $instancename tmp_path)
    if [ "$retval" != "" ]; then
        echo "$retval"
        return 0
    fi
}

get_upload_path()
{
    local instancename=$1
    local retval=$(run_safe_xmlstarlet $instancename upload_path)
    if [ "$retval" != "" ]; then
        echo "$retval"
        return 0
    fi
}

get_tmpdir()
{
    if [ "$TMPDIR" != "" ]; then
        if [ -d "$TMPDIR" ]; then
            echo $TMPDIR
            return 0
        fi
        # We will not unset TMPDIR but just default to /tmp here
        # Note that mktemp (used later) would look at TMPDIR
        echo "/tmp"
        return 0
    fi
    local retval=$(mktemp -u)
    if [ "$retval" = "" ]; then
        echo "/tmp"
        return 0
    fi
    echo $(dirname $retval)
}

run_safe_xmlstarlet()
{
    # When a bash script sets -e (errexit), calling xmlstarlet on an
    # unexisting key would halt the script. This is resolved by calling
    # this function in a subshell. It will always returns true, while not
    # affecting the exec env of the caller. (Otherwise, errexit is cleared.)
    local instancename=$1
    local myexpr=$2
    set +e; # stay on the safe side
    echo $(xmlstarlet sel -t -v "yazgfs/config/$myexpr" /etc/koha/sites/$instancename/koha-conf.xml)
    return 0
}
