#!/usr/bin/bash

RUNNER_GEN_DIR=/var/lib/riak
RELX_RIAK=/usr/lib64/riak/bin/riak
export PID_DIR=/var/run/riak
export RUNNER_LOG_DIR=/var/log/riak

if [ ! -d $PID_DIR ]; then
    mkdir -p $PID_DIR
    chown riak:riak $PID_DIR
fi

# cuttlefish should be doing this, but it doesn't:
VMARGS_PATH=`ls -1 ${RUNNER_GEN_DIR}/generated.conf/vm.*.args 2>/dev/null | tail -1`
if [ ! -r  "$VMARGS_PATH" ]; then
    VMARGS_PATH="/usr/lib64/riak/releases/3.2.5/vm.args"
fi
export VMARGS_PATH

function su_bsd {
	# bsd su is fairly limited, so:
	mkdir -p "$RUNNER_GEN_DIR"
	chown riak:riak "$RUNNER_GEN_DIR"
	f=`mktemp "$RUNNER_GEN_DIR"/su_piggy-XXXXXXX`
	cat >"$f" <<EOF
#!/bin/sh
$*
EOF
	chmod +x "$f"
	chown riak:riak "$f"
	su riak -c "$f"
	rm -f "$f"
}

function maybe_su {
    if [[ $EUID -ne 0 ]]; then
        "$@"
    else
        # if we are executing an admin command that spins up a
        # (hidden) node to then execute custom erlang code via -eval,
        # we need to cd to a dir containing the erlang cookie
        cd "/usr/lib64/riak"
        if `grep BSD /etc/os-release` ; then
            su_bsd "$@"
        else
            sudo -H -E -u riak -- "$@"
        fi
    fi
}

case "$1" in
    stop)
        maybe_su $RELX_RIAK "$@" \
	    && rm -f $PID_DIR/riak.pid  ## relx-generated script doesn't remove it
	;;
    *)
        maybe_su $RELX_RIAK "$@"
        ;;
esac
