#!/bin/dash
#
# This helper implements rule actions derived from the compilation of
# udev rules, which have ended up as properties in the hwdb.

# not NYI
# exit 0

. $VDEV_HELPERS/subr.sh
. $VDEV_HELPERS/subr-hwdb.sh

process_group() {
    /bin/chgrp "$1" "$VDEV_MOUNTPOINT/$VDEV_PATH"
    /bin/chmod ${2-660} "$VDEV_MOUNTPOINT/$VDEV_PATH"
}

process_owner() {
    /bin/chown "$1" "$VDEV_MOUNTPOINT/$VDEV_PATH"
    /bin/chmod ${2-640} "$VDEV_MOUNTPOINT/$VDEV_PATH"
}

process_category() {
    # "smartcard", "scanner" or "mediaplayer:*"
    case "$1" in
	smartcard)
	    # driver=gnupg, tag=udev-acl
	;;
	scanner)
	    # group=scanner, mode=0664 ?
	    process_group scanner 660
	;;
	mediaplayer:*)
	    # ....
	;;
    esac
}

process_run() {
    # process %b %k and %p in $1
    case "$1" in
	hid2hci*)
	    #%p=$VDEV_MOUNTPOINT/$VDEV_PATH
	    #RUN=hid2hci --method=csr --devpath=%p
	    #RUN=hid2hci --method=dell --devpath=%p
	    #RUN=hid2hci --method=logitech-hid --devpath=%p
	    ${1%=%p}=$VDEV_MOUNTPOINT/$VDEV_PATH
	;;
	usb_modeswitch*)
	    #RUN=usb_modeswitch '%b/%k'
	    usb_modeswitch -v "$VDEV_VENDOR_ID" -p "$VDEV_MODEL_ID"
	;;
	*)
	    #RUN=/usr/sbin/usbmuxd -u -U usbmux
	    : # ignore; maybe not silently?
	;;
    esac
}

process_symlink() {
    case "$1" in
	libmtp*)
	    # %k should be handled at compile time
	    #SYMLINK=libmtp-%k
	;;
	*)
	    : # ignore; maybe not silently?
	;;
    esac
}

export RALPHLOG=/root/ralph.log
[ -w "$RALPHLOG" ] && cat <<EOF >> $RALPHLOG
compiled.sh
$(env)
EOF

if [ -z "$VDEV_PATH" ] ; then
    VDEV_PATH=UNKNOWN
fi
if [ "$VDEV_PATH" = "UNKNOWN" ]; then
    if [ -n "$VDEV_OS_DEVNAME" ] ; then
	VDEV_PATH="$VDEV_OS_DEVNAME"
    elif [ -n "$VDEV_OS_BUSNUM" -a -n "$VDEV_OS_DEVNUM" ] ; then
	VDEV_PATH="bus/usb/$VDEV_OS_BUSNUM/$VDEV_OS_DEVNUM"
    else
	[ -w "$RALPHLOG" ] && echo "** THIS IS CRUEL" >> $RALPHLOG
	exit 1
    fi
fi

# The following compound command processes the various properties for
# the current device held in hwdb.
$VDEV_HELPERS/hwdb.sh -S usb -D $VDEV_OS_SYSFS_MOUNTPOINT/$VDEV_OS_DEVPATH | \
    while read prop ; do
	[ -w "$RALPHLOG" ] && echo "## $prop" >> $RALPHLOG
	case "${prop%%=*}" in
	    VDEV_HWDB_CATEGORY) process_category "${prop#*=}" ;;
	    VDEV_HWDB_GROUP) process_group "${prop#*=}" ;;
	    VDEV_HWDB_OWNER) process_owner "${prop#*=}" ;;
	    VDEV_HWDB_RUN) process_run "${prop#*=}" ;;
	    *) : ;;
	esac
    done
[ -w "$RALPHLOG" ] && echo "####" >> $RALPHLOG
:
