#!/usr/bin/env python

import MySQLdb
import base64, string

#mysql database information that will be derived via ingest.sh
HOST =
PORT =
USER =
PASS =
DB =

db = None
cursor = None

#executes the query and returns the result
def execute(query):
    global db
    global cursor
    if db is None:
        db = MySQLdb.connect(host=HOST, port=PORT, user=USER, passwd=PASS, db=DB)
        cursor = db.cursor()
    try:
        cursor.execute(query)
        db.commit()
        ret = cursor.fetchall()
    except:
	db.rollback()
        ret = None
        print "Failed query"

    return ret

#from hex output (that we don't use elsewhere), get a base64 version
def gdp_printable_name(hexVal):
    binary = base64.b16decode(hexVal.upper())
    stdb64 = base64.b64encode(binary)
    # convert to filesystem safe version
    return stdb64.translate(string.maketrans("/+","_-"), "=")

#takes in a single 'item' from the list of primary nodes as input.
#parse the dictionary to get the public IP of primary
def parse_primary(d):
    s = d["NodeID (IP:port)"]
    return s.split(":")[0]

#takes in a single 'item' from the list of secondary nodes as input
#ideally, instead of 'Secondary Nodes', it should be called:
#">bunch of secondary nodes that are behind same public IP<"
#parses the maze, and return a list of pub/priv pairs
def parse_secondary(d):
    pubIP = d["NATIP"]
    nodes = d["Nodes"]
    ret = []
    for n in nodes:
        tmp = n["NodeID (IP:port)"]
        privIP = tmp.split(":")[0]
        ret.append((pubIP, privIP))
    return ret
