#!/bin/ash
#Barry Kauler, Oct. 2011
#called via udev /etc/udev/rules.d/88-puppy-autodetect.rules
#111007 first release.
#111010 maybe wait until delayedrun has done its stuff.

[ ! "$1" ] && exit
[ "`pidof -s X Xorg $(cat /etc/windowmanager 2>/dev/null)`" = "" ] && exit #X not running.
export PATH='/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/root/my-applications/bin'
export DISPLAY=':0'
export WAYLAND_DISPLAY='wayland-0'
export XDG_RUNTIME_DIR='/tmp/runtime-root'

#111010 maybe wait until delayedrun has done its stuff...
EXCNT=0
while [ ! -f /tmp/delayedrun_finished_flag ];do #see /usr/sbin/delayedrun.
 sleep 2
 EXCNT=$(($EXCNT + 1))
 [ $EXCNT -gt 10 ] && break #precaution
done


please_install() {
	gtkdialog-splash -bg orange -close box -text "Please install $1"
	exit
}

case $1 in
 camera)
   
  #kill pupcamera gui first if present
  pupcampids=$(busybox ps | grep "gtkdialog" | grep "PCAMGUI" | awk '{ print $1 }' | tr '\n' ' ')
   
  for xpid in $pupcampids
  do
   kill $xpid
  done
   
  pupcamera &
 
 ;;
 android-device)
  if [ "$(which pupmtp)" != "" ]; then
  
   #kill pupmtp gui first if present
   pupmtppids=$(busybox ps | grep "gtkdialog" | grep "PMTPGUI" | awk '{ print $1 }' | tr '\n' ' ')
   
   for xpid in $pupmtppids
   do
    kill $xpid
   done
  
   pupmtp &
  
  elif [ "$(which mtpdevice)" != "" ]; then
   mtpdevice mount &
  else
   please_install "mtpdevice or pupmtp"
  fi
 ;;

esac