#!/bin/bash
#
# koha-create -- Create a new Koha instance.
# Copyright 2010  Catalyst IT, Ltd
# 
# 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/>.

# Read configuration variable file if it is present
[ -r /etc/default/koha-common ] && . /etc/default/koha-common

set -e

# include helper functions
if [ -f "/usr/share/koha/bin/koha-functions.sh" ]; then
    . "/usr/share/koha/bin/koha-functions.sh"
else
    echo "Error: /usr/share/koha/bin/koha-functions.sh not present." 1>&2
    exit 1
fi

usage()
{
    local scriptname=$0
    cat <<EOF

Creates new Koha instances.

Usage:

  $scriptname [DB usage mode] [options] instancename

DB usage mode:
  --create-db               Create a new database on localhost. (default).
  --request-db              Creates a instancename-db-request.txt file where
                            you adjust your DB settings and re-run with --populate-db.
  --populate-db             Finish the installation you started with --request-db after
                            you adjusted the instancename-db-request.txt file.
  --use-db                  Use this option if you already created and populated your DB.

Options:
  --marcflavor flavor       Set the MARC flavor. Valid values are marc21 (default),
                            and unimarc.
  --zebralang lang          Choose the primary language for Zebra indexing. Valid
                            values are cs, el, en (default), es, fr, nb, ru and uk.
  --elasticsearch-server s  Enforce the use of the specified Elasticsearch server(s)
                            (default: localhost:9200).
  --memcached-servers str   Set a comma-separated list of host:port memcached servers.
  --memcached-prefix str    Set the desired prefix for the instance memcached namespace.
  --enable-sru              Enable the Z39.50/SRU server in Zebra search engine
                            (default: disabled).
  --sru-port                Specify a TCP port number for Zebra's Z39.50/SRU server
                            to listen on. (default: 7090).
  --defaultsql some.sql     Specify a default SQL file to be loaded on the DB.
  --configfile cfg_file     Specify an alternate config file for reading default values.
  --passwdfile passwd       Specify an alternate passwd file.
  --dbhost host             Enforce the use of the specified DB server
  --database dbname         Enforce the use of the specified DB name (64 char limit)
  --adminuser n             Explicit the admin user ID in the DB. Relevant in
                            conjunction with --defaultsql and --populate-db.
  --template-cache-dir      Set a user defined template_cache_dir. It defaults to
                            /var/cache/koha/<instance>/templates
  --timezone time/zone      Specify a timezone. e.g. America/Argentina
  --upload-path dir         Set a user defined upload_path. It defaults to
                            /var/lib/koha/<instance>/uploads
  --tmp-path dir            Set a user defined tmp_path. It defaults to
                            /var/lib/koha/<instance>/tmp
  --letsencrypt             Set up a https-only site with letsencrypt certificates
  --smtp-host host          SMTP host name
  --smtp-port NN            SMTP port
  --smtp-timeout NN         Connection timeout in seconds
  --smtp-ssl-mode mode      SSL mode. Options are 'disabled' (default), 'ssl' and 'starttls'.
  --smtp-user-name user     User name to be used on SMTP auth
  --smtp-password  pass     Password to authenticate SMTP
  --smtp-debug              Enable debug mode for SMTP

  --mb-host host            RabbitMQ host name (default: localhost)
  --mb-port NN              RabbitMQ port (default: 61613)
  --mb-user user            RabbitMQ user (default: guest)
  --mb-pass pass            RabbitMQ password (default: guest)
  --mb-vhost vhost          RabbitMQ vhost (default: koha_<instance>)

  --keep-cookie NAME        Do not clear this cookie at logout (can be repeated)

  --help,-h                 Show this help.

Note: the instance name cannot be longer that 11 chars.

EOF
}

