Cron job to maintain nextcloud

Don’t forget to add your topic to the Howto/FAQ Wiki!

Hi.

I am using this script on my test nextcloud instance. I hope others might get good use for it. In production I initiates manually whenever my daily verification of test instance is as desired. So this script exists on both test and production instance.

To clarify a few important things before just implementing this script as is:
I am running scheduled ZFS snapshotting each day with an automatic retention of 14 days, which is the ONLY reason I use the --no-backup parameter. However if I did not use the no-backup, then also because of ZFS, the backup procedure would be okay fast, but the cleanup of temporary files (the backup created by NC updater) would take forever, because delete operations of large bulks of data, is a pain on transactional filesystems.

#! /bin/bash
rm tmp.txt
SQLFILE="/path/to/dumps/nc-$(date +"%Y-%m-%d_%M-%H")"

mysqldump --opt --user='NCUSER' --password='NCUSERPASS' 'NCDATABASE' > "$SQLFILE.sql"
gzip -c "$SQLFILE.sql" > "$SQLFILE.gz"

#sudo -u www-data php8.1 /var/www/nextcloud/occ maintenance:mode --on
#gzip -r /var/www/nextcloud/data/* "ncbackup-$(date +"%Y-%m-%d_%M-%H").gz"

#If any JSON returned from status url, server is running and returns no internal error
#Add appcode and basic auth to CURL and recieve proper status to use for more advanced stuff.
curl https://cloud.yourdomain.ltd/ocs/v2.php/apps/serverinfo/api/v1/info?format=json > tmp.txt
if  grep -q '{"ocs":{"meta":{"status":"failure","statuscode":401,"message":null},"data":{"message":"Unauthorized"}}}' "tmp.txt" ; then
        rm tmp.txt 
        apt-get update -y
        apt-get upgrade -y

        PHPCOMMAND="sudo -u www-data php8.1" #Keep PHP version up to date when you migrates to newer PHP version!!
        commands[0]="/var/www/nextcloud/updater/updater.phar --no-backup --no-interaction"
        commands[1]="/var/www/nextcloud/occ db:add-missing-indices"
        commands[2]="/var/www/nextcloud/occ maintenance:mode --off"
        commands[3]="/var/www/nextcloud/occ maintenance:data-fingerprint"
        commands[4]="/var/www/nextcloud/occ app:update --all"

        for i in "${commands[@]}"; do eval $PHPCOMMAND $i; done

        systemctl restart php8.1-fpm #Keep PHP version up to date when you migrates to newer PHP version!!
        systemctl restart apache2
else
        rm tmp.txt
        echo 'server not running' ; 
fi