from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from time import gmtime, strftime
from mydatabase import *
import subprocess
import requests
import redis
import MySQLdb
import base64
import time
import json
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

ashconfig_api = Blueprint('ashconfig_api', __name__)



def queryfilter(filter):
    url = "https://pb-cho.eng.fireeye.com:8000/api/stats"
    response = requests.post(url, auth=(username,password), json={"filter":[filter]}, verify=False )
    print response.text
    try:
       payload = json.loads(response.text)
    except:
       print "ERROR"
       pass

    print payload

    return



@ashconfig_api.route('/getlinkinfo/', methods=['POST'])
def getlinkinfo():

    sname = request.form['servername']
    port  = request.form['port']
    p     = int(port)

    if p > 3:
       device = 1
       p = p - 3
    else:
       device = 0

    commandstring = "python /home/veronica/tcp-client.py status --rate -s hhreplay -g %s -d %s -p %s" % (sname, device, p)
    print commandstring
    res = subprocess.check_output(commandstring, shell=True)
    result = json.loads(res)

    if result['status'] == "success":
       rate = str(result['message'])
    else:
       rate = "0.0"

    commandstring = "python /home/veronica/tcp-client.py status --loop -s hhreplay -g %s -d %s -p %s" % (sname, device, p)
    print commandstring
    res = subprocess.check_output(commandstring, shell=True)
    result = json.loads(res)

    if result['status'] == "success":
       loop = str(result['message'])
    else:
       loop = "0"

    retstring = rate + "*" + loop

    return retstring



@ashconfig_api.route('/savevalues/', methods=['POST'])
def savevalues():
    sname = request.form['servername']
    loops = request.form['loops']
    rates = request.form['rates']

    loop = loops.split('*')
    rate = rates.split('*')

    print loop
    print rate

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % sname
    cr.execute(sql)
    result = cr.fetchall()
    location = result[0][7]

    ls = base64.b64encode(json.dumps(loop))
    rs = base64.b64encode(json.dumps(rate))

    sql = "UPDATE servers SET rate='%s', pcaploop='%s' where name='%s';" % (rs, ls, sname)
    cr.execute(sql)
    db.commit()

    initializeDatabase()

    target = location.lower() + "_api." + location.lower()
    return redirect(url_for(target))



@ashconfig_api.route('/cancelpcapload/', methods=['POST'])
def cancelpcapload():
    location = request.form['location']
    target = location.lower() +	"_api."	+ location.lower()
    return redirect(url_for(target))

@ashconfig_api.route('/configureserver/', methods=['POST'])
def configureserver():
    pos   = int(request.form['position'])
    sname = request.form['servername']
    pcap  = request.form['pcap']

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % sname
    cr.execute(sql)
    result = cr.fetchall()
    location = result[0][7]
    pc = result[0][17]
    pcaps = json.loads(base64.b64decode(pc))
    pcaps[pos] = pcap
    ps = base64.b64encode(json.dumps(pcaps))
    sql = "UPDATE servers SET pcaps='%s' where name='%s';" % (ps, sname)
    cr.execute(sql)
    db.commit()

    initializeDatabase()

    target = location.lower() + "_api." + location.lower()
    return redirect(url_for(target))


