#!/bin/bash
# postinst script for open-xchange-guard
#
# 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='*'

    # SoftwareChange_Request 2900, 2902, 2975, 3105, 3139
    # additionally backup old guard.properties file
    old_core_file=/opt/open-xchange/guard/etc/guard.properties
    old_core_file_back=/opt/open-xchange/etc/guard.properties.move
    new_core_file=/opt/open-xchange/etc/guard-core.properties
    key_prefix="com.openexchange.guard."
    core_names_22=( aesKeyLength backend_SSL badMinuteLock badPasswordCount cacheDays connectiontimeout cronHour databasePassword databaseUsername dbSchemaBaseName defaultLanguage exposedKeyDurationInHours externalEmailURL externalReaderPath guestSMTPPassword guestSMTPPort guestSMTPServer guestSMTPUsername keycachecheckinterval keyValidDays mailIdDomain mailresolverurl maxhttpconnections maxtotalconnections minpasswordlength newpasslength noDeletePrivate noDeleteRecovery noRecovery oxbackendidletime oxbackendpath OXBackendPort oxguardDatabaseHostname oxguardDatabaseRead oxguardShardDatabase oxguardShardRead passwordFromAddress passwordFromName pgpCacheDays publicKeyWhitelist publicPGPDirectory restApiHostname restApiPassword restApiUsername rsacache rsacachecount rsacertainty rsaKeyLength shardsize supportapipassword supportapiusername usestarttls productName )

    core_names_24=( aesKeyLength backendSSL badMinuteLock badPasswordCount cacheDays connectionTimeout cronHour databasePassword databaseUsername dbSchemaBaseName defaultLanguage exposedKeyDurationInHours externalEmailURL externalReaderPath guestSMTPPassword guestSMTPPort guestSMTPServer guestSMTPUsername keyCacheCheckInterval keyValidDays mailIdDomain mailResolverUrl maxHttpConnections maxTotalConnections minPasswordLength newPassLength noDeletePrivate noDeleteRecovery noRecovery oxBackendIdleTime oxBackendPath oxBackendPort oxGuardDatabaseHostname oxGuardDatabaseRead oxGuardShardDatabase oxGuardShardRead passwordFromAddress passwordFromName pgpCacheDays publicKeyWhitelist publicPGPDirectory restApiHostname restApiPassword restApiUsername rsaCache rsaCacheCount rsaCertainty rsaKeyLength shardSize supportApiPassword supportApiUsername useStartTLS productName )

    #if all needed files exist
    if [ -e $old_core_file ] && [ -e $new_core_file ]; then
      #make a backup of user changes
      cp $old_core_file $old_core_file_back
      last_index=$(( ${#core_names_22[@]}-1 ))
      for index in $(seq 0 $last_index); do
        old_name=${key_prefix}${core_names_22[$index]}
        new_name=${key_prefix}${core_names_24[$index]}
        #if property is uncommented
        if $(ox_exists_property ${old_name} ${old_core_file}); then
          value=$(ox_read_property ${old_name} ${old_core_file})
          #and property has a value
          if [ -n "${value}" ]; then
            ox_comment ${new_name} remove ${new_core_file}
            ox_set_property ${new_name} "${value}" ${new_core_file}
          fi
        fi
      done
    fi

    # SoftwareChange_Request-2907
    if [ -e "/opt/open-xchange/guard/oxguardpass" ]; then
        mv /opt/open-xchange/guard/oxguardpass /opt/open-xchange/etc/oxguardpass
    fi

    # SoftwareChange_Request-2928
    if [ -e "/opt/open-xchange/guard/private_dns_key" ]; then
        rm /opt/open-xchange/guard/private_dns_key
    fi
    if [ -e "/opt/open-xchange/guard/public_dns_key" ]; then
        rm /opt/open-xchange/guard/public_dns_key
    fi
    if [ -d "/opt/open-xchange/guard/etc" ]; then
        rm -rf /opt/open-xchange/guard/etc
    fi
    find /opt/open-xchange -name guard -type d -empty -delete

    # SoftwareChange_Request-2933
    # Try to remove Wheezy start scripts because administrator may upgrade from Wheezy to Jessie, too.
    update-rc.d open-xchange-guard remove >/dev/null
    if [ -e "/etc/init.d/open-xchange-guard" ]; then
        rm /etc/init.d/open-xchange-guard
    fi
    # Try to remove Jessie start script when administrator already upgraded to Jessie.
    if [ -x "/usr/bin/deb-systemd-helper" ]; then
        deb-systemd-helper mask open-xchange-guard.service >/dev/null
        deb-systemd-helper purge open-xchange-guard.service >/dev/null
        deb-systemd-helper unmask open-xchange-guard.service >/dev/null
    fi
    if [ -e /lib/systemd/system/open-xchange-guard.service ]; then
        rm /lib/systemd/system/open-xchange-guard.service
    fi

    # SoftwareChange_Request-3307
    ox_add_property com.openexchange.guard.defaultAdvanced false /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-3313
    ox_add_property com.openexchange.guard.trustedPGPDirectory "" /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.untrustedPGPDirectory "" /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-3318
    ox_add_property com.openexchange.guard.mailResolverUrl.basicAuthUsername "" /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.mailResolverUrl.basicAuthPassword "" /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-3357
    ox_add_property com.openexchange.guard.authLifeTime 1W /opt/open-xchange/etc/guard-core.properties
}

case "$1" in
    configure)
        chmod 750 /var/spool/open-xchange/guard/uploads
        chown open-xchange:root /var/spool/open-xchange/guard/uploads
        chmod 640 /opt/open-xchange/etc/guard-core.properties
        chown root:open-xchange /opt/open-xchange/etc/guard-core.properties

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

    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