# UPPER CASE VARIABLES - from configfile or default value
# lower case variables - generated within this script
generate_config_file() {
    touch "$2"
    chown "root:$username" "$2"
    # Bug 28364: the z3950 responder needs other permissions
    [ "$1" = "log4perl-site.conf.in" ] && chown "$username:$username" "$2"

    # Handle repeated command line options (KEEP_COOKIE)
    keep_cookie_lines=""
    for cookie in "${KEEP_COOKIE[@]}"
    do
        keep_cookie_lines="${keep_cookie_lines} <do_not_remove_cookie>${cookie}<\/do_not_remove_cookie>\\n"
    done

    chmod 0640 "$2"
    sed -e "s/__KOHA_CONF_DIR__/\/etc\/koha\/sites\/$name/g" \
        -e "s/__KOHASITE__/$name/g" \
        -e "s/__OPACPORT__/$OPACPORT/g" \
        -e "s/__INTRAPORT__/$INTRAPORT/g" \
        -e "s/__OPACSERVER__/$opacdomain/g" \
        -e "s/__INTRASERVER__/$intradomain/g" \
        -e "s/__ZEBRA_PASS__/$zebrapwd/g" \
        -e "s/__ZEBRA_MARC_FORMAT__/$ZEBRA_MARC_FORMAT/g" \
        -e "s/__ZEBRA_LANGUAGE__/$ZEBRA_LANGUAGE/g" \
        -e "s/__SRU_BIBLIOS_PORT__/$SRU_SERVER_PORT/g" \
        -e "s/__START_SRU_PUBLICSERVER__/$START_SRU_PUBLICSERVER/g" \
        -e "s/__END_SRU_PUBLICSERVER__/$END_SRU_PUBLICSERVER/g" \
        -e "s/__API_SECRET__/$API_SECRET/g" \
        -e "s/__DB_NAME__/$mysqldb/g" \
        -e "s/__DB_HOST__/$mysqlhost/g" \
        -e "s/__DB_USER__/$mysqluser/g" \
        -e "s/__DB_PASS__/$mysqlpwd/g" \
        -e "s/__ELASTICSEARCH_SERVER__/${ELASTICSEARCH_SERVER}/g" \
        -e "s/__UNIXUSER__/$username/g" \
        -e "s/__UNIXGROUP__/$username/g" \
        -e "s#__TEMPLATE_CACHE_DIR__#$TEMPLATE_CACHE_DIR#g" \
        -e "s#__TIMEZONE__#$TIMEZONE#g" \
        -e "s#__BCRYPT_SETTINGS__#$BCRYPT_SETTINGS#g" \
        -e "s#__UPLOAD_PATH__#$UPLOAD_PATH#g" \
        -e "s#__TMP_PATH__#$TMP_PATH#g" \
        -e "s/__LOG_DIR__/\/var\/log\/koha\/$name/g" \
        -e "s/__PLUGINS_DIR__/\/var\/lib\/koha\/$name\/plugins/g" \
        -e "s/__MEMCACHED_NAMESPACE__/$MEMCACHED_NAMESPACE/g" \
        -e "s/__MEMCACHED_SERVERS__/$MEMCACHED_SERVERS/g" \
        -e "s/__SMTP_HOST__/$SMTP_HOST/g" \
        -e "s/__SMTP_PORT__/$SMTP_PORT/g" \
        -e "s/__SMTP_TIMEOUT__/$SMTP_TIMEOUT/g" \
        -e "s/__SMTP_SSL_MODE__/$SMTP_SSL_MODE/g" \
        -e "s/__SMTP_USER_NAME__/$SMTP_USER_NAME/g" \
        -e "s/__SMTP_PASSWORD__/$SMTP_PASSWORD/g" \
        -e "s/__SMTP_DEBUG__/$SMTP_DEBUG/g" \
        -e "s/__MESSAGE_BROKER_HOST__/$MESSAGE_BROKER_HOST/g" \
        -e "s/__MESSAGE_BROKER_PORT__/$MESSAGE_BROKER_PORT/g" \
        -e "s/__MESSAGE_BROKER_USER__/$MESSAGE_BROKER_USER/g" \
        -e "s/__MESSAGE_BROKER_PASS__/$MESSAGE_BROKER_PASS/g" \
        -e "s/__MESSAGE_BROKER_VHOST__/$MESSAGE_BROKER_VHOST/g" \
        -e "s/ <do_not_remove_cookie>__KEEP_COOKIE__<\/do_not_remove_cookie>/$keep_cookie_lines/" \
        "/etc/koha/$1" > "$2"

}

