otasigcheck: Rewrite for CM 13.0

Rewrite the packages.xml parser to be slightly less brittle.  Read
lines from packages.xml and save off the interesting values, then
compare with expected results afterward.

This both avoids using grep's -A option, which is not supported in
toybox, and allows the script to recognize the cert tag regardless
of its position inside the package tag.

Change-Id: Idc0006e38f4a3f9d5aec223a8a1571f5c11fe3bb
diff --git a/prebuilt/common/bin/otasigcheck.sh b/prebuilt/common/bin/otasigcheck.sh
index ad7f3a3..99fdaec 100644
--- a/prebuilt/common/bin/otasigcheck.sh
+++ b/prebuilt/common/bin/otasigcheck.sh
@@ -15,14 +15,71 @@
   exit 0
 fi
 
-if [ -f /data/system/packages.xml -a -f /tmp/releasekey ]; then
-  relCert=$(grep -A3 'package name="com.android.htmlviewer"' /data/system/packages.xml  | grep "cert index" | head -n 1 | sed -e 's|.*"\([[:digit:]][[:digit:]]*\)".*|\1|g')
+if [ -f "/data/system/packages.xml" -a -f "/tmp/releasekey" ]; then
+  relkey=$(cat "/tmp/releasekey")
+  OLDIFS="$IFS"
+  IFS=""
+  while read line; do
+    params=${line# *<package *}
+    if [ "$line" != "$params" ]; then
+      kvp=${params%% *}
+      params=${params#* }
+      while [ "$kvp" != "$params" ]; do
+        key=${kvp%%=*}
+        val=${kvp#*=}
+        vlen=$(( ${#val} - 2 ))
+        val=${val:1:$vlen}
+        if [ "$key" = "name" ]; then
+          package="$val"
+        fi
+        kvp=${params%% *}
+        params=${params#* }
+      done
+      continue
+    fi
+    params=${line# *<cert *}
+    if [ "$line" != "$params" ]; then
+      keyidx=""
+      keyval=""
+      kvp=${params%% *}
+      params=${params#* }
+      while [ "$kvp" != "$params" ]; do
+        key=${kvp%%=*}
+        val=${kvp#*=}
+        vlen=$(( ${#val} - 2 ))
+        val=${val:1:$vlen}
+        if [ "$key" = "index" ]; then
+          keyidx="$val"
+        fi
+        if [ "$key" = "key" ]; then
+          keyval="$val"
+        fi
+        kvp=${params%% *}
+        params=${params#* }
+      done
+      if [ -n "$keyidx" ]; then
+        if [ "$package" = "com.android.htmlviewer" ]; then
+          cert_idx="$keyidx"
+        fi
+      fi
+      if [ -n "$keyval" ]; then
+        eval "key_$keyidx=$keyval"
+      fi
+      continue
+    fi
+  done < "/data/system/packages.xml"
+  IFS="$OLDIFS"
 
   # Tools missing? Err on the side of caution and exit cleanly
-  if [ "z$relCert" == "z" ]; then exit 0; fi
+  if [ -z "$cert_idx" ]; then
+    echo "Package cert index not found; skipping signature check..."
+    exit 0
+  fi
 
-  grep "cert index=\"$relCert\"" /data/system/packages.xml | grep -q `cat /tmp/releasekey`
-  if [ $? -ne 0 ]; then
+  varname="key_$cert_idx"
+  eval "pkgkey=\$$varname"
+
+  if [ "$pkgkey" != "$relkey" ]; then
      echo "You have an installed system that isn't signed with this build's key, aborting..."
      exit 124
   fi