#!/usr/bin/python2
import sys
import cgi
import os
import socket
import time
import StringIO

try:
    import cgitb
    cgitb.enable()
except ImportError:
    sys.stderr = sys.stdout
def cgiprint(inline=''):
    sys.stdout.write(inline)
    sys.stdout.write('\r\n')
    sys.stdout.flush()
contentheader = 'Content-Type: text/html'

def getform(theform, valuelist, notpresent='', nolist=False):
    """
    This function, given a CGI form as a
    FieldStorage instance, extracts the
    data from it, based on valuelist
    passed in. Any non-present values are
    set to '' - although this can be
    changed. (e.g. to return None so you
    can test for missing keywords - where
    '' is a valid answer but to have the
    field missing isn't.) It also takes a
    keyword argument 'nolist'. If this is
    True list values only return their
    first value.
    """
    data = {}
    for field in valuelist:
        if not theform.has_key(field):
        #  if the field is not present (or was empty)
            data[field] = notpresent
        else:
        # the field is present
            #print type(theform[field])
            if  type(theform[field]) != type([]):
            # is it a list or a single item
                #print type(theform[field])
                data[field] = theform[field].value
            else:
                if not nolist:
                # do we want a list ?
                    data[field] = theform.getlist(field)
                else:
                    data[field] = theform.getfirst(field)
                    # just fetch the first item
    return data

def getall(theform, nolist=False):
    """
    Passed a form (cgi.FieldStorage
    instance) return *all* the values.
    This doesn't take into account
    multipart form data (file uploads).
    It also takes a keyword argument
    'nolist'. If this is True list values
    only return their first value.
    """
    data = {}
    for field in theform.keys():
    # we can't just iterate over it, but must use the keys() method
        if type(theform[field]) ==  type([]):
            if not nolist:
                data[field] = theform.getlist(field)
            else:
                data[field] = theform.getfirst(field)
        else:
            data[field] = theform[field].value
    return data

def isblank(indict):
    """
    Passed an indict of values it checks
    if any of the values are set. Returns
    True if the indict is empty, else
    returns False. I use it on the a form
    processed with getform to tell if my
    CGI has been activated without any
    form values.
    """
    for key in indict.keys():
        if indict[key]:
            return False
    return True

def go_backup(myhost):
    myhostname = socket.gethostname()
    results="Nothing happened"
    command= "sudo /usr/LH/bin/lh_system_backup_job"
    #print command

    command2="sleep 1; sudo -u nobody /home/xymon/server/ext/hbnotes.py"
    results=os.popen(command,'r')
    os.popen(command2,'r')

    return  results

def go_download_backup(dl_file):
    # Actual File Content will go hear.
    dlf = "/data/storage/disk0/backup/system_backups/%s" %dl_file
    fo = open(dlf, "rb")

    str = fo.read()
    fo.close()

    # HTTP Header
    print "Content-Type:application/octet-stream; name=\"%s\"\r\n;" %(dl_file)
    print "Content-Disposition: attachment; filename=\"%s\"\r\n;" %(dl_file)
    print "Content-Length: %d" % len(str)
    print ""

    print str
    return results

def go_restore(restorefile,myhost,prestore):
    myhostname = socket.gethostname()
    psc = ''
    if prestore == "on":
        psc = "partial"

    if myhostname.strip() == myhost.strip():
        command="sudo /usr/LH/bin/lh_system_restore_job %s  %s" %(restorefile , psc)
    else:
        #this should never execute
        sshcmd="ssh -o StrictHostKeyChecking=no -o ConnectTimeout=1 -i /data/srv/.nobody_ssh/id_dsa mythtv@"
        sshcmd+=myhost.strip()
        cmd=' "sudo /usr/bin/restore_job.sh   "   '
        command=sshcmd + cmd + restorefile + " 2>&1 "
    #print command
    results=os.popen(command,'r')
    return  results