getmysqlhost() {
    if [ ! -f /etc/mysql/debian.cnf ]
    then
        echo localhost
        return
    fi
    awk '
        BEGIN { FS="=" }
        $1 ~/\[/ { inclient=0 }
        $1 ~/\[client\]/ { inclient=1; next }
        inclient==1 && $1 ~/host/ { gsub(/ /, "", $2); print $2 }' \
        /etc/mysql/koha-common.cnf
}

getinstancemysqlpassword() {
    xmlstarlet sel -t -v 'yazgfs/config/pass' "/etc/koha/sites/$1/koha-conf.xml"
}

getinstancemysqluser() {
    xmlstarlet sel -t -v 'yazgfs/config/user' "/etc/koha/sites/$1/koha-conf.xml"
}

getinstancemysqldatabase() {
    xmlstarlet sel -t -v 'yazgfs/config/database' "/etc/koha/sites/$1/koha-conf.xml"
}

check_apache_config()
{

    # Check that mpm_itk is installed and enabled
    if ! /usr/sbin/apachectl -M | grep -q 'mpm_itk'; then
        # Check Apache version
        APACHE_DISABLE_MPM_MSG=""
        if /usr/sbin/apache2ctl -v | grep -q "Server version: Apache/2.4"; then
            # mpm_event or mpm_worker need to be disabled first. mpm_itk depends
            # on mpm_prefork, which is enabled if needed. See
            # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734865
            if /usr/sbin/apachectl -M | grep -q 'mpm_event'; then
                APACHE_DISABLE_MPM_MSG=" sudo a2dismod mpm_event ;"
            elif /usr/sbin/apachectl -M | grep -q 'mpm_worker'; then
                APACHE_DISABLE_MPM_MSG=" sudo a2dismod mpm_worker ;"
            # else mpm_prefork: a2enmod mpm_itk works
            fi
        # else Apache 2.2: a2enmod mpm_itk works
        fi

        cat 1>&2  <<EOM

Koha requires mpm_itk to be enabled within Apache in order to run.
Typically this can be enabled with:

   $APACHE_DISABLE_MPM_MSG sudo a2enmod mpm_itk
EOM

        die
    fi

    # Check that mod_rewrite is installed and enabled.
    if ! /usr/sbin/apachectl -M | grep -q 'rewrite_module'; then
        cat 1>&2  <<EOM

Koha requires mod_rewrite to be enabled within Apache in order to run.
Typically this can be enabled with:

    sudo a2enmod rewrite
EOM
        die
    fi

    # Check that the CGI module is installed and enabled
    # (Apache 2.4 may not have it by default.)
    if ! /usr/sbin/apachectl -M | grep -q 'cgi_module'; then
        cat 1>&2 << EOM
Koha requires mod_cgi to be enabled within Apache in order to run.
Typically this can be enabled with:

    sudo a2enmod cgi
EOM
        die
    fi

    # Check that mod_ssl is installed and enabled.
    if [ "$CLO_LETSENCRYPT" = "yes" ]; then
        if ! /usr/sbin/apachectl -M | grep -q 'ssl_module'; then
            cat 1>&2  <<EOM

Koha requires mod_ssl to be enabled within Apache in order to run with --letsencrypt.
Typically this can be enabled with:

    sudo a2enmod ssl
EOM
            die
        fi
    fi

}

set_memcached()
{
    local instance="$1"

    if [ "$CLO_MEMCACHED_SERVERS" != "" ]; then
        MEMCACHED_SERVERS=$CLO_MEMCACHED_SERVERS
    else
        if [ "$MEMCACHED_SERVERS" = "" ]; then
            MEMCACHED_SERVERS=$DEFAULT_MEMCACHED_SERVERS
        # else: was set by the koha-sites.conf file
        fi
    fi

    if [ "$CLO_MEMCACHED_PREFIX" != "" ]; then
        MEMCACHED_NAMESPACE="$CLO_MEMCACHED_PREFIX$instance"
    else
        if [ "$MEMCACHED_PREFIX" != "" ]; then
            MEMCACHED_NAMESPACE="$MEMCACHED_PREFIX$instance"
        else
            MEMCACHED_NAMESPACE="$DEFAULT_MEMCACHED_PREFIX$instance"
        fi
    fi

}

set_smtp()
{
    if [ "$CLO_SMTP_HOST" != "" ]; then
        SMTP_HOST=$CLO_SMTP_HOST
    fi

    if [ "$CLO_SMTP_PORT" != "" ]; then
        SMTP_PORT=$CLO_SMTP_PORT
    fi

    if [ "$CLO_SMTP_TIMEOUT" != "" ]; then
        SMTP_TIMEOUT=$CLO_SMTP_TIMEOUT
    fi

    if [ "$CLO_SMTP_SSL_MODE" != "" ]; then
        SMTP_SSL_MODE=$CLO_SMTP_SSL_MODE
    fi

    if [ "$CLO_SMTP_USER_NAME" != "" ]; then
        SMTP_USER_NAME=$CLO_SMTP_USER_NAME
    fi

    if [ "$CLO_SMTP_PASSWORD" != "" ]; then
        SMTP_PASSWORD=$CLO_SMTP_PASSWORD
    fi

    if [ "$CLO_SMTP_DEBUG" != "" ]; then
        SMTP_DEBUG=$CLO_SMTP_DEBUG
    fi
}

set_message_broker()
{
    local instance="$1"

    if [ "$CLO_MESSAGE_BROKER_HOST" != "" ]; then
        MESSAGE_BROKER_HOST=$CLO_MESSAGE_BROKER_HOST
    fi

    if [ "$CLO_MESSAGE_BROKER_PORT" != "" ]; then
        MESSAGE_BROKER_PORT=$CLO_MESSAGE_BROKER_PORT
    fi

    if [ "$CLO_MESSAGE_BROKER_USER" != "" ]; then
        MESSAGE_BROKER_USER=$CLO_MESSAGE_BROKER_USER
    fi

    if [ "$CLO_MESSAGE_BROKER_PASS" != "" ]; then
        MESSAGE_BROKER_PASS=$CLO_MESSAGE_BROKER_PASS
    fi

    if [ "$CLO_MESSAGE_BROKER_VHOST" != "" ]; then
        MESSAGE_BROKER_VHOST=$CLO_MESSAGE_BROKER_VHOST
    fi
}

set_upload_path()
{
    local instance="$1"

    if [ "$CLO_UPLOAD_PATH" != "" ]; then
        UPLOAD_PATH=$CLO_UPLOAD_PATH
    else
        UPLOAD_PATH="$INSTANCE_PATH_BASE/$instance/$UPLOAD_DIR"
    fi
}

set_tmp_path()
{
    local instance="$1"

    if [ "$CLO_TMP_PATH" != "" ]; then
        TMP_PATH=$CLO_TMP_PATH
    else
        TMP_PATH="$INSTANCE_PATH_BASE/$instance/$TMP_DIR"
    fi
}

enable_sru_server()
{
    # remove the commenting symbols
    START_SRU_PUBLICSERVER=""
    END_SRU_PUBLICSERVER=""
    if [ "$SRU_SERVER_PORT" = "" ]; then
        # --sru-port not passed, use the default
        SRU_SERVER_PORT=$DEFAULT_SRU_SERVER_PORT
    fi
}

check_letsencrypt()
{
    if [ $(dpkg-query -W -f='${Status}' letsencrypt 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
        set +e
        apt-cache show letsencrypt &>/dev/null
        local aptcacheshow=$?
        set -e
        if [ $aptcacheshow -eq 0 ]; then
                read -r -p "The letsencrypt package is not installed. Do it now?  [y/N] " response
                if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
                    local debrelease="$(lsb_release -c -s)"
                    if [ $debrelease = "jessie" ]; then
                        apt-get install -y -t jessie-backports letsencrypt
                    else
                        apt-get install -y letsencrypt
                    fi
                else
                    die "You have to install letsencrypt to use the --letsencrypt parameter."
                fi
        else
            echo "No installation candidate available for package letsencrypt."
            if [[ -f /usr/bin/letsencrypt ]]; then
                read -r -p "If you have a symlink from /usr/bin/letsencrypt to letsencrypt-auto, it should work. [y/N] " response
                if [[ ! $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
                    die "You have to install letsencrypt to use the --letsencrypt parameter."
                fi
            else
                die "You can create a symlink from /usr/bin/letsencrypt to letsencrypt-auto."
            fi
        fi
    fi
}

letsencrypt_instance()
{
    # Get letsencrypt certificates
    letsencrypt --agree-tos --renew-by-default --webroot certonly \
        -w /usr/share/koha/opac/htdocs/ -d $opacdomain -w /usr/share/koha/intranet/htdocs/ -d $intradomain
    # enable all ssl settings (apache won't start with these before certs are present)
    sed -i "s:^\s*#\(\s*SSL.*\)$:\1:" "/etc/apache2/sites-available/$name.conf"
    # change port from 80 to 443. (apache won't start if it is 443 without certs present)
    sed -i "s:^\s*\(<VirtualHost \*\:\)80> #https$:\1443>:" "/etc/apache2/sites-available/$name.conf"
    # enable redirect from http to https on port 80
    sed -i "s:^\s*#\(.*\)#nohttps$:\1:" "/etc/apache2/sites-available/$name.conf"
    # make koha-list --letsencrypt aware of this instance # could be done by checking apache conf instead
    echo -e "opacdomain=\"$opacdomain\"\nintradomain=\"$intradomain\"" > /var/lib/koha/$name/letsencrypt.enabled
    # restart apache with working certs
    service apache2 restart
}

# Set defaults and read config file, if it exists.
DOMAIN=""
OPACPORT="80"
OPACPREFIX=""
OPACSUFFIX=""
INTRAPORT="8080"
INTRAPREFIX=""
INTRASUFFIX=""
DEFAULTSQL=""
ZEBRA_MARC_FORMAT="marc21"
ZEBRA_LANGUAGE="en"
ADMINUSER="1"
PASSWDFILE="/etc/koha/passwd"

# SMTP config
SMTP_HOST="localhost"
SMTP_PORT="25"
SMTP_TIMEOUT="120"
SMTP_SSL_MODE="disabled"
SMTP_USER_NAME=""
SMTP_PASSWORD=""
SMTP_DEBUG="0"

# Message broker (a.k.a. RabbitMQ) config
DEFAULT_MESSAGE_BROKER_PREFIX="koha_"
MESSAGE_BROKER_HOST="localhost"
MESSAGE_BROKER_PORT="61613"
MESSAGE_BROKER_USER="guest"
MESSAGE_BROKER_PASS="guest"
MESSAGE_BROKER_VHOST=""

# memcached variables
USE_MEMCACHED="yes"
MEMCACHED_SERVERS=""
MEMCACHED_PREFIX=""
# elasticsearch config
ELASTICSEARCH_SERVER="localhost:9200"
# hardcoded memcached defaults
DEFAULT_MEMCACHED_SERVERS="127.0.0.1:11211"
DEFAULT_MEMCACHED_PREFIX="koha_"
# hardcoded instance base path
INSTANCE_PATH_BASE="/var/lib/koha"
UPLOAD_DIR="uploads"
UPLOAD_PATH=""
# timezone defaults to empty
TIMEZONE=""
# hardcoded upload_tmp_path
TMP_DIR="tmp"
TMP_PATH=""
# cache base dir
CACHE_DIR_BASE="/var/cache/koha"
# Generate a randomizaed API secret
API_SECRET="$(pwgen -s 64 1)"
# SRU server variables
ENABLE_SRU="no"
SRU_SERVER_PORT=""
# hardcoded default SRU server port
DEFAULT_SRU_SERVER_PORT="7090"
START_SRU_PUBLICSERVER="<!--"
END_SRU_PUBLICSERVER="-->"

APACHE_CONFIGFILE=""

declare -a KEEP_COOKIE

if [ -e /etc/koha/koha-sites.conf ]
then
    . /etc/koha/koha-sites.conf
fi

[ $# -ge 1 ] && [ $# -le 16 ] || ( usage ; die "Error: wrong parameters" )

TEMP=`getopt -o chrpm:l:d:f:b:a: -l create-db,request-db,populate-db,use-db,enable-sru,sru-port:,help,marcflavor:,auth-idx:,biblio-idx:,zebralang:,defaultsql:,configfile:,passwdfile:,dbhost:,database:,elasticsearch-server:,adminuser:,memcached-servers:,memcached-prefix:,template-cache-dir:,timezone:,upload-path:,tmp-path:,smtp-host:,smtp-port:,smtp-timeout:,smtp-ssl-mode:,smtp-user-name:,smtp-password:,smtp-debug,mb-host:,mb-port:,mb-user:,mb-pass:,mb-vhost:,letsencrypt,keep-cookie:, \
     -n "$0" -- "$@"`

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

# Temporary variables for the command line options
CLO_ZEBRA_MARC_FORMAT=""
CLO_ZEBRA_LANGUAGE=""
CLO_DEFAULTSQL=""
CLO_ADMINUSER=""
CLO_MEMCACHED_SERVERS=""
CLO_MEMCACHED_PREFIX=""
CLO_ELASTICSEARCH_SERVER=""
CLO_UPLOAD_PATH=""
CLO_TMP_PATH=""
CLO_LETSENCRYPT=""
CLO_TEMPLATE_CACHE_DIR=""
CLO_TIMEZONE=""
CLO_SMTP_HOST=""
CLO_SMTP_PORT=""
CLO_SMTP_TIMEOUT=""
CLO_SMTP_SSL_MODE=""
CLO_SMTP_USER_NAME=""
CLO_SMTP_PASSWORD=""
CLO_SMTP_DEBUG=""

CLO_MESSAGE_BROKER_HOST=""
CLO_MESSAGE_BROKER_PORT=""
CLO_MESSAGE_BROKER_USER=""
CLO_MESSAGE_BROKER_PASS=""
CLO_MESSAGE_BROKER_VHOST=""

while true ; do
    case "$1" in
        -c|--create-db)
            op=create ; shift ;;
        -r|--request-db)
            op=request ; shift ;;
        -p|--populate-db)
            op=populate ; shift ;;
        -u|--use-db)
            op=use ; shift ;;
        --memcached-servers)
            CLO_MEMCACHED_SERVERS="$2" ; shift 2 ;;
        --memcached-prefix)
            CLO_MEMCACHED_PREFIX="$2" ; shift 2;;
        --elasticsearch-server)
            CLO_ELASTICSEARCH_SERVER="$2" ; shift 2 ;;
        -m|--marcflavor)
            CLO_ZEBRA_MARC_FORMAT="$2" ; shift 2 ;;
        -l|--zebralang)
            CLO_ZEBRA_LANGUAGE="$2" ; shift 2 ;;
        -d|--defaultsql)
            CLO_DEFAULTSQL="$2" ; shift 2 ;;
        -f|--configfile)
            configfile="$2" ; shift 2 ;;
        -s|--passwdfile)
            CLO_PASSWDFILE="$2" ; shift 2 ;;
        -b|--database)
            CLO_DATABASE="$2" ; shift 2 ;;
        --dbhost)
            CLO_DBHOST="$2" ; shift 2 ;;
        -a|--adminuser)
            CLO_ADMINUSER="$2" ; shift 2 ;;
        --enable-sru)
            ENABLE_SRU="yes" ; shift ;;
        --keep-cookie)
            KEEP_COOKIE+=("$2"); shift 2;;
        --mb-host)
            CLO_MESSAGE_BROKER_HOST="$2" ; shift 2 ;;
        --mb-port)
            CLO_MESSAGE_BROKER_PORT="$2" ; shift 2 ;;
        --mb-user)
            CLO_MESSAGE_BROKER_USER="$2" ; shift 2 ;;
        --mb-pass)
            CLO_MESSAGE_BROKER_PASS="$2" ; shift 2 ;;
        --mb-vhost)
            CLO_MESSAGE_BROKER_VHOST="$2" ; shift 2 ;;
        --smtp-debug)
            CLO_SMTP_DEBUG="1" ; shift ;;
        --smtp-host)
            CLO_SMTP_HOST="$2" ; shift 2 ;;
        --smtp-port)
            CLO_SMTP_PORT="$2" ; shift 2 ;;
        --smtp-timeout)
            CLO_SMTP_TIMEOUT="$2" ; shift 2 ;;
        --smtp-ssl-mode)
            CLO_SMTP_SSL_MODE="$2" ; shift 2 ;;
        --smtp-user-name)
            CLO_SMTP_USER_NAME="$2" ; shift 2 ;;
        --smtp-password)
            CLO_SMTP_PASSWORD="$2" ; shift 2 ;;
        --sru-port)
            SRU_SERVER_PORT="$2" ; shift 2 ;;
        --template-cache-dir)
            CLO_TEMPLATE_CACHE_DIR="$2" ; shift 2 ;;
        --timezone)
            CLO_TIMEZONE="$2" ; shift 2 ;;
        --upload-path)
            CLO_UPLOAD_PATH="$2" ; shift 2 ;;
        --tmp-path)
            CLO_TMP_PATH="$2" ; shift 2 ;;
        --letsencrypt)
            CLO_LETSENCRYPT="yes" ; shift ;;
        -h|--help)
            usage ; exit 0 ;;
        --)
            shift ; break ;;
        *)
            die "Internal error processing command line arguments" ;;
    esac
