#!/bin/bash
#VERSION=1.0

DO_MYSQL=1
DO_CPU=1


CPU_LOG=/root/.cpu.processes.log
if [ "$DO_CPU" -eq 1 ]; then
	top -b -n 2 > $CPU_LOG
fi

MYSQL_LOG=/root/.mysql.processes.log
if [ "${DO_MYSQL}" -eq 1 ]; then
        #this script is only called once per minute, so dont worry about race conditions, only queries that last more than a minute.
        LOCK=${MYSQL_LOG}.lock
        HAVE_LOCK=0
        if [ ! -e ${LOCK} ]; then
                echo $$ > $LOCK
                HAVE_LOCK=1
        fi

        if [ "${HAVE_LOCK}" -eq 1 ]; then
                mysql --defaults-extra-file=/usr/local/directadmin/conf/my.cnf -e "SELECT USER,TIME FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND!='Sleep'" > ${MYSQL_LOG}
                rm -f $LOCK
        fi
fi


USRS=/usr/local/directadmin/data/users
for i in `ls $USRS`; do
{
        U=$USRS/$i
        if [ ! -d $U ]; then
                continue;
        fi
        id -u $i >/dev/null 2>&1
        if [ $? -gt 0 ]; then
                continue;
        fi

        L=$U/cpu_usage.log

        if [ "$DO_CPU" -eq 1 ]; then
		STR="cat /root/.cpu.processes.log | awk 'NR>7 { if (\$2==\"$i\") sum += \$9; } END { print sum; }'"
		CPU=`eval $STR`
		if [ "${CPU}" = "" ]; then
			CPU=0
		fi
        fi
        if [ "$DO_MYSQL" -eq 1 ]; then
		STR="cat $MYSQL_LOG | awk '\$1 ~ /${i}_/ { sum += \$2 } END { print sum; }'"
		MYSQL=`eval $STR`
		if [ "${MYSQL}" = "" ]; then
			MYSQL=0
		fi
        fi

	echo "`date +%s`=cpu=$CPU&mysql=$MYSQL" >> $U/cpu.log
};
done;
exit 0;

