# sarch include functions

sarch_debug () {
   dbgmsg=$*
   log -p i -t sarch $dbgmsg
}

#dir file count of $1
dir_count () {
   sarch_debug dir_count entered
   if [ "$1" ];then
	  return `busybox ls -l $1 | busybox wc -l`;
   else
      sarch_debug dir_count error path
      exit 50
   fi
}

#remove the oldest file from directory $1
remove_oldest () {
   sarch_debug remove_oldest entered
   if [ "$1" ];then
      old=`busybox ls $1 -t -r -1 | busybox head -1`
	  
      if [ "$old" ];then
         sarch_debug trying to remove oldest file $1/$old
         rm $1/$old
         if [ $? -ne 0 ];then
           sarch_debug rm error - exiting 
	   return 89
	 fi
      fi
   else
      sarch_debug remove_oldest - path error
      exit 51
   fi
}

#remove the oldest file from klog directory
remove_oldest_klog () {
   sarch_debug remove_oldest_klog entered
   old=`busybox ls /data/logsave/kmessage/kmessage.* -t -r -1 | busybox head -1`
 
   if [ "$old" ];then
      sarch_debug trying to remove oldest file from /kmessage/
      rm $old
	if [ $? -ne 0 ];then
	   sarch_debug klog rm error - exiting 
        fi
   fi
}

# remove oldest files until the directory count matches $1 $2=path
# the dir_count function returns value to $?
# it has a check to make sure that the dir_count is changing after rm
# of the file - if not it exits to avoid infinite loop
remove_until_dircount_is () {
   sarch_debug remove_until_dircount_is entered
   if [ "$1" ];then
      if [ "$2" ]; then
		dir_count $2
		dc=$?
        lasttime=`busybox expr $dc + 1`   # latest dir_count
        while [ $dc -gt $1 ];do
	  remove_oldest $2
      dir_count $2
	  dc=$?
	  if [ $dc -eq $lasttime ];then
	     sarch_debug error: file count not stable - exiting with no archive
	     exit 47
	  fi
	  lasttime=$dc  #reset lasttime
        done
      else
	sarch_debug remove_until_dircount_is - missing param 2
	exit 77
      fi
   else
	sarch_debug remove_until_dircount_is - missing param 1
	exit 99
   fi
}

#get the size available of disk usage in a directory $1 = path
get_dir_size_avail () {
   sarch_debug get_dir_size_avail entered
   if [ "$1" ];then
	  # get df output, cut 'avaliable' column, cut value out
      avail=`busybox df -B 1 $1 | busybox tail -n 1 | busybox tr -s ' ' | busybox cut -d' ' -f4`
      sarch_debug "space available: $avail"
      echo $avail
   else
      sarch_debug get_size - path error
      exit 52
   fi
}

