#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014, NORDUnet A/S.
# See LICENSE for licensing information.

import argparse
import json
import base64
import urllib
import urllib2
import sys
import time
import ecdsa
import hashlib
import urlparse
import os
import yaml
import select
import struct
from certtools import build_merkle_tree, create_sth_signature, \
    check_sth_signature, get_eckey_from_file, timing_point, http_request, \
    get_public_key_from_file, get_leaf_hash, decode_certificate_chain, \
    create_ssl_context

parser = argparse.ArgumentParser(description="")
parser.add_argument('--config', help="System configuration", required=True)
parser.add_argument('--localconfig', help="Local configuration", required=True)
parser.add_argument("--nomerge", action='store_true', help="Don't actually do merge")
parser.add_argument("--timing", action='store_true', help="Print timing information")
args = parser.parse_args()

config = yaml.load(open(args.config))
localconfig = yaml.load(open(args.localconfig))

ctbaseurl = config["baseurl"]
frontendnodes = config["frontendnodes"]
storagenodes = config["storagenodes"]
paths = localconfig["paths"]
mergedb = paths["mergedb"]

signingnodes = config["signingnodes"]
create_ssl_context(cafile=paths["https_cacertfile"])

chainsdir = mergedb + "/chains"
logorderfile = mergedb + "/logorder"

own_key = (localconfig["nodename"], "%s/%s-private.pem" % (paths["privatekeys"], localconfig["nodename"]))

logpublickey = get_public_key_from_file(paths["logpublickey"])

hashed_dir = True

def parselogrow(row):
    return base64.b16decode(row)

def get_logorder():
    f = open(logorderfile, "r")
    return [parselogrow(row.rstrip()) for row in f]

def write_chain(key, value):
    filename = base64.b16encode(key)
    if hashed_dir:
        path = chainsdir + "/" + filename[0:2] + "/" + filename[2:4] + "/" + filename[4:6]
        try:
            os.makedirs(path)
        except Exception, e:
            pass
    else:
        path = chainsdir
    f = open(path + "/" + filename, "w")
    f.write(value)
    f.close()

def read_chain(key):
    filename = base64.b16encode(key)
    path = chainsdir + "/" + filename[0:2] + "/" + filename[2:4] + "/" + filename[4:6]
    try:
        f = open(path + "/" + filename, "r")
    except IOError, e:
        f = open(chainsdir + "/" + filename, "r")
    value = f.read()
    f.close()
    return value

def add_to_logorder(key):
    f = open(logorderfile, "a")
    f.write(base64.b16encode(key) + "\n")
    f.close()

