#!/bin/sh
set -e

. /usr/share/debconf/confmodule

detect_webservers()
{
    WEB_SERVERS=""

    if dpkg-query -W -f='${Status}' apache2 2>/dev/null |
        grep -q 'install ok installed'; then
        WEB_SERVERS="$WEB_SERVERS apache2"
    fi

    if dpkg-query -W -f='${Status}' nginx 2>/dev/null |
        grep -q 'install ok installed'; then
        WEB_SERVERS="$WEB_SERVERS nginx"
    fi

    if dpkg-query -W -f='${Status}' lighttpd 2>/dev/null |
        grep -q 'install ok installed'; then
        WEB_SERVERS="$WEB_SERVERS lighttpd"
    fi

    WEB_SERVERS="${WEB_SERVERS# }"
}

db_get yms/db-name
DB_NAME="$RET"

db_get yms/db-user
DB_USER="$RET"

db_get yms/db-password
DB_PASSWORD="$RET"

echo "Configuring YMS..."
echo "Checking MariaDB database '${DB_NAME}'..."

if mariadb -N -B -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${DB_NAME}'" | grep -Fxq "${DB_NAME}"; then
    echo "Database '${DB_NAME}' already exists."
else
    echo "Database '${DB_NAME}' does not exist."
    echo "Creating database '${DB_NAME}'..."
    mariadb -e "CREATE DATABASE \`${DB_NAME}\`"
    echo "Database '${DB_NAME}' created."
    echo "Initializing database schema..."
    mariadb "${DB_NAME}" < /usr/share/yms/db/mariadb.sql
    mariadb "${DB_NAME}" < /usr/share/yms/db/minimal.sql
    echo "Database schema initialized."
    mariadb -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASSWORD}'"
    mariadb -e "GRANT SELECT, INSERT, UPDATE, DELETE ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost'"
fi

echo "Initializing document storage..."
if ! getent group yms >/dev/null; then
    addgroup --system yms
fi
if ! id -nG www-data | tr ' ' '\n' | grep -qx yms; then
    adduser www-data yms
fi
mkdir -p /var/lib/yms/thumb
chown -R www-data:yms /var/lib/yms

db_get yms/webgui
if [ "$RET" = "true" ]; then

    detect_webservers
    case "$WEB_SERVERS" in
    "")
        echo "No supported webserver installed."
        ;;
    apache2)
        echo "Apache detected."
        a2enconf yms
        invoke-rc.d apache2 reload
        echo "Web GUI for apache2 enabled."
        ;;
    nginx)
        echo "nginx detected."
        ;;
    lighttpd)
        echo "lighttpd detected."
        ;;
    *)
        echo "Multiple webservers detected: $WEB_SERVERS"
        ;;
    esac

    if [ ! -f /etc/yms/config.inc ]; then
        # create initial configuration
        sed \
            -e "s|@DB_USERNAME@|$DB_USER|g" \
            -e "s|@DB_PASSWORD@|$DB_PASSWORD|g" \
            -e "s|@DB_SCHEMA@|$DB_NAME|g" \
            /usr/share/yms/config.inc-sample \
            > /etc/yms/config.inc
        chmod 0640 /etc/yms/config.inc
        chown root:www-data /etc/yms/config.inc
        ln -s /etc/yms/config.inc /usr/share/yms/webgui/config.inc
    fi

fi

exit 0
