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

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

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

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

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

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

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

        # Change working directory
        cd $PWD

        $BIN_DIR/_stop-webapp.sh
        $BIN_DIR/_stop-search.sh
EOS
fi
