#!/usr/bin/env python

# Copyright (c) 2015 Tim Savannah GPLv2
# You should have recieved a copy of LICENSE with this distrubition. Details on the license can be found therein
#
# This is a program that scans the running processes of a system for mappings (running executable, shared library, something else) and prints the results

# vim: set ts=4 sw=4 expandtab

import os
import sys


import ProcessMappingScanner


if __name__ == '__main__':
    if len(sys.argv) not in (2, 3) or '--help' in sys.argv:
        sys.stderr.write('Usage: findProcessesUsing (options) [library name part]\n\n Searches all running processes for those containing a given mapping portion. This could be the running executable (like python), or a shared library, or other mapping.\n\n  Options:\n\n    -v or --verbose\t\tAlso print mapping lines containing the given pattern\n\nExample: findProcessesUsing libpython2.7\n\nIt is recommended to run this process as root, otherwise you are only able to scan your own processes.\n\n')
        sys.exit(1)

    if os.getuid() != 0:
        sys.stderr.write('Warning: You are not root. Results will only contain processes for which you are the owner.\n\n')



    isVerbose = False

    for verboseOption in ('-v', '--verbose'):
        if verboseOption in sys.argv:
            isVerbose = True
            sys.argv.remove(verboseOption)
            break

    searchPortion = sys.argv[1]

    scanResults = ProcessMappingScanner.scanAllProcessessForMapping(searchPortion)
    pids = scanResults.keys()
    for pid in pids:
        result = scanResults[pid]
        sys.stdout.write('Found %s in %d (%s) [ %s ]\n' %(searchPortion, result['pid'], result['owner'], result['cmdline']))
        if isVerbose is True:
            sys.stdout.write('\n'.join(["\t" + line for line in result['matchedMappings']]) + '\n\n')

