#!/usr/bin/env bash

# Resolve any links in $0 to get the real path
SELF="$0"
while [ -h "$SELF" ]; do
    LSLD=$(ls -ld "$SELF")
    LINK=$(expr "$LSLD" : '.*-> \(.*\)$')
    if expr "$LINK" : '/.*' > /dev/null; then
        SELF="$LINK"
    else
        SELF=$(dirname "$SELF")/"$LINK"
    fi
done

BIN_DIR=$(dirname "$SELF")
export BIN_DIR

INST_DIR=$(dirname "$BIN_DIR")
export INST_DIR

source $BIN_DIR/set-mesh-home.sh &&
    source $BIN_DIR/set-mesh-user.sh
if [ -z "$MESH_HOME" ]; then
    echo Required environment variables were not set.
    exit 1
fi

if [ -z "$MESH_USER" ] || [ "$(id -un)" == "$MESH_USER" ]; then
    echo "Stopping Bitbucket Mesh as the current user"

    # Stop mesh. The stop script relies on a PID file generated by
    # the paired start script
    $BIN_DIR/_stop-mesh.sh
elif [ $UID -ne 0 ]; then
    echo Bitbucket Mesh has been installed to run as "$MESH_USER", and can only be stopped by that
    echo user. Use "sudo -u $MESH_USER $0" to stop Bitbucket Mesh.
    exit 1
else
    echo "Stopping Bitbucket Mesh as dedicated user $MESH_USER"

    if [ -x "/sbin/runuser" ]; then
        SU="/sbin/runuser"
    else
        SU="su"
    fi

    $SU -l "$MESH_USER" <<EOS
        # Copy over the environment, the poor man's way
        export MESH_HOME="$MESH_HOME"
        export BIN_DIR="$BIN_DIR"
        export INST_DIR="$INST_DIR"

        # Change working directory
        cd $PWD

        $BIN_DIR/_stop-mesh.sh
EOS
fi