#!/usr/bin/env bash
# Extract the installed Nextcloud version from config.php and compare it
# with the version of the code on disk (version.php).
# if match 29.* try to upgrade to 34

NC_ROOT="/usr/share/nextcloud"
CONFIG="$NC_ROOT/config/config.php"
VERSION_PHP="$NC_ROOT/version.php"

if [ ! -r "$CONFIG" ]; then
    echo "Cannot read $CONFIG (try running with sudo)" >&2
    exit 1
fi

# Installed version, as recorded in config.php
installed=$(sed -n "s/^[[:space:]]*'version'[[:space:]]*=>[[:space:]]*'\([^']*\)'.*/\1/p" "$CONFIG" | head -n1)

# Code version on disk, from version.php ($OC_Version = array(29,0,7,1);)
code=""
if [ -r "$VERSION_PHP" ]; then
    code=$(sed -n 's/.*\$OC_Version[[:space:]]*=[[:space:]]*array(\([0-9, ]*\)).*/\1/p' "$VERSION_PHP" \
        | head -n1 | tr -d ' ' | tr ',' '.')
fi

echo "Installed version (config.php): ${installed:-not found}"
echo "Code version (version.php):     ${code:-not found}"

if [ -n "$installed" ] && [ -n "$code" ]; then
    if [ "$installed" = "$code" ]; then
        echo "OK: versions match."
    else
        echo "MISMATCH: an upgrade is probably pending (run: sudo -u www-data php occ upgrade)."    
        if [[ "$installed" == 29.* ]]; then
            echo "OK: $installed matches 29.* try upgrade"
            # start mysql if required
            systemctl start mysql
            /var/lib/dpkg/info/nextcloud.preinst upgrade "$installed"
            dpkg-reconfigure kwartz-nextcloud
        else
            echo "NOT 29.*: found ${installed:-nothing}"
        fi
    fi
fi
