#!/bin/bash

function OCC
{
    params=$@;
    source /opt/remi/php73/enable
    cd /usr/share/nextcloud/
    TERM=dumb /usr/bin/OCC $params
}

# check if inodb is enabled for up to SME9, if not do it.
innodb=$(/sbin/e-smith/db configuration getprop mysqld InnoDB || echo "disabled")
if [[ "$innodb" != "enabled" ]]; then
    /sbin/e-smith/db configuration setprop mysqld InnoDB enabled
    /sbin/e-smith/expand-template /etc/my.cnf
    sv t /service/mysqld
    sleep 8
fi

# important configuration variables
password=`/sbin/e-smith/db configuration getprop nextcloud DbPassword || echo "missing"`
dbname=`/sbin/e-smith/db configuration getprop nextcloud DbName || echo "nextcloud"`
dbuser=`/sbin/e-smith/db configuration getprop nextcloud DbUser || echo "nextcloud"`
adminuser=`/sbin/e-smith/db configuration getprop nextcloud AdminUser || echo "admin"`
adminpass=`/sbin/e-smith/db configuration getprop nextcloud AdminPassword ||/sbin/e-smith/db configuration getprop sysconfig SystemID  || echo "password;109"`

# initialize grants mysql nextcloud database
/usr/bin/mysql --defaults-file=/root/.my.cnf -e "CREATE DATABASE IF NOT EXISTS $dbname;"
/usr/bin/mysql --defaults-file=/root/.my.cnf -e "grant all on $dbname.* to '$dbuser'@'localhost' identified by '$password';"
/usr/bin/mysql --defaults-file=/root/.my.cnf -e "FLUSH PRIVILEGES"

# check if we are migrating from release 10 to 11
if [ -f /var/www/html/nextcloud/config/config.php ]; then
    mv /var/www/html/nextcloud/config/config.php /usr/share/nextcloud/config/config.php
    rm -rf /var/www/html/nextcloud/
fi

res=`/usr/bin/mysql --defaults-file=/root/.my.cnf -e "select count(*) from information_schema.tables where table_type = 'BASE TABLE' and table_schema = '$dbname'" | tail -n1`;

if [[ $res == '0' ]]; then
    OCC "maintenance:install --database mysql --database-name $dbname --database-user $dbuser --database-pass $password --admin-user $adminuser --admin-pass  $adminpass --data-dir /home/e-smith/files/nextcloud/data/"

    OCC "app:enable user_ldap"
    OCC "ldap:create-empty-config" # create config with empty id
    OCC "ldap:create-empty-config" # create config with id s01
    OCC "ldap:delete-config ''" # delte config with empty id
else
    # to satisfy code integrity check
    if [ -f /usr/share/nextcloud/.htaccess.rpmsave ]; then
        rm -f /usr/share/nextcloud/.htaccess.rpmsave
    fi
    if [ -f /usr/share/nextcloud/.htaccess.rpmnew ]; then
        rm -f /usr/share/nextcloud/.htaccess.rpmnew
    fi
    OCC "maintenance:mode --on"
    OCC "upgrade"
    OCC "maintenance:mode --off"
    OCC "integrity:check-core"
    # Catch 'Nextcloud is already latest version' message
    if [ $? -eq 3 ]; then
        exit 0
    fi
fi
