#!/usr/bin/env python3
#
# SYNTAX
#
#     pinfo <process_name>
#
# DESCRIPTION
#
#     Prints process memory information.
#

import sys
import os
import subprocess
import re
import json

def term(s):
    r  = subprocess.run(s, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return r.stdout.decode("utf-8")

def yank(p, q):
    s = term("cat {} | grep {}".format(p, q))
    if s is None or len(s) == 0:
        return None
    return re.split(" +", s.strip())

if __name__ == "__main__":
    argv = sys.argv[1:]
    argc = len(argv)

    if argc == 0:
        print("[ERROR] Missing argument")
        quit(1)

    process_name = argv[0]

    # Collect target procesesses
    results = term("ps -A | grep -E ' {}$'".format(process_name)).strip()

    if len(results) == 0:
        print("[INFO] Process name does not exist")
        quit(0)

    results = results.split("\n")

    # Collect process pids
    pids = []
    for result in results:
        match = re.match('^([0-9]{1,})', result)
        if match is not None:
            pids.append(match.group(1))

    # Collect data
    info = {}
    info[process_name] = {
        "# processes": len(pids)
    }
    for pid in pids:
        try:
            vm_size = yank("/proc/" + pid + "/status", "VmSize")[1:]
            fields = {
                "name": None,
                "pid": pid,
                "vm_size": vm_size
            }
            if info[process_name].get("data") is None:
                info[process_name]["data"] = [ fields ]
            else:
                info[process_name]["data"].append(fields)
        except Exception:
            pass

    print(json.dumps(info, indent = 4, sort_keys = True))
