#!/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

mkdir -p $PID_DIR
chown riak:riak $PID_DIR

# 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.0/vm.args"
fi
export VMARGS_PATH

# centos7-based distros have a su that contacts pam and prints the "Last logged in" message
if [ "`cat /etc/redhat-release 2>&1`" = "CentOS Stream release 7" ] ||
   [ "`cat /etc/system-release 2>&1`" = "Amazon Linux release 2 (Karoo)" ]; then
    COPTION="--session-command"
else
    COPTION="-c"
fi

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
	# (previously implicitly done by su -, which option we have
	# removed in order to allow any env vars to be available for
	# the ultimate invocation of riak/riak-cs/stanchion)
	cd "/usr/lib64/riak"
	# freebsd 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 $COPTION "$f"
	rm -f "$f"
   fi
}

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

	# what is this for?
        #ESCAPED_ARGS=`echo "$@" | sed -e 's/\([\\\(\\\){}"\x27]\)/\\\\\1/g'`
        maybe_su $RELX_RIAK $*
        ;;
esac
