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

postInstall() {
    # prevent bash from expanding, see bug 13316
    GLOBIGNORE='*'

    # SoftwareChange_Request 3105
    # Installing open-xchange-guard created a backup so we are able to take
    # over the previous config params to the new location.
    old_core_file_back=/opt/open-xchange/etc/guard.properties.move
    s3_properties=/opt/open-xchange/etc/guard-s3.properties
    key_prefix="com.openexchange.guard.storage.s3." 
    old_keys=( endpoint bucketName region accessKey secretKey )
    new_keys=( endPoint bucketName region accessKey secretKey )

    if [ -e ${old_core_file_back} ] && [ -e ${s3_properties} ]; then
        last_index=$(( ${#old_keys[@]}-1 ))
        for index in $(seq 0 ${last_index}); do
            old_name=${key_prefix}${old_keys[$index]}
            new_name=${key_prefix}${new_keys[$index]}
            #if property is uncommented
            if $(ox_exists_property ${old_name} ${old_core_file_back}); then
                value=$(ox_read_property ${old_name} ${old_core_file_back})
                #and property has a value
                if [ -n "${value}" ]; then
                    ox_comment ${new_name} remove ${s3_properties}
                    ox_set_property ${new_name} "${value}" ${s3_properties}
                fi  
            fi  
        done
        # after open-xchange-guard and open-xchange-storage-* are installed we
        # can clean up as properties have been moved
        rm ${old_core_file_back}
    fi
}

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

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

    s3_properties=/opt/open-xchange/etc/guard-s3.properties

    # SCR-83
    ox_add_property com.openexchange.guard.storage.s3.signerOverride "" ${s3_properties}
}

case "$1" in
    configure)
        if [ -n "$2" ]; then
            # we are in update mode, run postFix to apply fixes
            postFix "$2"
        else
            # we are in install mode
            postInstall
        fi
    ;;

    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
