#!/bin/sh
#
# /etc/hotplug/usb/usbcam
#
# Set up newly plugged in USB camera
# Notify all KDE sessions (thanks to the mediamanager) that a
# new camera appeared or disappeared

# to debug this script, uncomment the next line and see /tmp/usbcam.debug after execution
#DEBUG=1

# exit immediately if /usr/bin/ is not yet available (during boot if /usr is a separate partition)
/bin/ls -d /usr/bin/ >/dev/null 2>&1 || exit

GROUP=camera

if [ "${ACTION}" = "add" ] && [ -f "${DEVICE}" ]
then
    chmod a-rwx "${DEVICE}"
    chgrp "${GROUP}" "${DEVICE}"
    chmod ug+rw "${DEVICE}"
fi


DEBUGOUT=/tmp/usbcam.debug.$$
if [ "$DEBUG" = "1" -a -z "$2" ]; then
  echo "executing $0 $@" > $DEBUGOUT
  echo "with the following environment variables:" >> $DEBUGOUT
  env >> $DEBUGOUT
  echo "----" >> $DEBUGOUT
  sh -x $0 $@ debug >> $DEBUGOUT 2>&1
  exit
fi

# functions for syslog
LOGGER="logger -t `basename $0`[$$] -p user.notice"
write_syslog () {
  echo ${@} | $LOGGER
}

if [ -z "$REMOVER" ]; then
  write_syslog "No remover found"
  exit
fi

dcop_users="`ps aux | grep dcopserver | grep -v grep | awk '{print $1}' | sort | uniq`"

# if the current device is being added
if [ "$ACTION" = "add" ]; then
  write_syslog "Copying remover..."
  cp /etc/hotplug/usb/usbcam $REMOVER
  chmod +x $REMOVER
  # get camera information
  camera="/sys${DEVPATH}/.."
  if [ -e $camera/product ]; then product="`cat $camera/product`"; fi
  if [ -e $camera/manufacturer ]; then manufacturer="`cat $camera/manufacturer`"; fi

  write_syslog "Invoking dcop..."
  write_syslog "kded mediamanager removableCamera $DEVICE \"$manufacturer $product\""

  method="kded mediamanager removablePlug"
  for user in $dcop_users ; do
    dcop --user $user --all-sessions $method $DEVICE "$manufacturer $product"
  done
  
  method="kded mediamanager removableCamera"
  for user in $dcop_users ; do
    dcop --user $user --all-sessions $method $DEVICE
  done
  
elif [ "$ACTION" = "remove" ]; then
  write_syslog "Invoking dcop..."
  write_syslog "kded mediamanager removableUnplug $DEVICE"

  method="kded mediamanager removableUnplug"
  for user in $dcop_users ; do
    dcop --user $user --all-sessions $method $DEVICE
  done
  
fi


