#!/bin/bash

set -uo pipefail

# check if $1 is a number
if [ "${1:-}" -eq "${1:-}" ] 2>/dev/null; then
	# if it is, then use it as the slot
	SLOT=$1
	# and then shift (remove $1 from args) to have the rest turn into CMD
	shift
else
	# otherwise, default to 1 as the slot
	SLOT=1
fi

RUNTIME_DIR=${RUNTIME_DIR:-${XDG_RUNTIME_DIR:-/tmp}}
SOCKFILE="${RUNTIME_DIR}/wnl_slot_${SLOT}.sock"

if [ ! -S "$SOCKFILE" ]; then
	echo "Error: socket $SOCKFILE not found" >&2
	exit 1
fi

SIGNAL=${SIGNAL:-USR1}

case "$SIGNAL" in
USR1)
	COMMAND=START
	;;
USR2)
	COMMAND=STOP
	;;
esac

echo "$COMMAND" | socat -U UNIX-CLIENT:"$SOCKFILE" STDIN
