#!/bin/sh

set -e

case $1 in
    configure)
        # Add the "orthanc" user
        if ! getent passwd orthanc > /dev/null; then
            adduser --system --quiet \
                    --home /var/lib/orthanc --no-create-home \
                    --shell /bin/bash --group --gecos "Orthanc Administrator" orthanc
        fi
        if test "`id -u orthanc`" -eq 0; then
            echo "The orthanc administrative user must not be root." >&2
            false
        fi
        if test "`id -g orthanc`" -eq 0; then
            echo "The orthanc administrative group must not be root." >&2
            false
        fi

        # Configure the permissions of the working directories
        chown orthanc:orthanc /var/lib/orthanc
        chown orthanc:orthanc /var/log/orthanc

	chmod 0750 /var/lib/orthanc
	chmod 0750 /var/log/orthanc
	
	# The "credentials.json" contains unencrypted sensitive
	# configuration options ("RegisteredUsers"): It must only be
	# readble by the users running Orthanc.
        chown root:orthanc /etc/orthanc/credentials.json
        chmod 0640 /etc/orthanc/credentials.json

        # Make sure the en_US.UTF-8 locale has been generated
        # (required for case-insensitive comparison of strings with
        # accents).  Note that the call "locale-gen en_US.UTF-8" that
        # was used in versions <= 1.9.7+dfsg-4 of this package only
        # worked on Ubuntu.
	sed -i 's/^# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/g' /etc/locale.gen
	locale-gen
	update-locale

	# Start the Orthanc service after installation
        # https://www.debian.org/doc/debian-policy/ch-opersys.html#s9.3.3.2
	if [ -x /etc/init.d/orthanc ]; then
           if which invoke-rc.d >/dev/null 2>&1; then
               invoke-rc.d orthanc start
           else
               /etc/init.d/orthanc start
           fi
        fi
	;;

    triggered)
	if [ "$2" = "orthanc-restart-trigger" ] ; then
	    echo "orthanc-restart-trigger: restarting the Orthanc service" >&2
	    # Restart the Orthanc service if the "orthanc-restart-trigger" dpkg trigger
            # is activated by some of the plugin package (cf. Debian issue #1003314)
            # https://wiki.debian.org/DpkgTriggers
            # https://stackoverflow.com/a/15276537
            # https://web.archive.org/web/20111022012105/http://www.seanius.net/blog/2009/09/dpkg-triggers-howto/
	    if [ -x /etc/init.d/orthanc ]; then
		if which invoke-rc.d >/dev/null 2>&1; then
		    invoke-rc.d orthanc restart
		else
		    /etc/init.d/orthanc restart
		fi
            fi
	else
	    echo "unknown trigger in orthanc.postinst: $2" >&2
	    exit 1
	fi
	;;

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

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

#DEBHELPER#
