#!/bin/sh

# if biglybt is running as daemon,
# and if the user is allowed to display the UI,
# then start the UI
#
# Authorization to display the UI is set in the sudoers file :
#   /etc/sudoers.d/biglybtd-gui-xauth
#
if [ "$(systemctl is-active biglybtd.service)" = "active" ]; then
  # Biglybt is running as a daemon

  # Check if current DISPLAY is the one used by biglybtd
  BIGLYBTD_DISPLAY=$(systemctl show -p Environment --value biglybtd.service | cut -d = -f 2)
  if [ ! "$DISPLAY" = "$BIGLYBTD_DISPLAY" ]; then
    echo "biglybtd DISPLAY [$BIGLYBTD_DISPLAY] and currrent DISPLAY [$DISPLAY] differ."
    echo "The UI may not show up. Adapt biglybtd's DISPLAY to match the display you use."
    echo "See /usr/share/doc/biglybtd/README.Debian for more information."
  fi

  # Check if current user is allowed to update .Xauthority file for biglybt user
  BIGLYBTD_USER=$(systemctl show -p User --value biglybtd.service)
  if [ ! "$USER" = "$BIGLYBTD_USER" ]; then
    # Check if current user is allowed in sudoers file
    if sudo -l -u $BIGLYBTD_USER /usr/bin/xauth merge ->/dev/null; then
      xauth extract - $DISPLAY | sudo XAUTHORITY=$( getent passwd "$BIGLYBTD_USER" | cut -d: -f6 )/.Xauthority -u $BIGLYBTD_USER /usr/bin/xauth merge -
    else
      echo "Not allowed to run swt UI on bibybt deamon."
      echo "Please check /etc/sudoers.d/biglybtd-gui-xauth or read /usr/share/doc/biglybtd/README.Debian"
      exit 64
    fi
  fi

  # start swt UI
  echo "ui swt\nlogout" | nc 127.0.0.1 57006 > /dev/null

else
  echo "biglybt deamon is not running"
fi
