#!/bin/bash
set -ex

# This script starts up MoaT-KV.

# Normally, starting MoaT-KV on a host where clients don't connect locally is
# a bad idea. However, on a system that has more than one network namespace
# you need to use a specific address. So set LOCAL=yes to force starting
# anyway.

if test "$LOCAL" != "yes" && test "$(moat util cfg link.backend.host)" != "127.0.0.1"; then
    echo "Server is not localhost: not starting."
    exit 42  # mark as succeeded
fi

if test ! -n "$NAME" ; then
    NAME="$(uname -n)"
fi

if test -v TEMP && test -s "$TEMP" ; then
    test -f /etc/moat/link.init && rm /etc/moat/link.init
    exec moat -c /etc/moat/moat.cfg link -n "$NAME" server -l "$TEMP"
elif test -f /etc/moat/link.init ; then
    D="$(head -1 /etc/moat/link.init)"
    rm /etc/moat/link.init
    exec moat -c /etc/moat/moat.cfg link -n "$NAME" server -I "$D"
else
    exec moat -c /etc/moat/moat.cfg link -n "$NAME" server
fi
