#!/bin/bash
source /opt/rh/rh-mariadb105/enable

function OCC
{
    params=$@;
    source /opt/remi/php80/enable
    cd /usr/share/nextcloud/
    TERM=dumb runuser -s /bin/bash apache -c "php -d memory_limit=1024M -d apc.enable_cli=1 ./occ $params"
}

exitOnError () {
    echo $1
    OCC "app:enable accessibility"
    exit 1
}

databaseTest () {
    out=$(mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -BN -e "select count(*) from information_schema.tables where table_type = 'BASE TABLE' and table_schema = 'nextcloud'")
    if [[ $((out)) -gt "0" ]]; then
        return 1
    else
        return 0
    fi
}

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

systemctl is-active --quiet rh-mariadb105-mariadb@nextcloud
if [[ $? -ne 0 ]]; then
    systemctl start rh-mariadb105-mariadb@nextcloud
    max_wait=20
    wait=0
    while ! mysql --socket /run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "SHOW DATABASES" 2>/dev/null; do
        sleep 1
        wait=$((wait+1))
        if [[ $wait -ge $max_wait ]]; then
            echo "[ERROR] Can't start rh-mariadb105-mariadb@nextcloud"
            exit 1
        fi
    done
fi
# verify if the db exists and if mysql is installed
database=""
if [[ -x '/usr/bin/mysql' ]]; then
    database=$(/usr/bin/mysql -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'nextcloud'")
fi

if [[ -n $database ]]; then
    # we still use mariadb55, this is wrong we need rh-mariadb105

    # Make sure loglevel is set to 2 (see https://github.com/nextcloud/server/pull/27334)
    OCC "config:system:set loglevel --value=2 --type=integer"
    OCC "maintenance:mode --on"
    # accessibility takes a lot of PHP ressources but is a mandatory 
    # else white NC dashboard (nextcloud/server#25742)
    OCC "app:disable accessibility"

    tmp_sql=`mktemp`
    trap "rm -f $tmp_sql" EXIT

    # Dump the mariadb55 nextcloud database or exit on error
    /usr/bin/mysqldump --databases nextcloud > $tmp_sql
    if [[ $? -ne 0 ]]; then
        exitOnError "[ERROR] Error while dumping nextcloud database from mariadb55"
    fi
 
    # We got the dump or exit on error
    if [[ ! -f $tmp_sql ]]; then
        exitOnError "[ERROR] There is no dumped nextcloud database"
    fi
 
    # Create the database in rh-mariadb105 and import the dump from mariadb55 or exit on error
    mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "CREATE DATABASE IF NOT EXISTS nextcloud;"
    mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock --database nextcloud < $tmp_sql
    if [[ $? -ne 0 ]]; then
        exitOnError "[ERROR] Error while restoring nextcloud database to SCL mariadb105"
    fi
 
    # we need to upgrade mariadb55 to mariadb105 or exit on error 
    # https://access.redhat.com/documentation/en-us/red_hat_software_collections/3/html/3.3_release_notes/chap-migration
    mysql_upgrade --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock --force
    if [[ $? -ne 0 ]]; then
        exitOnError "[ERROR] Error while upgrading nextcloud database"
    fi
 
    # rh-mariadb105 is created,migrated,updated we can remove mariadb55 and use the socket in nextcloud for the new database
    # we test if the nextcloud database from SCL is not blank or wrong

    if  ! databaseTest ; then
        OCC config:system:set dbhost --value="localhost:/run/rh-mariadb105-mariadb/nextcloud-mysql.sock" --type="string"
        if [[ $? -gt 0 ]]; then
             exitOnError "[ERROR] Can't configure socket for mysql database"
        fi
        /usr/bin/mysql -e "drop database nextcloud;"

        # Alter database for migration
        mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "ALTER DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"
        mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "grant all on nextcloud.* to 'nextcloud'@'localhost' identified by '$password';"
        mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "FLUSH PRIVILEGES"
        #Enabling MySQL 4-byte support
        OCC "config:system:set mysql.utf8mb4 --type boolean --value='true'"
        OCC "maintenance:repair"
        OCC "db:add-missing-primary-keys"
        OCC "db:add-missing-columns"
        # Enable back accessibility
        OCC "app:enable accessibility"
    fi
else
    # initialize grants mysql nextcloud database
    mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "CREATE DATABASE IF NOT EXISTS nextcloud;"
    mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "ALTER DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"
    mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "grant all on nextcloud.* to 'nextcloud'@'localhost' identified by '$password';"
    mysql --socket=/run/rh-mariadb105-mariadb/nextcloud-mysql.sock -e "FLUSH PRIVILEGES"
fi

# 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

# we test if the nextcloud database from SCL is not initialized or workable

if databaseTest ; then
    OCC "maintenance:install --database mysql --database-name nextcloud --database-user nextcloud --database-pass $password --database-host=localhost:/run/rh-mariadb105-mariadb/nextcloud-mysql.sock --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

    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
