#!/usr/bin/env bash
# ***********************************************************
# ** Arguments (each -argument option may be repeated):
# **   [-add <sid> [--p]] 
# **   [-dn <sid> "<x500_distinguished_name>"]
# **   [-remove <sid>] 
# **   [-reset <sid> [--p]]
# **   [-admin <sid> "<repository-name>"] 
# **   [-list] [-users] 
# **   [-migrate "<repository-name>"] [-migrate-all]
# **
# **   add - add a new user to the server with the default password 'changeme' [--p prompt for password]
# **   dn - set a user's distinguished name for PKI authentication
# **   remove - remove an existing user from the server
# **   reset - reset an existing user's password to 'changeme' [--p prompt for password]
# **   admin - set the specified existing user as an admin of the specified repository
# **   list - list all existing named repositories
# **   users - list all users or those associated with each listed repository
# **   migrate - migrate the specified named repository to an indexed data storage
# **   migrate-all - migrate all named repositories to index data storage
# ***********************************************************  

SUDO=sudo

# Maximum heap memory may be changed if default is inadequate. This will generally be up to 1/4 of 
# the physical memory available to the OS. Uncomment MAXMEM setting if non-default value is needed.
MAXMEM=128M

# Resolve symbolic link if present and get the directory this script lives in.
# NOTE: "readlink -f" is best but works on Linux only, "readlink" will only work if your PWD
# contains the link you are calling (which is the best we can do on macOS), and the "echo" is the 
# fallback, which doesn't attempt to do anything with links.
SCRIPT_FILE="$(readlink -f "$0" 2>/dev/null || readlink "$0" 2>/dev/null || echo "$0")"
SCRIPT_DIR="${SCRIPT_FILE%/*}"

if [ -d "${SCRIPT_DIR}/../Ghidra" ]; then
	# Production Environment
	CONFIG="${SCRIPT_DIR}/server.conf"
else
	# Development Environment
	CONFIG="${SCRIPT_DIR}/../../Common/server/server.conf"
fi

# Identify server process owner if set within server.conf
OWNER="$(grep '^wrapper.app.account=' "${CONFIG}" | sed -e 's/^.*=\(.*\)\s*.*$/\1/')"

if [ -z "${OWNER}" -o "${OWNER}" = "$(whoami)" ]; then
	VMARGS="-DUserAdmin.invocation=$(basename "${SCRIPT_FILE}")"
	"${SCRIPT_DIR}"/../support/launch.sh fg jre svrAdmin "${MAXMEM}" "$VMARGS" ghidra.server.ServerAdmin "${CONFIG}" "$@"
else
	echo "Running svrAdmin with $SUDO as ${OWNER} ..."
	$SUDO -u $OWNER "$0" "$@"
fi