done

# Load the configfile given on the command line
if [ "$configfile" != "" ]
then
    if [ -e "$configfile" ]
    then
        . "$configfile"
    else
        die "$configfile does not exist.";
    fi
fi

# Make sure options from the command line get the highest precedence
if [ "$CLO_ZEBRA_MARC_FORMAT" != "" ]
then
    ZEBRA_MARC_FORMAT="$CLO_ZEBRA_MARC_FORMAT"
fi
if [ "$CLO_ZEBRA_LANGUAGE" != "" ]
then
    ZEBRA_LANGUAGE="$CLO_ZEBRA_LANGUAGE"
fi
if [ "$CLO_DEFAULTSQL" != "" ]
then
    DEFAULTSQL="$CLO_DEFAULTSQL"
fi
if [ "$CLO_ADMINUSER" != "" ]
then
    ADMINUSER="$CLO_ADMINUSER"
fi
if [ "$CLO_PASSWDFILE" != "" ]
then
    PASSWDFILE="$CLO_PASSWDFILE"
fi

if [ "$CLO_TIMEZONE" != "" ]; then
    TIMEZONE=$CLO_TIMEZONE
fi

if [ "${CLO_ELASTICSEARCH_SERVER}" != "" ]; then
    ELASTICSEARCH_SERVER="${CLO_ELASTICSEARCH_SERVER}"
