#!/bin/bash
set -e
set -o pipefail

# add group
if ! getent group | grep -q "^flocore:" ; then
    echo "Creating system group: flocore"
    groupadd --system flocore
fi

# add user
if ! getent passwd | grep -q "^flocore:"; then
    echo "Creating flocore system user"
    useradd --gid "flocore" --system -m flocore
fi

# build nodejs addons
cd "/usr/opt/flocore"
SKIP_BITCOIN_DOWNLOAD=1 npm rebuild

# setup data directory
mkdir -p "/home/flocore/.flocore/data"
chown -R flocore:flocore "/home/flocore/.flocore"

# start flocore
if hash service 2> /dev/null; then
    service flocore start || echo "flocore could not be registered or started"
elif hash start 2> /dev/null; then
    start flocore || echo "flocore could not be registered or started"
elif hash systemctl 2> /dev/null; then
    {
        systemctl enable "flocore.service" && \
            systemctl start "flocore.service"
    } || echo "flocore could not be registered or started"
else
    echo 'Your system does not appear to use upstart or systemd, so flocore could not be started'
fi
