#!/bin/sh

set -e

case "$1" in
    install|upgrade|configure)
        # If abi 4.0 is not present, then remove the apparmor profile config
        if [ ! -e /etc/apparmor.d/abi/4.0 ]; then
            rm -f /etc/apparmor.d/usr.bin.coolwsd
        fi
        ;;
esac

case "$1" in
    configure)
	if [ -f /etc/loolwsd/loolwsd.xml ]; then /usr/bin/coolconfig migrateconfig --write || true; fi

	adduser --quiet --system --group --home /opt/cool cool
	chown cool: /etc/coolwsd/coolwsd.xml
	chmod 640 /etc/coolwsd/coolwsd.xml

	# We assume that the LibreOffice to be used is built TDF-style
	# and installs in @LO_PATH@, and that /opt/cool is
	# on the same file system

	rm -rf /opt/cool || true
	mkdir -p /opt/cool/child-roots /opt/cool/cache
	chown cool: /opt/cool
	chown cool: /opt/cool/child-roots
	chown cool: /opt/cool/cache

	fc-cache @LO_PATH@/share/fonts/truetype

	coolwsd-systemplate-setup /opt/cool/systemplate @LO_PATH@ >/dev/null 2>&1
	coolconfig generate-proof-key >/dev/null 2>&1
    cat << EOF > /etc/apt/apt.conf.d/25coolwsd
// Rebuild systemplate of @APP_NAME@
DPkg::Post-Invoke { "echo Updating coolwsd systemplate;coolwsd-systemplate-setup /opt/cool/systemplate @LO_PATH@ >/dev/null 2>&1 || true"; };
EOF
	;;

esac

#DEBHELPER#
