#!/usr/bin/sh
#
# Copyright (C) 2025 Claes Nästén <pekdon@gmail.com>
#
# script to handle playback and volume keybindings for a various supported
# backends.
#

KNOWN_PLAYERS="cmus"
KNOWN_VOL="pulse, sndio"

music_init()
{
	MUSIC_CTRL=`xrdb -get pekwm.audio.player`
	if test "x$MUSIC_CTRL" = "x"; then
		if test "x$1" = "xno"; then
			pekwm_dialog -D no-titlebar -t pekwm_audio_ctrl.sh \
				"ERROR: pekwm.audio.player not set or empty\n\n"
				"Set pekwm.audio.player to one of: $KNOWN_PLAYERS\n"
		fi
		exit 1
	fi
}

# C* Music Player

music_cmus_play()
{
	cmus-remote -p
}

music_cmus_pause()
{
	cmus-remote -u
}

music_cmus_play_pause()
{
	status=`cmus-remote -Q | /usr/bin/awk '/^status / { print $2}'`
	if test "x$status" = "xplaying"; then
		cmus-remote -u
	else
		cmus-remote -p
	fi
}

music_cmus_stop()
{
	cmus-remote -s
}

music_cmus_next()
{
	cmus-remote -n
}

music_cmus_prev()
{
	cmus-remote -p
}

vol_init()
{
	VOL_CTRL=`xrdb -get pekwm.audio.control`
	if test "x$VOL_CTRL" = "x"; then
		# volume control not configured, try to guess
		if test "`uname -s`" -eq "OpenBSD"; then
			VOL_CTRL="sndio"
		fi
	fi
	if test "x$VOL_CTRL" = "x"; then
		if test "x$1" = "xno"; then
			pekwm_dialog -D no-titlebar -t pekwm_audio_ctrl.sh \
				"ERROR: pekwm.audio.control not set or empty\n\n" \
				"Set pekwm.audio.control to one of: $KNOWN_VOL"
		fi
		exit 1
	fi
}

# Pulse Audio

vol_pulse_set_sink()
{
	if test "x$VOL_SINK" = "x"; then
		VOL_SINK=`xrdb -get pekwm.audio.pulse_sink`
		if test "x$VOL_SINK" = "x"; then
			VOL_SINK=""
		fi
	fi
}

vol_pulse_up()
{
	vol_pulse_set_sink
	pactl -- set-sink-volume "$VOL_SINK" "+10%"
}

vol_pulse_down()
{
	vol_pulse_set_sink
	pactl -- set-sink-volume "$VOL_SINK" "-10%"
}

vol_pulse_mute()
{
	vol_pulse_set_sink
	pactl -- set-sink-mute "$VOL_SINK" toggle
}

# OpenBSD sndioctl

vol_sndio_up()
{
	sndioctl output.level=+0.1 >/dev/null
}

vol_sndio_down()
{
	sndioctl output.level=-0.1 >/dev/null
}

vol_sndio_mute()
{
	sndioctl output.mute=! >/dev/null
}

usage()
{
	cat <<EOF
usage: $0 [-hq] [play|pause|stop|next|prev|vup|vdown|vmute]
EOF
	exit $1
}

opt_quiet="no"
while `test "x$1" != "x"`; do
	case $1 in
		"-h")
			usage 0
			;;
		"-q")
			opt_quiet="yes"
			shift
			;;
		*)
			break
			;;
	esac
done

case $1 in
	play)
		music_init
		cmd="music_${MUSIC_CTRL}_play"
		;;
	pause)
		music_init
		cmd="music_${MUSIC_CTRL}_pause"
		;;
	playpause)
		music_init
		cmd="music_${MUSIC_CTRL}_play_pause"
		;;
	stop)
		music_init
		cmd="music_${MUSIC_CTRL}_stop"
		;;
	next)
		music_init
		cmd="music_${MUSIC_CTRL}_next"
		;;
	prev)
		music_init
		cmd="music_${MUSIC_CTRL}_prev"
		;;
	vup)
		vol_init
		cmd="vol_${VOL_CTRL}_up"
		;;
	vdown)
		vol_init
		cmd="vol_${VOL_CTRL}_down"
		;;
	vmute)
		vol_init
		cmd="vol_${VOL_CTRL}_mute"
		;;
	*)
		usage 1
		;;
esac

$cmd