@ashconfig_api.route('/configure/', methods=['POST'])
def configure():
    sname = request.form['servername']
    location = request.form['location']

    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    sql = "SELECT * FROM servers where name='%s';" % sname
    cr.execute(sql)
    result = cr.fetchall()
    pc = result[0][17]
    pcaps = json.loads(base64.b64decode(pc))
    lp = result[0][14]
    loops = json.loads(base64.b64decode(lp))
    rt = result[0][13]
    rate  = json.loads(base64.b64decode(rt))

    plen = len(pcaps)

    hstr = '<h2>%s</h2>' % sname
    hstr = hstr + '<table><th>Port</th><th style="text-align:center">Rate</th><th style="text-align:center">Loop</th><th style="text-align:center">Pcap</th>'
    
    for i in range(0,plen):
        hstr = hstr + '<tr>'
        hstr = hstr + '<td style="width:40px;">&nbsp;<b>%s</b></td>' % i
        hstr = hstr + '<td><input size=5 id=rate%s type=text value=%s></td>' % (i, rate[i])
        hstr = hstr + '<td><input size=5 id=loop%s type=text value=%s></td>' % (i, loops[i])
        hstr = hstr + '<td><input size=45 id=pcap%s type=text value=%s></td>' % (i, pcaps[i])
        pname = "'" + sname + "'"
        hstr = hstr + '<td><input size=6 style="padding:6px;" type=button id=load%s onclick="javascript:loadpcap(%s, %s);" value=Load></td>' % (i, pname, i)
        hstr = hstr + '<tr><td style="height:2px;" colspan=5> &nbsp; </td><tr>'
    hstr = hstr + '</table>'
    hstr = hstr + '<input type="hidden" id="location" value="%s">' % location
    hstr = hstr + '<br><div style="float:right;">'
    hstr = hstr + '<input type=button style="width:80px;padding:10px;margin-right:10px;" size=10 id="submit" onclick="javascript:saveValues(%s,%s);" value="Save">' % (pname, plen)
    hstr = hstr + '<input type=button style="width:80px;padding:10px;" size=10 id="cancel" onclick="javascript:closeBox();" value="Cancel"></div>'
    hstr = hstr + '<input type=hidden id=plen value="%s">' % plen
    return str(hstr)


@ashconfig_api.route('/queryserver/', methods=['POST'])
def queryserver():
    sname  = request.form['sname']
    flicid = request.form['flicid']
    string = ""

    if flicid == "":
       retstring = '<div style="text-align:center;margin-bottom:40px;"><h2>%s</h2></div><br><div>Virtual Consumer</div>' % sname
       return retstring

    url = "http://artie.eng.fireeye.com/api/v1/machines?asset_id=%s" % flicid
    print url
    response = requests.get(url, verify=False)
    try:
       payload = json.loads(response.text)
    except:
       retstring = '<div style="text-align:center;margin-bottom:40px;"><h2>%s</h2></div><br><div>Virtual Consumer</div>' % sname
       return retstring

    m = payload['machines']
    machines = m[0]
    reserved = machines['reserved_by']
    task = machines['task']
    retstring = queryflic(flicid, reserved, task)
    return retstring


