#!/usr/bin/python3

from optparse import OptionParser
import os
import sys
import re
import pwd
import time

def get_cmdline(pid):
    # A process may exec, so we must always reread its cmdline
    cmdlinepath=os.path.join("/proc",pid,"cmdline")
    try:
        proc_cmdline = open(cmdlinepath)
    except IOError:
        return '{no such process}'
    cmdline = proc_cmdline.read(4096)
    parts = cmdline.split('\0')
    #first_command_char = parts[0].rfind('/') + 1
    #parts[0] = parts[0][first_command_char:]
    cmdline = ' '.join(parts).strip()
    return cmdline.encode('string_escape')


def catfile(filename):
    '''Print a file to the standard output.'''
    f = file(filename)
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end=' ') # notice comma
    f.close()

def kill_all_user_processes(signal,killuser):

    numonly=re.compile('^\d+$')

    procdir = os.listdir("/proc")

    for pid in procdir:
        if numonly.match(pid):
            #print pid,
            statuspath=os.path.join("/proc",pid,"status")
            cmdlinepath=os.path.join("/proc",pid,"cmdline")
            try:
                #t = open("/proc"."/".pid."/"."status")
                t = open(statuspath)
                v = t.read()
                t.close()

                i = v.index("Uid")
                vu = v[i:].split(None, 3)  # whitespace
                #print vu
                uid=vu[1]

                i = v.index("Name")
                vn = v[i:].split(None, 3)  # whitespace
                #print vn[1]
                cmdname=vn[1]


                try:
                    uname = pwd.getpwuid(int(uid))[0]
                except KeyError:
                    print('Unknown user:', uid, file=sys.stderr)
                    error = True

                cmdline=get_cmdline(pid)

                pidint=int(pid)
                uidint=int(uid)


                killreason=0
                killexplanation=""
                exceptionexplanation=""

                if uidint >= 1000:
                    killreason=killreason+1;
                    killexplanation+="high user id"



                if killuser != "":
                    #if a name is specified on the command line, kill not matter what!
                    if killuser == uname:
                        killreason=20;
                        exceptionexplanation+="owned by specified kill user "
                    else:
                        killreason=0;
                        exceptionexplanation+="not owned by specified kill user "

#also we could look for exceptions of users not to kill, not implemented yet
#    exception_uids=["somedontkillusername","anotherdontkillusername"]
#    kill_uids=["guest1","guest5"]
#    try:
#        exception_uid_match = exception_uids.index(uname)
#        killreason=0;
#       exceptionexplanation+=" uname exception match "
#    except ValueError:
#        pass
#        #exceptionexplanation+=" no uname exception match "





                if killreason > 0:
                    print("dokill",signal,": ",pidint,",",uidint,",",uname,",",cmdname,",",cmdline,", reason: ",killexplanation,", exceptions: ",exceptionexplanation)
                    os.kill(pidint,signal)
                else:
                    print("    nokill: ",pidint,",",uidint,",",uname,",",cmdname,",",cmdline,", exceptions: ", exceptionexplanation)

            except:
                print("no longer active:",pid, file=sys.stderr)


#MAIN
parser = OptionParser()
parser.add_option("-u", "--user", dest="killuser", default="", help="user to kill processes of")

(options, args) = parser.parse_args()
killuser=options.killuser


kill_all_user_processes(15,killuser)
time.sleep(2)
kill_all_user_processes(9,killuser)
