Expand insertkeys.py script to allow union of files.

Allow script to union mac_permissions.xml files
specified using the BOARD_SEPOLICY_DIRS and
BOARD_SEPOLICY_UNION constructs.

Change-Id: I4fc65fd1ab4c612f25e966f030247e54a270b614
Signed-off-by: rpcraig <rpcraig@tycho.ncsc.mil>
diff --git a/tools/insertkeys.py b/tools/insertkeys.py
index e4eeb43..509c43f 100755
--- a/tools/insertkeys.py
+++ b/tools/insertkeys.py
@@ -116,12 +116,16 @@
         handler.ContentHandler.__init__(self)
         self._keyMap = keyMap
         self._out = out
-
-    def startDocument(self):
         self._out.write(ReplaceTags.XML_ENCODING_TAG)
         self._out.write("<!-- AUTOGENERATED FILE DO NOT MODIFY -->")
+        self._out.write("<policy>")
+
+    def __del__(self):
+        self._out.write("</policy>")
 
     def startElement(self, tag, attrs):
+        if tag == ReplaceTags.POLICY_TAG:
+            return
 
         self._out.write('<' + tag)
 
@@ -140,6 +144,9 @@
             self._out.write('/>')
 
     def endElement(self, tag):
+        if tag == ReplaceTags.POLICY_TAG:
+            return
+
         if tag in ReplaceTags.TAGS_WITH_CHILDREN:
             self._out.write('</%s>' % tag)
 
@@ -157,10 +164,11 @@
 
     # Intentional double space to line up equls signs and opening " for
     # readability.
-    usage  = "usage: %prog [options] CONFIG_FILE MAC_PERMISSIONS_FILE\n"
-    usage += "This tool allows one to configure an automatic inclusion "
-    usage += "of signing keys into the mac_permision.xml file from the "
-    usage += "pem files."
+    usage  = "usage: %prog [options] CONFIG_FILE MAC_PERMISSIONS_FILE [MAC_PERMISSIONS_FILE...]\n"
+    usage += "This tool allows one to configure an automatic inclusion\n"
+    usage += "of signing keys into the mac_permision.xml file(s) from the\n"
+    usage += "pem files. If mulitple mac_permision.xml files are included\n"
+    usage += "then they are unioned to produce a final version."
 
     version = "%prog " + str(__VERSION)
 
@@ -180,11 +188,10 @@
     parser.add_option("-t", "--target-build-variant", default="eng", dest="target_build_variant",
                       help="Specify the TARGET_BUILD_VARIANT, defaults to eng")
 
-
     (options, args) = parser.parse_args()
 
-    if len(args) != 2:
-        parser.error("Must specify a config file (keys.conf) AND mac_permissions.xml file!")
+    if len(args) < 2:
+        parser.error("Must specify a config file (keys.conf) AND mac_permissions.xml file(s)!")
 
     logging.basicConfig(level=logging.INFO if options.verbose == True else logging.WARN)
 
@@ -205,4 +212,5 @@
     # Generate the XML file with markup replaced with keys
     parser = make_parser()
     parser.setContentHandler(ReplaceTags(key_map, output_file))
-    parser.parse(args[1])
+    for f in args[1:]:
+        parser.parse(f)