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

if [ "$1" = configure ]; then
    if [ "$2" = "" ]; then
        # This should be ensured by the foundationdb-clients package, but it can't hurt...
        getent group foundationdb >/dev/null || addgroup --system foundationdb
        getent passwd foundationdb >/dev/null || adduser --system --disabled-login --ingroup foundationdb --no-create-home --home /var/lib/foundationdb --gecos "FoundationDB" --shell /bin/false foundationdb

        chown -R foundationdb:foundationdb /var/lib/foundationdb /var/log/foundationdb
        chmod -R 0700 /var/lib/foundationdb/data /var/log/foundationdb

        if [ ! -f /etc/foundationdb/fdb.cluster ]; then
            description=`LC_CTYPE=C tr -dc A-Za-z0-9 < /dev/urandom | head -c 8`
            random_str=`LC_CTYPE=C tr -dc A-Za-z0-9 < /dev/urandom | head -c 8`
            echo $description:$random_str@127.0.0.1:4500 > /etc/foundationdb/fdb.cluster
            chown foundationdb:foundationdb /etc/foundationdb/fdb.cluster
            chmod 0664 /etc/foundationdb/fdb.cluster
            NEWDB=1
        fi
    fi

    # It would be better to use 'systemctl start foundationdb.service'. 
    # Since it does not work on Ubuntu 14.04, use this workaround as of now.
    /etc/init.d/foundationdb start

    if [ "$2" = "" ]; then
        update-rc.d foundationdb defaults

        if [ "$NEWDB" != "" ]; then
            /usr/bin/fdbcli -C /etc/foundationdb/fdb.cluster --exec "configure new single memory; status" --timeout 20
        fi
    fi
fi

exit 0
