#!/usr/bin/python


import sys, subprocess
import optparse
import re
import socket
import os
import datetime,time



try:
    from MythTV import MythBE
    mythtv = MythBE()
except:
    mythtv = None

#print mythtv.db.getSetting( 'Theme', socket.gethostname())

def optimize():
    try:
        cursor = mythtv.db.cursor()
        cursor.execute("SHOW tables")
        result = cursor.fetchall()
    except:
        print "Problem getting tables from database"
	return
    ops=["REPAIR","OPTIMIZE","ANALYZE"]
    for row in result:
        ctable=row[0]
        for op in ops:
            print op,ctable
            cmd= "%s  table %s" %(op,ctable)
            cursor.execute(cmd)


def upcoming_check():
    try:
        upcoming = mythtv.getUpcomingRecordings()
    except:
        return True
    try:
        show=str(upcoming[0])
        show=show.strip()
        showtime=show.partition("(")[2].strip(")")
        now=time.time()
        rec_time=time.strptime( showtime ,"%Y-%m-%d %H:%M:%S" )
        r=time.mktime(rec_time)
        time_diff= ( r - now ) / 60
    except:
        time_diff=100
        show="No show"
    if ( time_diff  >  30) :
        return True
    else:
        print show , "is upcoming in " , time_diff
        return False


def schemalock_check():
    try:
        c = mythtv.db.cursor()
        c.execute("select count(*) from schemalock")
        results=c.fetchone()
        schemalock=results[0]
    except:
        return True

    if schemalock == 0:
        return True
    else:
        print "schema is locked"
        return False

def job_check():
    try:
        c = mythtv.db.cursor()
        c.execute("select count(*) from jobqueue where status = 4")
        results=c.fetchone()
    except:
        return True
    jobs= results[0]
    if jobs == 0 :
        return True
    else:
        print " jobs are running"
        return False


def in_use():
    try:
        c = mythtv.db.cursor()
        c.execute("select count(*) from inuseprograms")
        results=c.fetchone()
    except:
        return True
    prginuse=results[0]
    if prginuse == 0 :
        return True
    else:
        print "programs in use"
        return False

def mfd_check():
    ps = subprocess.Popen("ps ax -o pid= -o args= ", shell=True, stdout=subprocess.PIPE)
    ps_pid = ps.pid
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    proc_name="mythfilldatabase"
    for line in output.split("\n"):
        res = re.findall("(\d+) (.*)", line)
        if res:
            pid = int(res[0][0])
            if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:
                print "mythfilldatabase is running"
                return False

    return True



def idle_check():
    if  (   upcoming_check() and schemalock_check() and job_check()  and in_use() and  mfd_check()  ):
        idle=True
        print "Myth is idle"
    else:
        idle=False
        print "Myth is NOT idle"
    return idle

def run_stuff():
    if idle_check():
	print "Running optimize"
        optimize()

	print "Running backup"
        os.system('/usr/LH/bin/lh_system_backup_job')

	print "Running system_update"
	os.system('/usr/LH/bin/lh_system_host_update')
        continue_loop=False
    else:
        continue_loop=True
    return continue_loop

#---------------------------------
starttime=time.time()
ctin=True
while ctin:
    ctin=run_stuff()
    if  ctin:
        time.sleep(600)
    current_time=time.time()
    if (current_time - starttime) > 10800 :
        ctin = False
        print "time exceeded (3 hours)"
        exit(1)