#!/usr/bin/python
import sys, subprocess
import re
import socket
import os
import datetime,time
import shlex
sys.dont_write_bytecode = True

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

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

def get_timestamp():
    now = datetime.datetime.now()
    date = (now.strftime('%Y-%m-%d %H:%M'))
    return date

def getFreePercentForDir(dir):
    stats = os.statvfs(dir)
    total = (stats.f_blocks)
    avail = (stats.f_bavail)
    return (total - avail) / float(total)

def check_home():
    #get the mythtv home dir
    MYTHHOME=subprocess.check_output("lh_home_check.sh").decode('utf-8').strip()

    freePcent = getFreePercentForDir(MYTHHOME)
    print("  Home directory percent used: " + str(freePcent * 100) + "%")
    if float(freePcent) > .9:
        print("    Home directory is greater than 90% used. Clearing caches...")
        cmd = "/usr/bin/rm -rf " + MYTHHOME + "/.mythtv/{*cache,Cache-*,tmp/*,MythMusic/AlbumArt/*}"
        subprocess.call(["sh", "-c", cmd])
        print("    Restarting mythfrontend...")
        subprocess.call(["killall", "mythfrontend"])
        cmd = "/usr/bin/rm -rf " + MYTHHOME + "/.cache/*"
        subprocess.call(["sh", "-c", cmd])
        cmd = "/usr/bin/rm -rf " + MYTHHOME + "/.plexht/userdata/Thumbnails/*"
        subprocess.call(["sh", "-c", cmd])
        cmd = "/usr/bin/rm -rf " + MYTHHOME + "/.plexht/userdata/ThemeMusicCache/*"
        subprocess.call(["sh", "-c", cmd])
        freePcent = getFreePercentForDir(MYTHHOME)
        print("  Home directory percent used: " + str(freePcent * 100) + "%")
    else:
        print("    Home directory is less than 90% used. Not clearing caches.")
    return 0

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

def cleanup_inuseprograms():
    fourHoursAgo=datetime.datetime.today() - datetime.timedelta(hours=4)
    cmd="DELETE FROM inuseprograms WHERE lastupdatetime < '%s';" %fourHoursAgo
    try:
        cursor = mythtv.db.cursor()
        cursor.execute(cmd)
    except:
        print("\n%s Problem cleaning inuseprograms in database" %(get_timestamp()))


def bail_if_another_is_running():
    cmd = shlex.split("pgrep -u {} -f {}".format(os.getuid(), __file__))
    pids = subprocess.check_output(cmd).decode('utf-8').strip().split('\n')
    if len(pids) > 1:
        pids.remove("{}".format(os.getpid()))
        print("Exiting! Found {} is already running (pids): {}".format(
            __file__, " ".join(pids)))
        raise SystemExit(1)

def run_stuff():
    print("\n%s" %get_timestamp())

    if (len(sys.argv) == 1) or ("--noidlecheck" in sys.argv) and (len(sys.argv) == 2):
        runall = True
    else:
        runall = False

    if ("--noidlecheck" in sys.argv):
        print("No system idle check will be done.")
        idle = 0
    else:
        idle = subprocess.call(["/usr/bin/python", "/usr/bin/idle.py"])

    if not idle:
        if ("--check_home" in sys.argv) or runall:
            print("\n#######################################")
            print("\n%s Checking size of MythTV home" %(get_timestamp()))
            if not check_home():
                print("\nFinished checking size of MythTV home")
            else:
                return True

        if ("--optimize" in sys.argv) or runall:
            print("\n#######################################")
            print("\n%s Running Optimize" %(get_timestamp()))
            if not optimize():
                print("\nFinished Optimize")
            else:
                return True

        if ("--backup" in sys.argv) or runall:
            print("\n#######################################")
            print("\n%s Running Backup" %(get_timestamp()))
            if not os.system('sudo /usr/bin/lh_system_backup_job'):
                print("\nFinished Backup")

#        if ("--update" in sys.argv) or runall:
#            print("\n#######################################")
#            print("\n%s Running System Update" %(get_timestamp()))
#            if not os.system('/usr/bin/lh_system_host_update'):
#                print("\nFinished Update")

        print("\n#######################################")
        continue_loop=False
    else:
        continue_loop=True
    return continue_loop

#---------------------------------
bail_if_another_is_running()
starttime=time.time()
ctin=True
while ctin:
    cleanup_inuseprograms()
    ctin=run_stuff()
    if ctin:
        print("\n%s Waiting 10 minutes before trying again." %(get_timestamp()))
        time.sleep(600)

    current_time=time.time()
    if (current_time - starttime) > 3000 :
        ctin = False
        print("\n%s Time Exceeded 50 minutes. Quitting.)" %(get_timestamp()))
        exit(1)