#tarfile to /tmp and get its size in bytes 
# $1="normal", "image", or "reboot"
# $2=path ret
#if no path is given, then the size:file is passed back through echo
taritup () {
   sarch_debug "taritup entered, parms: $@"
	if [ "$2" = "STDIN" -o -z "$2" ];then
	  tpath=/tmp
	  stdout=1
	else
		tpath=$2
		stdout=0
	fi

	extra=""
	if [ -f $3 ]; then
	  extra="${extra} $3"
	fi
	if [ -f $4 ]; then
	  extra="${extra} $4"
	fi
	if [ -f $5 ]; then
	  extra="${extra} $5"
	fi
	# set filename for tar - colons changed to dots	
	#temp_date=`date +%Y%m%d_%R%S | sed "s/://g"`
	a=`date +%Y%m%d_%R%S`
	temp_date=${a/:/}
	if [ "$1" == "image" ]; then
		tempfn=$tpath/${temp_date}_lastimage.tar.gz
	elif [ "$1" == "klog" ]; then
                tempfn=$tpath/${temp_date}_kmessage.tar.gz
	else
		tempfn=$tpath/${temp_date}.tar.gz
	fi
	rm $tempfn > /dev/null 2>&1
	# tar up to the temporary file then get its size
	if [ "$1" == "klog" ]; then
	   sarch_debug "sarch klog processing, tempfn: $tempfn"
	    nice tar -cz -f $tempfn -C /tmp /proc/binder/failed_transaction_log /proc/binder/transaction_log /proc/binder/transactions /proc/binder/stats /proc/binder/state $extra > /dev/null 2>&1
	    remove_oldest_klog
	    remove_until_dircount_is 12 /data/logsave/kmessage/
	    chmod 0777 $tempfn
	    exit 0
	fi   

	sarch_debug "about to run logcat ..."
	nice -n -4 logcat -d -v threadtime -f /tmp/syslog.txt *:V
	# capture additional data for debugging issues
	ps -t > /tmp/ps.txt

	sarch_debug "sarch non-klog processing, tempfn: $tempfn"
	nice tar -cz -f $tempfn -C /tmp /proc/binder/failed_transaction_log /proc/binder/transaction_log /proc/binder/transactions /proc/binder/stats /proc/binder/state syslog.txt ps.txt $extra > /dev/null 2>&1
	chmod 0777 $tempfn
	rm /tmp/syslog.txt /tmp/ps.txt > /dev/null 2>&1
	#size is the size of the tempfn. 
	#the sed removes the first instance of double+ spaces. 
	#this is only done if $2 was not specified
	if [ "$1" != "image" ]; then
		proc=`/system/xbin/pgrep logcat`
		if [ -z "$proc" ]; then
		   logcat -c
		else
		   sarch_debug "logcat buffer not cleared"
		fi
	fi
	
	if [ "$stdout" = "1" ];then
	   #size=`wc -c $tempfn | sed "s/[ ][ ]*//1" | cut -d' ' -f1`
	   size=`busybox wc -c $tempfn | cut -d' ' -f1`
	   echo $size:$tempfn
	fi
        exit 0
}

#make enough space to put this file on $1=size $2=path
make_space_for () {
   if [ "$1" ];then
      if [ "$2" ]; then
	     command=`get_dir_size_avail $2`
         asz=`echo "$command"`
	     #echo dir size $2 is $asz
		 
         if [ $1 -lt $asz ];then
            return 0; #indicate to caller that its OK to write the file here
         else
 	       while [ $1 -gt $asz ];do
               dir_count $2
               dc=$?
	       if [ $dc -eq 0 ];then
                  sarch_debug "No more space on directory can be reclaimed. Archive fails"
                  exit 54
               else
                  remove_oldest $2
                  #sync
               fi
               asz=`echo "$command"`
               #echo dir size $2 is $asz
            done
            # if we exit the loop here - then we've reclaimed space so return 0
            return 0
         fi
      else
        sarch_debug "makespace error 2nd param path error"
        exit 54
      fi
   else
      sarch_debug "makespace error 1st param size expected"
      exit 55
   fi
   exit 56  # unlikely or impossible to get here - but just in case...
}

# get option value from sarch trc files conf first - if empty then get from the default.
get_sarch_option_value () {
   # this gets sarch from conf file, removes tabs to spaces, then removes double spaces,
   # then uses the 6th token to find the option value for sdump
   # check the .conf (stored) file first
   opt=`grep -w sarch /data/trc.conf | sed "s/[[:cntrl:]]/ /g" | sed "s/[ ][ ]*/ /g" | cut -d' ' -f6'`
   
   #if still empty then try the default trc file
   if [ -z "$opt" ];then
     opt=`grep -w sarch /etc/trc.def | sed "s/[[:cntrl:]]/ /g" | sed "s/[ ][ ]*/ /g" | cut -d' ' -f6`
   fi
   
   #if still empty then default to 24
   if [ -z "$opt" ];then
     opt=24
   fi
   return $opt
}
