#!/bin/bash
#
# 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 http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

. /opt/open-xchange/lib/oxfunctions.sh

postFix() {
    local version=${1%-*}
    version=${version//[-.]/}

    # prevent bash from expanding, see bug 13316
    GLOBIGNORE='*'

    odir=/opt/open-xchange/etc/groupware/contacts-ldap
    ndir=/opt/open-xchange/etc/contacts-ldap
    for i in $(find $odir -maxdepth 1 -name "mapping*.properties"); do
        cp -a $i $ndir/$(basename $i) && rm $i || true
    done
    for i in $(find $odir -name "[0-9]*" -type d); do
        npropdir=$ndir/$(basename $i)
        if [ ! -d $npropdir ]; then
            mkdir $npropdir
            ox_update_permissions "$npropdir" root:open-xchange 750
        fi
        for prop in $(find $i -name "*.properties"); do
            cp -a $prop $npropdir && rm $prop || true
        done
    done

    # SoftwareChange_Request-1080
    # -----------------------------------------------------------------------
    for i in $(find /opt/open-xchange/etc/contacts-ldap/ -name "[0-9]*" -type d); do
        if [ -d $i ]; then
            for prop in $(find $i -name "*.properties"); do
                ctx=$(basename $i)
                psname=$(basename $prop .properties)
                ostr="com.openexchange.contacts.ldap.context${ctx}.${psname}.storagePriority"
                if ! grep $ostr $prop > /dev/null; then
                    echo -e "\n${ostr}=17" >> $prop
                fi
            done
        fi
    done

}

setConfigFilePermissions() {
    for i in $(find /opt/open-xchange/etc/contacts-ldap -name "*.example"); do
        ox_update_permissions "$i" root:open-xchange 640
    done
    ox_update_permissions "/opt/open-xchange/etc/contacts-ldap" root:open-xchange 750
}

case "$1" in
    configure)
        test -n "$2" && {
            # we are in update mode, run postFix to apply fixes
            postFix "$2"
        }
        setConfigFilePermissions
    ;;

    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