def go_upload(up_file):
    saveDir = "/data/storage/disk0/backup/system_backups/"
    fPath = "%s/%s" % (saveDir, up_file.filename)
    buf = up_file.file.read()
    bytes = len(buf)
    sFile = open(fPath, 'wb')
    sFile.write(buf)
    sFile.close()
    results=["<b>%s</b> uploaded (%d bytes)." %(up_file.filename, bytes)]
    line = '''The backup has been uploaded and is now available for restore.
    To restore from the file, check "Restore database" then select the file from the drop down menu'''

    results.append(line)

    command2="sleep 1; sudo -u nobody /home/xymon/server/ext/hbnotes.py"
    os.popen(command2,'r')

    return results

def go_optimize(myhost):
    #myhostname = socket.gethostname()
    #if myhostname.strip() == myhost.strip():
    command="/usr/LH/bin/optimize_mythdb.py"
    #print command
    results=os.popen(command,'r')
    #else:
        #results='This host does not run a database'
    return  results

def go_update(myhost,update_type):
    cmd=" call pacman update_system "
    cmd+=update_type
    command="/usr/bin/func \"" + myhost.strip() + "*\"  " + cmd
    #print command
    results=os.popen(command,'r')
    return  results

def go_updateall(allupdate_type):
    cmd=" sudo /usr/bin/update_system_all "
    cmd+=allupdate_type
    command= cmd + " 2>&1 "
    results=os.popen(command,'r')
    return  results

def go_shutdown(myhost):
    myhostname = socket.gethostname()
    message="Shutdown from MBE"
    command="/usr/bin/func \"" + myhost.strip() +  "*\" call msg display \"%s\" " %message
    results=os.popen(command,'r')
    time.sleep(3)
    command="/usr/bin/func \"" + myhost.strip() +  "*\" call power poweroff "
    results=os.popen(command,'r')
    return  results

def go_shutdownall():
    import MySQLdb
    #import mysql
    #find all hosts(minus myself)
    #loop through results shutdown as we go.
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")
    # create a cursor
    cursor = db.cursor()
    # execute SQL statement
    myhostname = socket.gethostname()
    results=["Sent shutdown command to: \n "]
    cursor.execute("SELECT distinct(hostname) from settings where not  hostname = %s ; ",(myhostname))
    result = cursor.fetchall()

    for row in result:
         go_shutdown(row[0])
         results.append(row[0])

    #shutdown myself.
    #go_shutdown(myhostname)
    #results.append(myhostname)
    return  results

def go_reboot(myhost):
    myhostname = socket.gethostname()
    message="Reboot from MBE"
    command="/usr/bin/func \"" + myhost.strip() +  "*\" call msg display \"%s\" " %message
    results=os.popen(command,'r')
    time.sleep(3)

    command="/usr/bin/func \"" + myhost.strip() +  "*\" call power reboot "
    results=os.popen(command,'r')
    return  results

def go_wake(myhost):
    command="/usr/MythVantage/bin/wakeonlan.sh " + myhost.strip()
    results=os.popen(command,'r')
    return  results

def go_kill(myhost,kill_type):
    myhostname = socket.gethostname()
    cmd=" call fe_restart "
    cmd+=kill_type
    command="/usr/bin/func \"" + myhost.strip() + "*\"  " + cmd

    results=os.popen(command,'r')
    return  results

def go_restart_mbe_local():
    cmd = "/usr/LH/bin/lh_backend_control.sh restart &"
    #results=os.popen(cmd,'r')
    os.popen(cmd,'r')
    results = ["Attempting restart of backend service"]
    return  results


mainpage = '''
<html>
    <head>
        <style type="text/css">@import "/frame.css";</style>
        <meta http-equiv="cache-control" content="max-age=0">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
        <meta http-equiv="pragma" content="no-cache">
        <title>LinHES</title>
    </head>
    <body>
    %s
    </body>
</html>
'''