def queryflic(flicid, reserved, task):
    url = "https://flic.fireeye.com/api/v1/assets/%s" % flicid
    response = requests.get(url, verify=False)
    payload = json.loads(response.text)

    hostname = payload['hostname']

    network  = payload['networks'][0]
    type0    = 'Management'
    netmask0 = network['netmask']
    ip_addr0 = network['ip_address']
    mac_adr0 = network['mac_address']
    gatewy_0 = network['gateway']

    try:
       network  = payload['networks'][1]
       type1    = network['nw_type']
       netmask1 = network['netmask']
       ip_addr1 = network['ip_address']
       mac_adr1 = network['mac_address']
       gatewy_1 = network['gateway']
    except:
       type1    = "None"
       netmask1 = ""
       ip_addr1 = ""
       mac_adr1 = ""
       gatewy_1 = ""

    cname    = payload['cname']
    make     = payload['make']
    model    = payload['model']

    location = payload['location']
    city     = location['city']
    rack     = location['rack']
    slot     = location['slot']

    try:
       terminal = payload['terminal_server']
       portname = terminal['name'] + '.eng.fireeye.com'
       myport   = int(terminal['port'])
       portstring = 'ssh -p22%02d %s' % ( myport, portname )
    except:
       portstring = "Unknown"

    headstring = '<div style="text-align:center;margin-bottom:40px;"><h2>%s</h2></div>' % hostname

    tablestring0 = '''
    <table>
    <td style="width:270px;">Reserved:</td><td>%s</td>
    <tr>
    <td>Task:</td><td>%s</td>
    <tr>
    <td> &nbsp; </td><td> &nbsp; </td>
    </table>''' % (reserved, task)

    spacerstring = '<div style="padding:10px;"></div>'

    tablestring1 = '''
    <table>
    <td style="width:270px;">%s IP</td><td>%s</td>
    <tr>
    <td>%s Mask</td><td>%s</td>
    <tr>
    <td>%s Gateway</td><td>%s</td>
    <tr>
    <td>%s macAddr</td><td>%s</td>
    <tr>
    <td> &nbsp; </td><td> &nbsp; </td>
    </table>
    ''' % ( type0, ip_addr0, type0, netmask0, type0, gatewy_0, type0, mac_adr0 )       #'''

    tablestring2 = '''
    <table>
    <td style="width:270px;">%s IP</td><td>%s</td>
    <tr>
    <td>%s Mask</td><td>%s</td>
    <tr>
    <td>%s Gateway</td><td>%s</td>
    <tr>
    <td>%s macAddr</td><td>%s</td>
    <tr>
    <td> &nbsp; </td><td> &nbsp; </td>
    </table>
    ''' % (type1, ip_addr1, type1, netmask1, type1, gatewy_1, type1, mac_adr1)

    tablestring3 = '''
    <table>
    <td style="width:270px;">City</td><td>%s</td>
    <tr>
    <td>Model</td><td>%s</td>
    <tr>
    <td>Rack</td><td>%s</td>
    <tr>
    <td>Slot</td><td>%s</td>
    <tr>
    <td> &nbsp; </td><td> &nbsp; </td>
    </table>
    ''' % ( city, model, rack, slot)  #'''

    flic = "https://flic.fireeye.com/inv_assets/{}".format(flicid)
    mbx = "https://my.mbx.com/inventory/system/index.cfm?mbx_serial={}".format(payload['serial_number'])
    art_url = "http://artie.eng.fireeye.com/#{}".format(flicid)

    tablestring8 = '''
    <table>
    <td style="width:80px;">Console</td><td>%s</td>
    <tr>
    <td> &nbsp; </td><td> &nbsp; </td>
    <tr>
    <td>flic</td><td><a href="%s" target="_blank">%s</a></td>
    <tr>
    <td>mbx</td><td><a href="%s" target="_blank">%s</a></td>
    <tr>
    <td>artie</td><td><a href="%s" target="_blank">%s</a></td>
    <td> &nbsp; </td><td> &nbsp; </td>
    </table>
    ''' % (portstring, flic, flic,  mbx, mbx, art_url, art_url)

    htmlstring = headstring + tablestring0 + tablestring1 + tablestring2 + tablestring3 + tablestring8
    return htmlstring


@ashconfig_api.route('/deleteserver/', methods=['POST'])
def deleteserver():
    # delete from mysql
    sname  = request.form['servername']
    sql = "DELETE FROM servers where name='%s';" % sname
    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()
    cr.execute(sql)
    db.commit()

    # delete from redis
    r = redis.Redis(host='127.0.0.1', port='6379')
    count = int(r.get("totalBoxCount")) + 1
    for i in range(1, count):
        rkey = "server-%d" % i
        if r.hget(rkey,'name') == sname:
           r.delete(rkey)
           break

    initializeDatabase()

    return redirect(url_for('ashconfig_api.ashburnConfigure'))

