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

import argparse
import base64
import sys
import subprocess
from certtools import build_merkle_tree
from mergetools import *

parser = argparse.ArgumentParser(description="")
parser.add_argument('--mergedb', help="Merge database", required=True)
parser.add_argument('--verifycert', help="Path to verifycert program", required=True)
parser.add_argument('--knownroots', help="Path to knownroots directory", required=True)
args = parser.parse_args()

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

verifycert = subprocess.Popen([args.verifycert, args.knownroots],
                              stdin=subprocess.PIPE, stdout=subprocess.PIPE)

logorder = get_logorder(logorderfile)

for hash in logorder:
    entry = read_chain(chainsdir, hash)
    verify_entry(verifycert, entry, hash)

tree = build_merkle_tree(logorder)
root_hash = tree[-1][0]

print base64.b16encode(root_hash)