#!/bin/bash

function OCC
{
    params=$@;
    source /opt/rh/rh-php73/enable
    cd /usr/share/nextcloud/
    TERM=dumb runuser -s /bin/bash apache -c "php -dmemory_limit=512M ./occ $params"
}

password=`perl -e "use NethServer::Password; print NethServer::Password::store('nextcloud');"`

# initialize grants mysql nextcloud database
/usr/bin/mysql --defaults-file=/root/.my.cnf -e "CREATE DATABASE IF NOT EXISTS nextcloud;"
/usr/bin/mysql --defaults-file=/root/.my.cnf -e "grant all on nextcloud.* to 'nextcloud'@'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 = 'nextcloud'" | tail -n1`;

if [[ $res == '0' ]]; then
    OCC "maintenance:install --database mysql --database-name nextcloud --database-user nextcloud --database-pass $password --admin-user admin --admin-pass  Nethesis,1234 --data-dir /var/lib/nethserver/nextcloud/"

    OCC "app:enable user_ldap"
    OCC "ldap:create-empty-config" # create 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

    # Disable mail app when upgrading from NC 19: https://github.com/nextcloud/mail/issues/3727
    if OCC app:list | grep -q -- '- mail:'; then
        echo "[NOTICE] Disabling mail app"
        OCC app:disable mail
    fi
    echo "[NOTICE] Disabling theme app"
    OCC app:disable theming

    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
    OCC "db:add-missing-indices"
fi