# update server info from form
@ashconfig_api.route('/updateserver/', methods=['POST'])
def updateserver():
    sname  = request.form['servername']
    type   = request.form['type']
    flic   = request.form['flic']
    loc    = request.form['loc']
    ports  = request.form['ports']
    pcfg   = request.form['pcfg']
    scfg   = request.form['scfg']

    p = ports.replace(" ","")
    pl = len(p)
    q  = pl/2

    rate = []
    pcaploop = []
    linkstatus = []
    playstatus = []
    pcaps = []
    pathstart = {}
    pathend = {}

    for i in range(0,q):
        rate.append(0)
        pcaploop.append(0)
        linkstatus.append(True)
        playstatus.append('stop')
        pcaps.append('1.pcap')

    if type == 'consumer':
       fill = '#ddffdd'
    else:
       fill = '#ffdddd'

    serverdata ={
        "name"        : sname,
        "type"        : type,
        "disabled"    : False,
        "active"      : True,
        "reserved"    : "",
        "flicid"      : flic,
        "location"    : loc,
        "ports"       : ports.split(),
        "portconfig"  : pcfg.split(),
        "switchports" : scfg.split(),
        "pathstart"   : pathstart,
        "pathend"     : pathend,
        "rate"        : rate,
        "pcaploop"    : pcaploop,
        "linkstatus"  : linkstatus,
        "playstatus"  : playstatus,
        "pcaps"       : pcaps,
        "stroke"      : "black",
        "fill"        : fill
    }
    datablock = json.dumps(serverdata)
    updateData(datablock)

    return redirect(url_for('ashconfig_api.ashburnConfigure'))


# Save server info from form
@ashconfig_api.route('/saveserver/', methods=['POST'])
def saveserver():
    sname  = request.form['servername']
    type   = request.form['type']
    flic   = request.form['flic']
    loc    = request.form['loc']
    ports  = request.form['ports']
    pcfg   = request.form['pcfg']
    scfg   = request.form['scfg']

    p = ports.replace(" ","")
    pl = len(p)
    q  = pl/2

    rate = []
    pcaploop = []
    linkstatus = []
    playstatus = []
    pcaps = []
    pathstart = {}
    pathend = {}

    for i in range(0,q):
        rate.append(0)
        pcaploop.append(0)
        linkstatus.append(True)
        playstatus.append('stop')
        pcaps.append('1.pcap')

    if type == 'consumer':
       fill = '#ddffdd'
    else:
       fill = '#ffdddd'
 
    serverdata ={
        "name"        : sname,
        "type"        : type,
        "disabled"    : False,
        "active"      : True,
        "reserved"    : "",
        "flicid"      : flic,
        "location"    : loc,
        "ports"       : ports.split(),
        "portconfig"  : pcfg.split(),
        "switchports" : scfg.split(),
        "pathstart"   : pathstart,
        "pathend"     : pathend,
        "rate"        : rate,
        "pcaploop"    : pcaploop,
        "linkstatus"  : linkstatus,
        "playstatus"  : playstatus,
        "pcaps"       : pcaps,
        "stroke"      : "black",
        "fill"        : fill
    }
    datablock = json.dumps(serverdata)
    insertData(datablock)

    initializeDatabase()

    return redirect(url_for('ashconfig_api.ashburnConfigure'))

# display all boxes in the database for editing

@ashconfig_api.route('/ashconfig/', methods=['GET','POST'])
def ashburnConfigure():

    servers = []

    sql = "SELECT * FROM servers;"
    db = MySQLdb.connect(host="localhost", passwd="veronicaHammerhead27!", db="veronica")
    cr = db.cursor()

    cr.execute(sql)
    result = cr.fetchall()

    for data in result:
        inputJson   = translateData(data)
        indata      = json.loads(inputJson)
        servername  = indata['name']
        type        = indata['type']
        disabled    = indata['disabled']
        active	    = indata['active']
        reserved    = indata['reserved']
        location    = indata['location']
        flicid      = indata['flicid']
        ports       = indata['ports']
        portconfig  = indata['portconfig']
        switchports = indata['switchports']
        rate        = indata['rate']
        pcaploop    = indata['loop']
        linkstatus  = indata['linkstatus']
        playstatus  = indata['playstatus']
        pcaps	    = indata['pcaps']
        stroke	    = indata['stroke']
        fill        = indata['fill']

        serverrecord = [ data[0], servername, type, reserved, ports, portconfig, switchports, flicid, location ]
        servers.append(serverrecord)

    total = len(servers)

    return render_template('ashconfig.html', servers=servers, total=total)
