#! /bin/sh
#
# udftools
#     Call pktsetup to set up packet device associations
#
# Written and Copyright 2003 Richard Atterer <atterer<at>debian.org>, GPLv2.
# Thanks to Aleksandar Topuzovic <aleksandar.topuzovic<at>fer.hr> for an
# initial version of the script.
# Thanks to Cyrille Chplov <cyrille<at>chepelov.org> for additional
# help with the specifics of 2.6 packet writing.

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC="udftools packet writing"
PKTSETUP=/usr/bin/pktsetup
DEFAULTFILE=/etc/default/udftools
DEVICES=""
DEVICENAMES="0 1 2 3" # For udev only
UDEV=""

if test -e /dev/.devfsd; then
    PDEVICES="/dev/pktcdvd/0 /dev/pktcdvd/1 /dev/pktcdvd/2 /dev/pktcdvd/3"
else
    PDEVICES="/dev/pktcdvd0 /dev/pktcdvd1 /dev/pktcdvd2 /dev/pktcdvd3"
fi

if test -f "$DEFAULTFILE"; then
    # Read user settings
    . "$DEFAULTFILE"
fi
test -x "$PKTSETUP" || exit 0

# Only execute modprobe if DEVICES set - avoid possible problems with
# the module for people who don't use packet writing.
if test -n "$DEVICES"; then
    modprobe --quiet pktcdvd || true
    if test -z "$UDEV"; then # User did not set UDEV, try auto-detection
        if grep -E -q "^[^[:space:]]+ /dev tmpfs" /proc/mounts; then
            UDEV=true
        else
            UDEV=false
        fi
    fi
fi

dostart() {
    if test -z "$DEVICES"; then
        echo "Not starting $DESC: No devices listed in $DEFAULTFILE"
    else
        echo -n "Starting $DESC:"
        if $UDEV; then
            set $DEVICENAMES
            for DEVICE in $DEVICES; do
                echo -n " /dev/pktcdvd/$1=$DEVICE" || true
                $PKTSETUP "$1" "$DEVICE"
                shift
            done
        else
            set $PDEVICES
            for DEVICE in $DEVICES; do
                echo -n " $1=$DEVICE" || true
                $PKTSETUP "$1" "$DEVICE"
                shift
            done
        fi
        echo "."
    fi
}

dostop() {
    if test -z "$DEVICES"; then
        echo "Not stopping $DESC: No devices listed in $DEFAULTFILE"
    else
        echo -n "Stopping $DESC:"
        if $UDEV; then
            set $DEVICENAMES
            for DEVICE in $DEVICES; do
                echo -n " /dev/pktcdvd/$1=$DEVICE" || true
                $PKTSETUP -d "$1"
                shift
            done
        else
            set $PDEVICES
            for DEVICE in $DEVICES; do
                echo -n " $1=$DEVICE" || true
                $PKTSETUP -d "$1" "$DEVICE"
                shift
            done
        fi
        echo "."
    fi
}

case "$1" in
    start) dostart;;
    stop)  dostop;;
    restart|force-reload) dostop; dostart;;
    *)
        echo "Usage: /etc/init.d/udftools {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