fi

BCRYPT_SETTINGS=$(htpasswd -bnBC 10 "" password | tr -d ':\n' | sed 's/$2y/$2a/');


if [ "$ENABLE_SRU" != "no" ]; then
    enable_sru_server
fi

[ $# -ge 1 ] || ( usage ; die "Missing instance name..." )

name="$1"

set_smtp
set_upload_path $name
set_tmp_path $name

if [ "$op" = use ] && [ "$CLO_DATABASE" = "" ] &&
   ( [ ! -f "$PASSWDFILE" ] || [ ! `cat $PASSWDFILE | grep "^$name:"` ] )
then
    cat <<NO_DB
--use-db must have a database name. It can be specified in a readable
password file ($PASSWDFILE). Using --passwdfile overrides the default
/usr/koha/passwd file. Each line of a passwd file should be in the format of:
    instance:username:password:dbname:dbhost
A database name can also be specified using '--database dbname'.
NO_DB
    die;
fi

if [ "$USE_MEMCACHED" = "no" ]; then
    MEMCACHED_SERVERS=""
    MEMCACHED_NAMESPACE=""
    MEMCACHED_PREFIX=""
else
    set_memcached $name
fi

set_message_broker $name

# Set template cache dir
if [ "$CLO_TEMPLATE_CACHE_DIR" != "" ]; then
    TEMPLATE_CACHE_DIR="$CLO_TEMPLATE_CACHE_DIR"
else
    TEMPLATE_CACHE_DIR="$CACHE_DIR_BASE/$name/templates"
fi

# Are we root? If not, the mod_rewrite check will fail and be confusing, so
# we look into this first.
if [[ $UID -ne 0 ]]
then
    die "This script must be run with root privileges."
fi

# Check everything is ok with Apache, die otherwise
check_apache_config

opacdomain="$OPACPREFIX$name$OPACSUFFIX$DOMAIN"
intradomain="$INTRAPREFIX$name$INTRASUFFIX$DOMAIN"

# Check everything is ok with letsencrypt, die otherwise
if [ "$CLO_LETSENCRYPT" = "yes" ]; then
    check_letsencrypt
fi

if [ -f $PASSWDFILE ] && [ `cat $PASSWDFILE | grep "^$name:"` ]
then
    passwdline=`cat $PASSWDFILE | grep "^$name:"`
    mysqluser=`echo $passwdline | cut -d ":" -f 2`
    mysqlpwd=`echo $passwdline | cut -d ":" -f 3`
    mysqldb=`echo $passwdline | cut -d ":" -f 4`
    mysqlhost=`echo $passwdline | cut -d ":" -f 5`
fi

# The order of precedence for MySQL database name is:
# default < passwd file < command line
if [ "$mysqldb" = "" ]
then
    mysqldb="koha_$name"
fi

if [ "$CLO_DATABASE" != "" ]
then
    mysqldb="$CLO_DATABASE"
fi

if [ "$mysqluser" = "" ]
then
    mysqluser="koha_$name"
fi

if [ "$CLO_DBHOST" != "" ]
then
    mysqlhost="$CLO_DBHOST"
fi

if [ "$mysqlhost" = "" ]
then
    mysqlhost="$(getmysqlhost)"
fi

if [ "$op" = create ] || [ "$op" = request ] || [ "$op" = use ]
then
    if [ "$mysqlpwd" = "" ]
    then
        # Removing : ' & \ < > /
        mysqlpwd=$(pwgen -s -y -r ":'&\\<>/" 16 1)
    fi
else
    mysqlpwd="$(getinstancemysqlpassword $name)"
fi


if [ "$op" = create ] || [ "$op" = request ] || [ "$op" = use ]
then
    # Create new user and group.
    username="$name-koha"
    if getent passwd "$username" > /dev/null
    then
        die "User $username already exists."
    fi
    if getent group "$username" > /dev/null
    then
        die "Group $username already exists."
    fi
    adduser --no-create-home --disabled-password \
        --gecos "Koha instance $username" \
        --home "/var/lib/koha/$name" \
        --quiet "$username"

    # Create the site-specific directories.
    koha-create-dirs "$name"

    # Generate Zebra database password.
    zebrapwd="$(pwgen -s 16 1)"
    # Future enhancement: make this configurable for when your db is on
    # another server.
    mysql_hostname="localhost"
    # Set up MySQL database for this instance.
    if [ "$op" = create ]
    then
        if [ ! -e /etc/mysql/debian.cnf ]; then
            MYSQL_OPTIONS="-u root"
            echo "WARNING: The koha-common.cnf file is a dead soft link!"
        else
            MYSQL_OPTIONS="--defaults-extra-file=/etc/mysql/koha-common.cnf"
        fi
        mysql $MYSQL_OPTIONS <<eof
CREATE DATABASE \`$mysqldb\`;
CREATE USER \`$mysqluser\`@'$mysql_hostname' IDENTIFIED BY '$mysqlpwd';
GRANT ALL PRIVILEGES ON \`$mysqldb\`.* TO \`$mysqluser\`@'$mysql_hostname';
FLUSH PRIVILEGES;
eof
    fi #`

    if [ "$CLO_LETSENCRYPT" = "yes" ]; then
        APACHE_CONFIGFILE="apache-site-https.conf.in"
    else
        APACHE_CONFIGFILE="apache-site.conf.in"
    fi
    # Generate and install Apache site-available file and log dir.
    generate_config_file $APACHE_CONFIGFILE \
        "/etc/apache2/sites-available/$name.conf"
    mkdir "/var/log/koha/$name"
    chown "$username:$username" "/var/log/koha/$name"


    # Generate and install main Koha config file.
    generate_config_file koha-conf-site.xml.in \
        "/etc/koha/sites/$name/koha-conf.xml"

    # Generate and install the log4perl config file.
    generate_config_file log4perl-site.conf.in \
        "/etc/koha/sites/$name/log4perl.conf"

    # Generate and install Zebra config files.
    generate_config_file zebra-biblios-dom-site.cfg.in \
        "/etc/koha/sites/$name/zebra-biblios-dom.cfg"
    generate_config_file zebra-authorities-dom-site.cfg.in \
        "/etc/koha/sites/$name/zebra-authorities-dom.cfg"
    generate_config_file zebra.passwd.in \
        "/etc/koha/sites/$name/zebra.passwd"

    # Create a GPG-encrypted file for requesting a DB to be set up.
    if [ "$op" = request ]
    then
        touch "$name-db-request.txt"
        chmod 0600 "$name-db-request.txt"
        cat > "$name-db-request.txt" << eof
Please create a MySQL database and user on $mysqlhost as follows:

database name: $mysqldb
database user: $mysqluser
     password: $mysqlpwd

Thank you.
eof

        echo "See $name-db-request.txt for database creation request."
        echo "Please forward it to the right person, and then run"
        echo "$0 --populate-db $name"
        echo "Thanks."
    fi
fi


if [ "$op" = create ] || [ "$op" = populate ]
then
    # Re-fetch the passwords from the config we've generated, allows it
    # to be different from what we set, in case the user had to change
    # something.
    mysqluser=$(getinstancemysqluser $name)
    mysqldb=$(getinstancemysqldatabase $name)
    # Use the default database content if that exists.
    if [ -e "$DEFAULTSQL" ]
    then
        # Populate the database with default content.
        zcat -f "$DEFAULTSQL" |
        sed "s/__KOHASITE__/koha_$name/g" |
        mysql --host="$mysqlhost" --user="$mysqluser" --password="$mysqlpwd" "$mysqldb"


        # Change the default user's password.
        staffpass="$(pwgen 12 1)"
        staffdigest=$(echo -n "$staffpass" |
                      perl -e '
                            use Digest::MD5 qw(md5_base64); 
                            while (<>) { print md5_base64($_), "\n"; }')
        mysql --host="$mysqlhost" --user="$mysqluser" \
--password="$mysqlpwd" <<eof
USE \`$mysqldb\`;
UPDATE borrowers 
SET password = '$staffdigest' 
WHERE borrowernumber = $ADMINUSER;
eof
        #`
        echo "staff user password is '$staffpass' but keep that secret"

        # Upgrade the database schema, just in case the dump was from an 
        # old version.
        koha-upgrade-schema "$name"
    else
        echo "Koha instance is empty, no staff user created."
    fi
fi


if [ "$op" = create ] || [ "$op" = populate ] || [ "$op" = use ]
then
    # Reconfigure Apache.
    if ! {
        a2ensite "$name" > /dev/null 2>&1 ||
            a2ensite "${name}.conf" > /dev/null 2>&1
    }; then
        echo "Warning: problem enabling $name in Apache" >&2
    fi
    service apache2 restart

    # Start Zebra.
    koha-zebra --start "$name"

    # Start workers
    for queue in $(get_worker_queues); do
        koha-worker --queue $queue --start "$name"
    done

    if [ "$USE_INDEXER_DAEMON" = "yes" ]; then
        # Start Indexer daemon
        koha-indexer --start "$name"
    fi

    if [ "$CLO_LETSENCRYPT" = "yes" ]; then
        # Get letsencrypt certificates
        letsencrypt_instance
    fi

    chown $username:$username /var/log/koha/$name/*.log
fi


if [ "$op" = request ]
then
    koha-disable "$name"
fi

echo <<eoh

Email for this instance is disabled. When you're ready to enable it, use:
koha-email-enable $name
eoh
