#!/bin/sh
#
# Script that runs after an upgrade to the Noblogs Docker image, to
# update the database schema.
#
# It detects if an upgrade needs to be run by looking at the Wordpress
# version, and the contents of the guard file
# /opt/noblogs/data/.noblogs_db_schema_version.

guard_file=/opt/noblogs/www/wp-content/blogs.dir/.db_schema_version
wp_version_file=/opt/noblogs/www/wp-includes/version.php

cur_schema_version=0
if [ -e $guard_file ]; then
    cur_schema_version=`cat $guard_file`
fi

if [ ! -e $wp_version_file ]; then
    echo "Error: Wordpress version.php not found in $wp_version_file" >&2
    exit 1
fi

new_schema_version=`awk '$1 == "$wp_db_version" {print $3}' < $wp_version_file | tr -d ';'`
if [ -z "$new_schema_version" ]; then
    echo "Error: failed to parse db schema version from version.php" >&2
    exit 1
fi

echo "Wordpress database schema: cur=${cur_schema_version}, new=${new_schema_version}"

if [ $cur_schema_version -lt $new_schema_version ]; then
    echo "Wordpress database upgrade required!"
    on-local-blogs upgrade

    # Note: we'd really like to exit on failure here, but we're not
    # sure we can trust the exit status code of that PHP script...

    echo "Wordpress database upgrade done"

    echo $new_schema_version > $guard_file

    noblogs remove-network-upgrade-message

    echo "network upgrade message removed"
fi

exit 0