#!/bin/dash

# helper to bind an input device

. "$VDEV_HELPERS/subr.sh"

# main method 
# return 0 on success
# return 1 on unknown action
# return 2 if bind helper does not apply
main() {
   
   local DEVICE DRIVER TEE

   if [ "$(id -u)" -eq 0 ]; then
      TEE=/usr/bin/tee
   else
      TEE="sudo /usr/bin/tee"
   fi
   
   case "$VDEV_ACTION" in

      add)
         DEVICE="$(/bin/readlink -n "$VDEV_OS_SYSFS_MOUNTPOINT/$VDEV_OS_DEVPATH/device")"
         # Get absolute path to the driver
         DRIVER="$(/bin/readlink -f "$VDEV_OS_SYSFS_MOUNTPOINT/$VDEV_OS_DEVPATH/$DEVICE/driver")"
         # Is it a broken link?
         /bin/readlink -e "$VDEV_OS_SYSFS_MOUNTPOINT/$VDEV_OS_DEVPATH/$DEVICE/driver"
         if [ $? -eq 0 ]; then
             /bin/echo "$(/usr/bin/basename "$DEVICE")" | $TEE "$DRIVER/unbind" >/dev/null
             /bin/echo "$(/usr/bin/basename "$DEVICE")" | $TEE "$DRIVER/bind" >/dev/null
         fi
         return $?
         ;;

      *)
         vdev_error "Unknown action '$VDEV_ACTION'"
         return 1
         ;;
   esac

   return 0
}

if [ $VDEV_DAEMONLET -eq 0 ]; then 
   main 
   exit $?
fi
