#!/bin/bash
# limit-mythcommflag.sh   v0.2  03/2/10
# Utility to automatically limit mythcommflag if CPU system load is above a certain level
# and if backend usage is above a certain level
# Uses cpulimit from http://cpulimit.sourceforge.net/
# Free for any use.
# Installation:
#  cp limit-mythcommflag.sh /usr/LH/bin
#  chmod +x /usr/LH/bin/limit-mythcommflag.sh
# Usage: Executed from runit limit-mythcommflag at boot

#-----OPTIONS______
# Number of seconds to wait between checking for mythcommflag process
SLEEP=5
# Backend and Frontend thresholds above which mythcommflag is stopped
BETHRESHOLD=30
FETHRESHOLD=55

# FUNCTIONS
limit_cpu()
# Arg_1 = LimitedRangeNum; Arg_2 = CPULimitPercent; Arg_3 = Commflag PID
{
if [ $ALREADYLIMITED -ne $1 ] ; then
    if [ $cpulimit_pid -ne 0 ]; then
        kill $cpulimit_pid
    fi
    cpulimit -p $3 -l $2 &
    cpulimit_pid=$!
    ALREADYLIMITED=$1
fi
}

stop_limit()
{
if [ $ALREADYLIMITED -ne 0 ]; then
    if [ $cpulimit_pid -ne 0 ]; then
        kill $cpulimit_pid
        cpulimit_pid=0
    fi
    ALREADYLIMITED=0
fi
}

ALREADYLIMITED=0
STOPPED=0
cpulimit_pid=0

while true; do
    PROCCOMMFLAG=`pidof mythcommflag`
    if [ -n "${PROCCOMMFLAG}" ]; then
        BACKENDCPU=`top -bn1u mythtv | grep -m 1 'mythbackend ' | awk '{ print $9 }'`
        FRONTENDCPU=`top -bn1u mythtv | grep -m 1 'mythfrontend ' | awk '{ print $9 }'`
        if [ "$FRONTENDCPU" = "" ]; then
            FRONTENDCPU=0
        fi
        if [ "$BACKENDCPU" -ge "$BETHRESHOLD" ]; then
            if [ "$FRONTENDCPU" -ge $FETHRESHOLD ]; then
                if [ $STOPPED -eq 0 ]; then
                    kill -s STOP $PROCCOMMFLAG
                    STOPPED=1
                fi
            else
                if [ $STOPPED -eq 1 ]; then
                    kill -s CONT $PROCCOMMFLAG
                    STOPPED=0
                fi
                stop_limit
            fi
        else
            if [ $STOPPED -eq 1 ]; then
                kill -s CONT $PROCCOMMFLAG
                STOPPED=0
            fi
            case $FRONTENDCPU in
	        [0-9]|[0-3][0-9] )
                stop_limit;;
	        [4-5][0-9] ) 
                limit_cpu "1" "70" $PROCCOMMFLAG;;
	        [6-7][0-9] ) 
                limit_cpu "2" "50" $PROCCOMMFLAG;;
	        [8-9][0-9] ) 
                limit_cpu "3" "20" $PROCCOMMFLAG;;
	        [1][0-9][0-9] )
                limit_cpu "4" "10" $PROCCOMMFLAG;;
	        esac
        fi
#    else
#        echo "No COMMFLAG Process Active"
    fi
    sleep $SLEEP
done