#!/bin/sh
# postinst script for nextcloud-server
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

export APACHE2_MAINTSCRIPT_HELPER_QUIET=1

case "$1" in
configure)

    # Apache conf
    if [ "a2query -c nextcloud"=~"No conf matches nextcloud" ]; then
        a2enconf nextcloud || true
        apache2ctl restart || true
    fi

    # Apache modules
    if [ -e /usr/share/apache2/apache2-maintscript-helper ]; then
        . /usr/share/apache2/apache2-maintscript-helper
        apache2_invoke enmod rewrite || exit $?
        apache2_invoke enmod headers || exit $?
        apache2_invoke enmod env || exit $?
        apache2_invoke enmod dir || exit $?
        apache2_invoke enmod mime || exit $?
    fi

    if [ "$(su 'www-data' -s /bin/sh -c 'php /var/www/nextcloud/occ status' | grep 'installed:' | cut -f2 -d ':' | xargs)" = "false" ]; then
        echo "Nextcloud is not configured, please use open web browser http://<your_server_ip>/nextcloud"
        echo "After configure please run  su 'www-data' -s /bin/sh -c 'php /var/www/nextcloud/occ config:system:set --value true upgrade.disable-web'"
    elif [ "$(su 'www-data' -s /bin/sh -c 'php /var/www/nextcloud/occ status' | grep 'installed:' | cut -f2 -d ':' | xargs)" = "true" ]; then
        su 'www-data' -s /bin/sh -c 'php /var/www/nextcloud/occ upgrade'
        su 'www-data' -s /bin/sh -c 'php /var/www/nextcloud/occ db:add-missing-indices'
        su 'www-data' -s /bin/sh -c 'php /var/www/nextcloud/occ config:system:set --value true upgrade.disable-web' >/dev/null || true
    else
        echo "Got unexpect answer, occ status can't to read satus of nextcloud. Check php installation."
    fi

    ;;

abort-upgrade | abort-remove | abort-deconfigure) ;;

\
    *)
    echo "postinst called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0