def get_new_entries(node, baseurl):
    try:
        result = http_request(baseurl + "ct/storage/fetchnewentries", key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            return [base64.b64decode(entry) for entry in parsed_result[u"entries"]]
        print "ERROR: fetchnewentries", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print "ERROR: fetchnewentries", e.read()
        sys.exit(1)

def get_entries(node, baseurl, hashes):
    try:
        params = urllib.urlencode({"hash":[base64.b64encode(hash) for hash in hashes]}, doseq=True)
        result = http_request(baseurl + "ct/storage/getentry?" + params, key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            entries = dict([(base64.b64decode(entry["hash"]), base64.b64decode(entry["entry"])) for entry in parsed_result[u"entries"]])
            assert len(entries) == len(hashes)
            assert set(entries.keys()) == set(hashes)
            return entries
        print "ERROR: getentry", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print "ERROR: getentry", e.read()
        sys.exit(1)

def get_curpos(node, baseurl):
    try:
        result = http_request(baseurl + "ct/frontend/currentposition", key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            return parsed_result[u"position"]
        print "ERROR: currentposition", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print "ERROR: currentposition", e.read()
        sys.exit(1)

def sendlog(node, baseurl, submission):
    try:
        result = http_request(baseurl + "ct/frontend/sendlog",
            json.dumps(submission), key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        return json.loads(result)
    except urllib2.HTTPError, e:
        print "ERROR: sendlog", e.read()
        return None
    except ValueError, e:
        print "==== FAILED REQUEST ===="
        print submission
        print "======= RESPONSE ======="
        print result
        print "========================"
        raise e

def sendentry(node, baseurl, entry, hash):
    try:
        result = http_request(baseurl + "ct/frontend/sendentry",
            json.dumps({"entry":base64.b64encode(entry), "treeleafhash":base64.b64encode(hash)}), key=own_key,
            verifynode=node, publickeydir=paths["publickeys"])
        return json.loads(result)
    except urllib2.HTTPError, e:
        print "ERROR: sendentry", e.read()
        sys.exit(1)
    except ValueError, e:
        print "==== FAILED REQUEST ===="
        print hash
        print "======= RESPONSE ======="
        print result
        print "========================"
        raise e

def sendsth(node, baseurl, submission):
    try:
        result = http_request(baseurl + "ct/frontend/sendsth",
            json.dumps(submission), key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        return json.loads(result)
    except urllib2.HTTPError, e:
        print "ERROR: sendsth", e.read()
        sys.exit(1)
    except ValueError, e:
        print "==== FAILED REQUEST ===="
        print submission
        print "======= RESPONSE ======="
        print result
        print "========================"
        raise e

def get_missingentries(node, baseurl):
    try:
        result = http_request(baseurl + "ct/frontend/missingentries", key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            return parsed_result[u"entries"]
        print "ERROR: missingentries", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print "ERROR: missingentries", e.read()
        sys.exit(1)

def chunks(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]

timing = timing_point()

logorder = get_logorder()

timing_point(timing, "get logorder")

certsinlog = set(logorder)

new_entries_per_node = {}
new_entries = set()
entries_to_fetch = {}

for storagenode in storagenodes:
    print "getting new entries from", storagenode["name"]
    new_entries_per_node[storagenode["name"]] = set(get_new_entries(storagenode["name"], "https://%s/" % storagenode["address"]))
    new_entries.update(new_entries_per_node[storagenode["name"]])
    entries_to_fetch[storagenode["name"]] = []

def unpack_entry(entry):
    pieces = []
    while len(entry):
        (length,) = struct.unpack(">I", entry[0:4])
        data = entry[4:4+length]
        entry = entry[4+length:]
        pieces.append(data)
    return pieces

import subprocess

def verify_entry(verifycert, entry, hash):
    unpacked = unpack_entry(entry)
    mtl = unpacked[0]
    assert hash == get_leaf_hash(mtl)
    s = struct.pack(">I", len(entry)) + entry
    try:
        verifycert.stdin.write(s)
    except IOError, e:
        sys.stderr.write("merge: unable to write to verifycert process: ")
        while 1:
            line = verifycert.stdout.readline()
            if line:
                sys.stderr.write(line)
            else:
                sys.exit(1)
    result_length_packed = verifycert.stdout.read(4)
    (result_length,) = struct.unpack(">I", result_length_packed)
    result = verifycert.stdout.read(result_length)
    assert len(result) == result_length
    (error_code,) = struct.unpack("B", result[0:1])
    if error_code != 0:
        print >>sys.stderr, result[1:]
        sys.exit(1)

timing_point(timing, "get new entries")

new_entries -= certsinlog

print "adding", len(new_entries), "entries"

if args.nomerge:
    sys.exit(0)

for hash in new_entries:
    for storagenode in storagenodes:
        if hash in new_entries_per_node[storagenode["name"]]:
            entries_to_fetch[storagenode["name"]].append(hash)
            break

verifycert = subprocess.Popen([paths["verifycert_bin"], paths["known_roots"]],
                              stdin=subprocess.PIPE, stdout=subprocess.PIPE)

added_entries = 0
for storagenode in storagenodes:
    print "getting", len(entries_to_fetch[storagenode["name"]]), "entries from", storagenode["name"]
    for chunk in chunks(entries_to_fetch[storagenode["name"]], 100):
        entries = get_entries(storagenode["name"], "https://%s/" % storagenode["address"], chunk)
        for hash in chunk:
            entry = entries[hash]
            verify_entry(verifycert, entry, hash)
            write_chain(hash, entry)
            add_to_logorder(hash)
            logorder.append(hash)
            certsinlog.add(hash)
            added_entries += 1
timing_point(timing, "add entries")
print "added", added_entries, "entries"

verifycert.communicate(struct.pack("I", 0))

tree = build_merkle_tree(logorder)
tree_size = len(logorder)
root_hash = tree[-1][0]
timestamp = int(time.time() * 1000)

tree_head_signature = None
for signingnode in signingnodes:
    try:
        tree_head_signature = create_sth_signature(tree_size, timestamp,
                                                   root_hash, "https://%s/" % signingnode["address"], key=own_key)
        break
    except urllib2.URLError, e:
        print e
if tree_head_signature == None:
    print >>sys.stderr, "Could not contact any signing nodes"
    sys.exit(1)

sth = {"tree_size": tree_size, "timestamp": timestamp,
       "sha256_root_hash": base64.b64encode(root_hash),
       "tree_head_signature": base64.b64encode(tree_head_signature)}

check_sth_signature(ctbaseurl, sth, publickey=logpublickey)

timing_point(timing, "build sth")

if args.timing:
    print timing["deltatimes"]

print "root hash", base64.b16encode(root_hash)

for frontendnode in frontendnodes:
    nodeaddress = "https://%s/" % frontendnode["address"]
    nodename = frontendnode["name"]
    timing = timing_point()
    print "distributing for node", nodename
    curpos = get_curpos(nodename, nodeaddress)
    timing_point(timing, "get curpos")
    print "current position", curpos
    entries = [base64.b64encode(entry) for entry in logorder[curpos:]]
    for chunk in chunks(entries, 1000):
        for trynumber in range(5, 0, -1):
            sendlogresult = sendlog(nodename, nodeaddress, {"start": curpos, "hashes": chunk})
            if sendlogresult == None:
                if trynumber == 1:
                    sys.exit(1)
                select.select([], [], [], 10.0)
                print "tries left:", trynumber
                continue
            break
        if sendlogresult["result"] != "ok":
            print "sendlog:", sendlogresult
            sys.exit(1)
        curpos += len(chunk)
        print curpos,
        sys.stdout.flush()
    timing_point(timing, "sendlog")
    print "log sent"
    missingentries = get_missingentries(nodename, nodeaddress)
    timing_point(timing, "get missing")
    print "missing entries:", len(missingentries)
    for missingentry in missingentries:
        hash = base64.b64decode(missingentry)
        sendentryresult = sendentry(nodename, nodeaddress, read_chain(hash), hash)
        if sendentryresult["result"] != "ok":
            print "send sth:", sendentryresult
            sys.exit(1)
    timing_point(timing, "send missing")
    sendsthresult = sendsth(nodename, nodeaddress, sth)
    if sendsthresult["result"] != "ok":
        print "send sth:", sendsthresult
        sys.exit(1)
    timing_point(timing, "send sth")
    if args.timing:
        print timing["deltatimes"]