#!/bin/sh

set -e

. /etc/default/killbill-server

set_property() {
    db_get $2 && VALUE="$RET" || VALUE=
    # Escape for sed
    VALUE=$(echo $VALUE | sed -e 's/[\/&]/\\&/g')
    if [ -f $KILLBILL_PROPERTIES ] && [ -n $VALUE ]; then
        TMPDIR=${TMPDIR-$(mktemp -d)}
        TMP_KILLBILL_PROPERTIES=$TMPDIR/$KILLBILL_PROPERTIES_FILE
        mkdir -p $TMPDIR && \
        sed -e "s/^$1=.*/$1=$VALUE/" \
            < $KILLBILL_PROPERTIES > $TMP_KILLBILL_PROPERTIES && \
        mv -f $TMP_KILLBILL_PROPERTIES $KILLBILL_PROPERTIES && \
        rmdir $TMPDIR
    fi
}

. /usr/share/debconf/confmodule

db_get killbill/username && KILLBILL_USER="$RET" || KILLBILL_USER="killbill"
db_get killbill/groupname && KILLBILL_GROUP="$RET" || KILLBILL_GROUP="killbill"

case "$1" in
    configure)
        # Create killbill user if it doesn't exist.
        if ! id ${KILLBILL_USER} > /dev/null 2>&1 ; then
            adduser --system --home ${KILLBILL_HOME} --no-create-home \
                --group --disabled-password --quiet --shell /bin/bash \
                ${KILLBILL_USER}
        fi
        # Create killbill group if it doesn't exist.
        if ! getent group ${KILLBILL_GROUP} > /dev/null 2>&1 ; then
            addgroup --system --quiet ${KILLBILL_GROUP}
            usermod -g ${KILLBILL_GROUP} ${KILLBILL_USER} > /dev/null 2>&1
        fi
        # Fix directory permissions
        chown -R ${KILLBILL_USER}:${KILLBILL_GROUP} ${KILLBILL_LOG_DIR} || true
        chown -R ${KILLBILL_USER}:${KILLBILL_GROUP} ${KILLBILL_HOME} || true

        # Configure Kill Bill properties (see config script)
        set_property org.killbill.jetty.jdbi.url killbill/dburl
        set_property org.killbill.jetty.jdbi.user killbill/dbusername
        set_property org.killbill.jetty.jdbi.password killbill/dbpassword
    ;;

    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
