#!/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-7.4.0.20251017160555/sbin/fdbserver 7400 \
    --slave /usr/sbin/fdbmonitor fdbmonitor /usr/lib/foundationdb-7.4.0.20251017160555/sbin/fdbmonitor \
    --slave /lib/systemd/system/foundationdb.service foundationdb.service /usr/lib/foundationdb-7.4.0.20251017160555/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-7.4.0.20251017160555/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
