#!/system/bin/sh
#
# trace debug info to file
# Malez

# v1.4 replaced file by syscall
# v1.3 monitor in background too
# v1.2 cat nohup / permanent logging control
# v1.1 added status
# v1 initial release
#

LOCKFILE=/sdcard/debug_pid.lock
MONITORSCRIPT=/sdcard/monitor.sh
MONITORLOG=/sdcard/monitor.log

usage()
{
  echo "usage :"
  echo "$0 on : start logging debug info to /sdcard/debug_X.log"
  echo "$0 start : start logging debug info to /sdcard/debug_X.log"
  echo "$0 off : stop logging"
  echo "$0 stop : stop logging"
  echo "$0 status : display log status"
  echo "$0 s : display log status"
  echo "This script requires root acess"
  exit 1

}

if [ $# -ne 1 ]; then
  usage
else
  id | grep "uid=0" || (echo "**** Please run su ****"; usage)
  if [ a$1 == "aon" -o a$1 == "astart" ]; then
	if [ -e $LOCKFILE ]; then 
	      echo "already logging"
	      #ps | grep cat
	      ps | grep 'logcat -b'
	      echo "launch $0 off"
	else
	      echo $$ > $LOCKFILE
	      
	      echo "start logging debug info to /sdcard/debug_X.log"
  
	      cat > $MONITORSCRIPT << EOF
	      
	      
 	      > /sdcard/debug_main.log
 	      > /sdcard/debug_events.log
 	      > /sdcard/debug_radio.log
		

	      while [ -e $LOCKFILE ]; do
		  
		  if [ \$(ps | grep cat | wc -l) -lt 3 ]; then
		      date
		      echo "Restarting monitor"
		      killall cat >/dev/null 2>&1
		      #nohup cat /dev/log/main >> /sdcard/debug_main.log &
		      #nohup cat /dev/log/radio >> /sdcard/debug_radio.log &
		      #nohup cat /dev/log/events >> /sdcard/debug_events.log &
		      nohup logcat -b main >> /sdcard/debug_main.log &
		      nohup logcat -b events >> /sdcard/debug_events.log &
		      nohup logcat -b radio >> /sdcard/debug_radio.log &
		      sleep 5s
		  else
		      sleep 30s
		  fi
	      done
	      
	      date
	      echo "Stop monitor"
EOF
	      chmod +x $MONITORSCRIPT
	      nohup sh 	$MONITORSCRIPT > $MONITORLOG & 

	fi
   elif [ a$1 == "aoff" -o a$1 == "astop" ]; then
	#PID=$(cat /scard/debug_pid.lock) && for CPID in $(); do kill $CPID; done && rm -f /scard/debug_pid.lock || echo "unable to stop logging. Please reboot"
	rm -f $LOCKFILE
	#killall cat && echo "Logging stopped" && ps | grep cat && echo "unable to stop logging. Please kill manually or reboot"
	killall logcat && echo "Logging stopped" && ps | grep logcat && echo "unable to stop logging. Please kill manually or reboot"
   elif [ a$1 == "astatus" -o a$1 == "as" ]; then
	if [ -e $LOCKFILE ]; then 
	    echo "Lockfile $LOCKFILE present"
	else
	    echo "Lockfile $LOCKFILE not present"
	fi
	#ps | grep cat && echo "logging in progress" || echo "not logging"
	ps | grep 'logcat' && echo "logging in progress" || echo "not logging"
	
   else
      usage
   fi
fi

