#!/bin/dash

# james note: 2019 - we disable this by default since
# in FD 800 we don't have a bluetooth-applet yet
# JakeSFR 2022: re-enable and re-write for James' btmanager.sh
# JakeSFR 2022: add menu with an option to restart BT service, remove hciconfig/bluetoothd checks

### std localisation stanza
export TEXTDOMAIN=fatdog
#. gettext.sh

TOOLTIP="$(echo $(gettext " --- Bluetooth Applet --- \n\nLeft-Click:\tBluetooth Manager\nRight-Click:\tShow Menu"))"
BT_ICON='/usr/share/pixmaps/midi-icons/bluetooth48.png'
BT_EXEC='btmanager.sh'
BT_RESTART='sh -l -c "( nohup service bluetooth restart > /dev/null 2>&1 & )"'	# gtkmenuplus requires this method for > 1 command

WORKDIR="/tmp/bluetooth-applet.${USER}.${$}"
MENU="${WORKDIR}/menu"
mkdir -p "$WORKDIR"
trap 'kill -0 $SIT_PID 2>/dev/null && kill $SIT_PID; rm -rf "${WORKDIR}"; exit' 0 INT TERM HUP

# =============================================================================

func_generate_menu () {
echo '
iconsize = 24

format = weight="bold"

item = '"$(gettext "Bluetooth Manager")"'
icon = '"$BT_ICON"'
cmd = '"$BT_EXEC"'

item =  '"$(gettext "Restart Bluetooth Service")"'
icon = gtk-refresh
cmd = '"$BT_RESTART"'

SEPARATOR

item ='"$(gettext "Quit")"'
icon = gtk-quit
cmd = 'kill $$ $SIT_PID'

' > "$MENU"
}

# =============================================================================

# Show the icon only if the bluetooth service is running.
#if [ -x /etc/init.d/85-bluetooth ] && [ ! -z "$(hciconfig)" ]; then
if [ -x /etc/init.d/85-bluetooth ] || service bluetooth status | grep -q running; then
	sit "$BT_ICON" "$TOOLTIP" "$BT_EXEC" "gtkmenuplus "${MENU}"" &
	SIT_PID=$!
	func_generate_menu	# must be here, to catch $SIT_PID
	wait
fi