loadingpage = '''
<html>
    <head>
        <style type="text/css">@import "/frame.css";</style>
        <script src="/ajaxloader.min.js"></script>
        <meta http-equiv="cache-control" content="max-age=0">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
        <meta http-equiv="pragma" content="no-cache">
        <title>LinHES</title>
    </head>
    <body>
        <div id="header">
            %s
        </div>
        <div id="container">
            <br><br>
            <h3>Working. Please Wait...</h3>
            <br><br>
            <div>
                <canvas id="spinner"></canvas>
            </div>
        </div>
        <script type="text/javascript">
            var opts = {
                size: 72,           // Width and height of the spinner
                factor: 0.25,       // Factor of thickness, density, etc.
                color: "#ebb81c",      // Color #rgb or #rrggbb
                speed: 1.0,         // Number of turns per second
                clockwise: true     // Direction of rotation
            };
            var ajaxLoader = new AjaxLoader("spinner", opts);
            ajaxLoader.show();
        </script>
'''


error = '''
    <h1>Error</h1>
    <h2>No Form Submission Was Received</h2>'''


result = '''
    <h1>%s of %s</h1>
'''

possible_parameters = ['param1', 'param2', 'param3', 'param4','hiddenparam','param5','param6','param7','uFile','param8']

if __name__ == '__main__':

    theform = cgi.FieldStorage()
    #print theform
    formdict = getform(theform, possible_parameters)
    #print possible_parameters

    if isblank(formdict):
        body = error
    else:
        name = formdict['param1']
        radio = formdict['param2']  # should be 'this' or 'that'
        if radio != 'Restore' :
            name = ""
        update_type = formdict['param3']
        oldurl = formdict['param4']
        hidden = formdict['hiddenparam']
        all_update_type=formdict['param5']
        kill_type = formdict['param6']
        dl_file = formdict['param7']
        try:
            up_file = theform['uFile']
        except:
            pass
        try:
            prestore = theform['param8'].value
        except:
            prestore = "off"
        body = result % (radio, hidden)

    selection=radio
    myhost=hidden.lower()

    if selection == "Restore":
        mylogfile=go_restore(name,myhost,prestore)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "Backup":
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print loadingpage % body
        mylogfile=go_backup(myhost)
    elif selection == "Dbackup":
        mylogfile=go_download_backup(dl_file)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "Update":
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print loadingpage % body
        mylogfile=go_update(myhost,update_type)
    elif selection == "Shutdown":
        mylogfile=go_shutdown(myhost)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "Reboot":
        mylogfile=go_reboot(myhost)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "Optimize":
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print loadingpage % body
        mylogfile=go_optimize(myhost)
    elif selection == "WOL":
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print loadingpage % body
        mylogfile=go_wake(myhost)
    elif selection == "UpdateAll":
        mylogfile=go_updateall(all_update_type)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "ShutdownAll":
        mylogfile=go_shutdownall()
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "Kill":
        mylogfile=go_kill(myhost,kill_type)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "Upload":
        mylogfile = go_upload(up_file)
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body
    elif selection == "RestartMBE":
        mylogfile = go_restart_mbe_local()
        cgiprint(contentheader)   # content header
        cgiprint()                # finish headers with blank line
        print mainpage % body

    cgiprint()                # finish headers with blank line

    box='''<br><br>
    <div id="resultbox" >

    '''

    endbox='''

     </div>
    '''
    javascript='''
    <script type="text/javascript">
        document.getElementById("container").style.display = 'none';
        ajaxLoader.hide();
        var objDiv = document.getElementById("resultbox");
        objDiv.scrollTop = objDiv.scrollHeight;
    </script>
    '''

    print box
    for line in mylogfile:
        print line + '<br> \r\n'

    print endbox
    print "<br><br>"
    #print '<a href=',  oldurl,     '  > Back </a> '
    s='<a href="%s"><img src="back.png"></a>' %oldurl
    print s
    #<a href="myfile.htm"><img src="rainbow.gif"></a>
    #print oldurl
    print javascript
