#! /bin/bash
#
# Copyright 2005-2023 The Mumble Developers. All rights reserved.
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file at the root of the
# Mumble source tree or at <https://www.mumble.info/LICENSE>.

DIR=$HOME/mumble-server
SYSDIR=/usr/share/doc/mumble-server/examples

if [ $UID == 0 ] || [ $EUID == 0 ]; then
  echo "You should never run this script as root. If you want a system-wide install, see "
  echo "the documentation included with this package."
  exit 2
fi

unset SETPW
DO_KILL=0
DO_STATUS=0
DO_INITONLY=0

while getopts "sid:p:k" flag; do
  case "$flag" in
  	"s")
  		DO_STATUS=1
  		;;
  	"i")
  		DO_INITONLY=1
  		;;
  	"d")
  		DIR=$OPTARG
  		;;
  	"p")
  		SETPW=$OPTARG
  		;;
  	"k")
  		DO_KILL=1
  		;;
  	*)
  		exit 2
  		;;
  esac
done
DBUSFILE=$DIR/.dbus.sh

if [ $DO_KILL == 1 ]; then
	if pkill -U $UID -u $EUID -o -x -f "/usr/sbin/mumble-server -ini $DIR/mumble-server.ini"; then
		echo "Termination signal sent"
	else
		echo "Mumble server process not found; not terminated"
        exit 2
	fi
	exit 0
fi

if [ ! -d $DIR ]; then
  echo "Making $DIR"
  mkdir -m 0700 $DIR
fi

cd $DIR || exit 2

if [ ! -f $DIR/mumble-server.ini ]; then
  echo "Creating $DIR/mumble-server.ini"
  if [ -f $SYSDIR/mumble-server.ini ]; then
    cp $SYSDIR/mumble-server.ini $DIR
  elif [ -f $SYSDIR/mumble-server.ini.gz ]; then
    gzip -cd $SYSDIR/mumble-server.ini.gz > $DIR/mumble-server.ini
  else
    echo "Could not find template for mumble-server.ini in $SYSDIR."
    exit 2
  fi
elif [ $DO_INITONLY == 1 ]; then
  echo "$DIR/mumble-server.ini already exists, initialization failed."
  exit 2
fi

if [ $DO_INITONLY == 1 ]; then
  echo "Initialization done. Please edit $DIR/mumble-server.ini"
  exit 0
fi

if [ "X$SETPW" != "X" ]; then
	echo "Setting superuser password to \"$SETPW\""
	/usr/sbin/mumble-server -ini $DIR/mumble-server.ini -supw $SETPW
	exit 0
fi

PID=$(pgrep -U $UID -u $EUID -o -x -f "/usr/sbin/mumble-server -ini $DIR/mumble-server.ini")

if [ $DO_STATUS == 1 ]; then
	if [ "X$PID" != "X" ]; then
		echo "Mumble server is running"
		exit 1
	else
		echo "Mumble server is not running"
		exit 0
	fi
fi

if [ "X$PID" != "X" ]; then
  echo "Mumble server is already running."
  exit 1
fi

DBUS_SESSION_BUS_ADDRESS=invalid:/
[ -f $DBUSFILE ] && . $DBUSFILE

if ! dbus-send --print-reply --dest=org.freedesktop.DBus --type=method_call / org.freedesktop.DBus.GetId 2> /dev/null > /dev/null; then
  echo "Launching D-Bus session"
  dbus-launch --sh-syntax > $DBUSFILE
  . $DBUSFILE
  if ! dbus-send --print-reply --dest=org.freedesktop.DBus --type=method_call / org.freedesktop.DBus.GetId 2> /dev/null > /dev/null; then
    echo "Failed to launch session DBUS, bailing out."
    exit 2
  fi
fi

echo "Starting Mumble server"
exec /usr/sbin/mumble-server -ini $DIR/mumble-server.ini
