#!/usr/bin/env python

"""
This Python script extracts info from an iOS 5 incident report.
These report files can be found on your iPhone by using the "Settings" app
and going to General >> About >> Diagnostics & Usage >> Diagnostics & Usage Data
Copy the data from one of the "LowMemory" reports and paste it into a text file
on your Mac, then run this script on that text file. E.g.:
    python processLowMemReport.py report.txt

Cameron Hayne (macdev@hayne.net)  October 2011
"""

from __future__ import division
import sys
import re

def processFile(inputFile):
    foundHeader = False
    headerPattern = r'\s*Name\s+UUID\s+Count\s+resident\s+pages'
    headerRE = re.compile(headerPattern)
    infoPattern = r'\s*(?P<name>\S+)\s+(?:<(?P<uuid>[^>]+)>\s+)?(?P<numPages>\d+)'
    infoRE = re.compile(infoPattern)
    info = dict() # indexed by process name
    for line in inputFile:
        if headerRE.match(line):
            foundHeader = True
            continue

        if foundHeader:
            matches = infoRE.match(line)
            if matches:
                name = matches.group('name')
                uuid = matches.group('uuid')
                numPages = int(matches.group('numPages'))
                info[name] = (uuid, numPages)

    if not foundHeader:
        sys.exit("Didn't find header in report file")
    return info

# -----------------------------------------------------------------------------
# MAIN:
# -----------------------------------------------------------------------------
if len(sys.argv) < 2:
    sys.exit("Must supply incident report filename as command-arg")

pageSizeMB = 4 / 1024
reportFilePath = sys.argv[1]
totalMB = 0
printUuid = False
with open(reportFilePath) as inputFile:
    info = processFile(inputFile)
    for name in sorted(info.keys()):
        (uuid, numPages) = info[name]
        sizeMB = numPages * pageSizeMB
        totalMB += sizeMB
        if printUuid:
            print "%20s (%32s): %7.3f" % (name, uuid, sizeMB)
        else:
            print "%20s: %7.3f" % (name, sizeMB)
    print "Total MB: %.3f" % totalMB
