#!/bin/bash
# pause-mythcommflag.sh   v0.2  05/21/09
# Utility to automatically pause & unpause mythcommflag if CPU usage is above a certain level
# Free for any use.
# Installation:
#  cp pause-mythcommflag.sh /usr/LH/bin
#  chmod +x /usr/LH/bin/pause-mythcommflag.sh
# Usage: Executed from sv start pause-mythcommflag

# Threshold for when mythcommflag will be paused
CPUTHRESHOLD=75

# Second Threshold for when mythcommflag is already paused
PAUSEDCPUTHRESHOLD=45

# Log file to write (change to /dev/null for no log)
LOG=/var/log/mythtv/pause-mythcommflag.log

# Number of seconds to wait between checking for mythcommflag process
SLEEP=5

#sleep $SLEEP

touch $LOG

COMMFLAGSTATE=1

while true; do
    PROCCOMMFLAG=`pidof mythcommflag`
    if [ -n "${PROCCOMMFLAG}" ]
    then
        FRONTENDCPU=`top -bn1u mythtv | grep mythfrontend | awk '{ print $9 }'`
        if [ $COMMFLAGSTATE -eq 1 ]
    	then
	        CPUTHRESHOLD1=$CPUTHRESHOLD
	    else
	        CPUTHRESHOLD1=$PAUSEDCPUTHRESHOLD
	    fi
        if [ "$FRONTENDCPU" -ge "$CPUTHRESHOLD1" ]
        then
#            echo "$(date) FE CPU $FRONTENDCPU% is greater than $CPUTHRESHOLD1%, PAUSE Commflagging" >> $LOG
            kill -s STOP $PROCCOMMFLAG
	    COMMFLAGSTATE=0
        else
#            echo "$(date) FE CPU $FRONTENDCPU% is less than $CPUTHRESHOLD1%, CONTINUE Commflagging" >> $LOG
            kill -s CONT $PROCCOMMFLAG
	    COMMFLAGSTATE=1
        fi
#    else
#        echo "No COMMFLAG Process Active" >> $LOG
    fi
    sleep $SLEEP
done