#!/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

    # SoftwareChange_Request-3534
    ox_add_property com.openexchange.guard.temporaryTokenLifespan 48 /opt/open-xchange/etc/guard-core.properties

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

    # SoftwareChange_Request-3645
    ox_add_property com.openexchange.guard.dns.allowUnsignedSRVRecords true /opt/open-xchange/etc/guard-core.properties

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

    # SoftwareChange_Request-3647
    PFILE=/opt/open-xchange/etc/guard-core.properties
    if ! grep "com.openexchange.guard.fileUploadDirectory" >/dev/null $PFILE; then
        echo -e "\n# File Upload\n" >> $PFILE
        echo "# The directory used for buffering uploaded data." >> $PFILE
        echo "# Default: empty which falls back to use \"java.io.tmpdir\"" >> $PFILE
        echo -e "# com.openexchange.guard.fileUploadDirectory=\n" >> $PFILE
    fi
    if ! grep "com.openexchange.guard.fileUploadBufferThreshhold" >/dev/null $PFILE; then
        echo "# The threshold in bytes at which uploaded data will be buffered to disk." >> $PFILE
        echo "# NOTE: Guard does only buffer non sensitive or encrypted data to disk." >> $PFILE
        echo "# Default: 10240 = 10 Kb" >> $PFILE
        echo -e "# com.openexchange.guard.fileUploadBufferThreshhold=10240\n" >> $PFILE
    fi

    # SoftwareChange_Request-3736
    ox_add_property com.openexchange.guard.attachHelpFile true /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-4293
    ox_add_property com.openexchange.guard.guestSMTPMailFrom "" /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-4488
    pname=com.openexchange.guard.cacheDays
    pfile=/opt/open-xchange/etc/guard-core.properties
    [[ -n "$(ox_read_property $pname $pfile)" ]] && ox_remove_property $pname $pfile
    ox_add_property com.openexchange.guard.guestCleanedAfterDaysOfInactivity 365 $pfile

    # SoftwareChange_Request-80
    ox_add_property com.openexchange.guard.keySources.trustThreshold 4 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelGuard 5 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelGuardUserUploaded 4 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelGuardUserShared 3 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelHKPPublicServer 1 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelHKPTrustedServer 5 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelHKPSRVServer 4 /opt/open-xchange/etc/guard-core.properties
    ox_add_property com.openexchange.guard.keySources.trustLevelHKPSRVDNSSECServer 4 /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-105
    ox_add_property com.openexchange.guard.guestCaching true /opt/open-xchange/etc/guard-core.properties

    # SoftwareChange_Request-152
    ox_add_property com.openexchange.guard.remoteKeyLookupTimeout 1000 /opt/open-xchange/etc/guard-core.properties

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

    # SoftwareChange_Request-181
    ox_add_property com.openexchange.guard.failForMissingMDC false /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
