#!/usr/bin/python2
# checks for the number of days of guide data left
# make sure myth_mtc ran ok


import urllib2
import string
import time , datetime
import sys,os
from MythTV import MythBE,MythDB,MythLog


#0=green
#1=yellow
#2=red



BBLINE = ''
BBCOLOR="green"
DATE = time.strftime("%a %b %d %H:%M:%S %Z %Y", time.localtime(time.time()))


if os.environ['BB']:
    #print os.environ['BB']
    BB=os.environ['BB']
if os.environ['BBDISP']:
    #print os.environ['BBDISP']
    BBDISP=os.environ['BBDISP']
if os.environ['MACHINE']:
    #print os.environ['MACHINE']
    MACHINE=os.environ['MACHINE']

#MACHINE='a'
#BB='b'
#BBDISP='12'


def set_color_code (current_color, new_color):
    if new_color > current_color:
        color = new_color
    else:
        color = current_color
    return color

def set_color(color_code):
    color = "unknown"
    if color_code == 0 :
        color = "green"
    elif color_code == 1 :
        color = "yellow"
    elif color_code == 2 :
        color = "red"
    
    return color
    
    



def check_mtc(mtc_file):
    line=''
    try:
        infile = open(mtc_file, 'r')
    except(IOError), e:
        print "couldn't open %s file" %mtc_file
        return False
    else:
        mtc = infile.readlines()
        infile.close()
        for i in mtc:
            line=i
        if line.split()[0] == "Finished":
            return True
        else:
            return False

def find_data_left():
    days_left = 0
    today = datetime.datetime.today()
    try:
        be=MythBE()
        db = MythDB()
        cursor = db.cursor()
    except:
        days_left = -100
        return days_left
    try:
        cmd="select max(starttime) from program ;"
        cursor.execute(cmd)
        results=cursor.fetchall()[0][0]
        days_left = (results - today).days
    except:
        days_left = "Undetermined"
    return days_left


now = datetime.datetime.now()
#date = "%s-%s-%s" %(now.year, now.month, now.day)
date = (now.strftime('%Y-%m-%d')) 
#2013-12-03
mtc_file = "/var/log/%s/myth_mtc.log" %date

mtc=check_mtc(mtc_file)
num_days=find_data_left()


current_color=0

if mtc:
    current_color = set_color_code(current_color,0)
    msg="\n Maintenance script was successful \n       Log file: %s\n    " %mtc_file
else:
    current_color = set_color_code(current_color,2)
    msg='''
 ** Maintenance script did not run. **
    BACKUP FILE WAS NOT CREATED
    
    The system may have been busy
    Log file: %s  \n''' %mtc_file

if num_days ==  1 :
    current_color = set_color_code(current_color,1)
    msg+="\n ** Only 1 day of guide data left **"
elif num_days == 0 :
    current_color = set_color_code(current_color,2)
    msg+="\n ** No guide data available **"

elif num_days == -100 :
    current_color = set_color_code(current_color,2)
    msg+="\n ** Could not connect to database ** "

elif num_days == "Undetermined" :
    current_color = set_color_code(current_color,1)
    msg+="\n ** Could not determine how many days of guide data are available ** "    

else:
    data_check = True
    current_color = set_color_code(current_color,0)
    msg+="\n %s days of guide data" %(num_days)

if os.path.isfile("/data/storage/disk0/backup/system_backups/remote_backup_failed.txt"):
    current_color = set_color_code(current_color,1)
    msg+="\n\n ** Remote backup jobs are queued **"
else:
    msg+="\n\n No remote backup jobs queued"




BBLINE = msg
BBCOLOR = set_color(current_color)

LINE = "status " + MACHINE  + ".myth_mtc" + " " + BBCOLOR +  " " + DATE + " " + BBLINE
cmd = BB + ' ' + BBDISP + ' "' + LINE + '"'
os.system(cmd)
#print cmd
#print BBLINE
#print BBCOLOR



sys.exit(0)