#!/usr/bin/python
# coding: utf-8
from lxml import etree
import sys

if len(sys.argv) < 3:
    print "Usage " + sys.argv[0] + " key_file tanker_xml [keyset prefix]"
    exit(1)
keyset_prefix = ""
if len(sys.argv) > 3:
    keyset_prefix = sys.argv[3].strip()
keys_file = open(sys.argv[1])
tanker_xml = etree.parse(sys.argv[2])
missing = 0
total = 0
for line in keys_file.xreadlines():
    total = total + 1
    line = line.strip()
    parts = line.split(":")
    keyset = parts[2].strip("{")
    key = parts[3].strip("}")
    if len(key) + 2 != len(parts[3]) or len(keyset) + 2 != len(parts[2]):
        print "ERR: Badly placed {{{{ }}}} for {0}:{1} ({2} line {3})".format(keyset, key, xml_file, xml_file_line)
        missing = missing + 1
    else:
        keyset = keyset_prefix + keyset
        xml_file = parts[0]
        xml_file_line = parts[1]
        keyxpath = unicode('//project[@id="mpro"]/keyset[@id="{0}"]/key[@id="{1}"]'.format(keyset, key), "cp1251")
        if len(tanker_xml.xpath(keyxpath)) == 0:
            print "ERR: Not found key for {0}:{1} ({2} line {3})".format(keyset, key, xml_file, xml_file_line)
            missing = missing + 1
if missing > 0:
    print "Need fix for " + str(missing) + " out of " + str(total)
else:
    print "Tanker refs are OK."
sys.exit(missing)
