#!/bin/bash
MYTH_RUN_STATUS=1
. /etc/systemconfig
. /etc/profile

date=`date +%Y-%m-%d`
timestamp=`date +'%Y-%m-%d %H:%M'`
hostname=`hostname`
logFile="/var/log/${date}/${hostname}_myth_mtc.log"
log="logger -t myth_mtc -p local6.info"

if [ ! -f $logFile ]; then
    touch $logFile
    echo "" | $log
fi

#check logfile for Finished and if not run myth_mtc.py
if ! grep -q "Finished Maintenance" $logFile
then

    if ! grep -q "Finished checking size of MythTV home" $logFile
    then
        MYTHCONFDIR=/usr/share/mythtv unbuffer myth_mtc.py --check_home | $log
        if [ $? = 0 ]
        then
            echo "" | $log
        else
            echo "Time Exceeded" | $log
            exit
        fi
    fi

    if ! grep -q "Finished Optimize" $logFile
    then
        if [ $SystemType = Frontend_only ]
        then
            echo "Will not run Optimize on Frontend Only systems." | $log
            echo "Finished Optimize" | $log
        else
            MYTHCONFDIR=/usr/share/mythtv unbuffer myth_mtc.py --optimize | $log
            if [ $? = 0 ]
            then
                echo "" | $log
            else
                echo "Time Exceeded" | $log
                exit
            fi
        fi
    fi

    if ! grep -q "Finished Backup" $logFile && grep -q "Finished Optimize" $logFile
    then
        MYTHCONFDIR=/usr/share/mythtv unbuffer myth_mtc.py --backup | $log
        if [ $? = 0 ]
        then
            echo "" | $log
        else
            echo "Time Exceeded" | $log
            exit
        fi
    fi

    if ! grep -q "Finished Update" $logFile
    then
        MYTHCONFDIR=/usr/share/mythtv unbuffer myth_mtc.py --update | $log
        if [ $? = 0 ]
        then
            echo "" | $log
        else
            echo "Time Exceeded" | $log
            exit
        fi
    fi

    if grep -q "Finished checking size of MythTV home" $logFile && grep -q "Finished Optimize" $logFile && grep -q "Finished Backup" $logFile && grep -q "Finished Update" $logFile
    then
        echo "Finished Maintenance" | $log
    fi
fi