#!/usr/bin/env bash

getent group foundationdb >/dev/null || groupadd -r foundationdb >/dev/null
getent passwd foundationdb >/dev/null || useradd -c "FoundationDB" -g foundationdb -s /bin/false -r -d /var/lib/foundationdb foundationdb >/dev/null

mkdir -p /var/lib/foundationdb/data /var/log/foundationdb
chown -R foundationdb:foundationdb /var/lib/foundationdb /var/log/foundationdb
chmod -R 0750 /var/lib/foundationdb/data /var/log/foundationdb

mkdir -p /usr/lib/foundationdb
update-alternatives --install /usr/sbin/fdbserver fdbserver /usr/lib/foundationdb-@FDB_VERSION@@FDB_BUILDTIME_STRING@/sbin/fdbserver @ALTERNATIVES_PRIORITY@ \
    --slave /usr/lib/foundationdb/fdbmonitor fdbmonitor /usr/lib/foundationdb-@FDB_VERSION@@FDB_BUILDTIME_STRING@/sbin/fdbmonitor \
    --slave /lib/systemd/system/foundationdb.service foundationdb.service /usr/lib/foundationdb-@FDB_VERSION@@FDB_BUILDTIME_STRING@/lib/systemd/system/foundationdb.service

if mkdir /etc/foundationdb
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
    cp /usr/lib/foundationdb-@FDB_VERSION@@FDB_BUILDTIME_STRING@/etc/foundationdb/foundationdb.conf /etc/foundationdb/foundationdb.conf
    chown -R foundationdb:foundationdb /etc/foundationdb
    chmod 775 /etc/foundationdb
    chmod 0664 /etc/foundationdb/fdb.cluster
    /usr/bin/systemctl enable foundationdb >/dev/null 2>&1
    /usr/bin/systemctl start foundationdb >/dev/null 2>&1
    /usr/bin/fdbcli -C /etc/foundationdb/fdb.cluster --exec "configure new single memory; status" --timeout 20
fi
