#!/bin/sh
#
# Divert some binaries that try to use /dev/dsp, which fail to work
# with LTSP and need a wrapper to divert the audio to pulseaudio or
# esd.

set -e

# FIXME Review program list and follow up on bug reports asking for 
# PulseAudio and ESpeaker support.
programs="/usr/bin/gtick"
divertowner=debian-edu-config

create_diverts() {
    for cmd in $programs ; do
	if [ -x "$cmd" ] && [ ! -x "$cmd.ltsp" ] ; then
	    cat <<EOF > "$cmd.ltsp"
#!/bin/sh
wrapper=""
if [ "\$LTSP_CLIENT" ] ; then
    if [ "\$PULSE_SERVER" ] && [ -x /usr/bin/padsp ] ; then
        # PulseAudio using padsp from pulseaudio-utils
        wrapper=padsp
    elif [ "\$ESPEAKER" ] && [ -x /usr/bin/esddsp ] ; then
        # ESD using espdsp from esound-clients
        wrapper=espdsp
    fi
fi
exec \$wrapper "$cmd.distrib" "\$@"
EOF

	    chmod 755 "$cmd.ltsp"

	    dpkg-divert --package $divertowner --rename --add "$cmd"
	    basename=$(basename "$cmd")
	    ln -s "$basename.ltsp" "$cmd"
	fi
    done
}

remove_diverts() {
    for cmd in $programs ; do
        if [ -f $cmd.ltsp ] ; then
            rm $cmd
	    dpkg-divert --package $divertowner --rename --remove $cmd
            rm $cmd.ltsp
        fi
    done
}

usage() {
    cat <<EOF
Usage: $0 < create | remove >

Implement diverted binaries for selected binaries to make sure
applications using OSS (/dev/dsp) work with Pulseaudio and ESD.

create will add the diverted binaries, while remove will take away the
diversions.

Currently handled binaries are (active diverts are marked with *):
EOF
    for cmd in $programs; do 
	if [ -x "$cmd.distrib" ] ; then
	    printf "%s(*) " "$cmd"
	else
	    printf "%s " "$cmd"
	fi
    done
    echo
}

case "$1" in
    create)
	create_diverts
	;;
    remove)
	remove_diverts
	;;
    *)
	usage
	;;
esac
