#!/usr/bin/python
# ===========================================================================
# eXe
# Copyright 2004-2005, University of Auckland
# Copyright 2006-2008 eXe Project, http://eXeLearning.org/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#t
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# ===========================================================================
"""
The LliureX patch
"""

import subprocess
import os
class SystemProcess:
	
	def __init__(self):
		self.process_list=[]
		self.get_process_list()
		#print self.get_user_process_list("hector")
		#print self.find_process("python /usr/bin/exe")
	#def init 
	
	def get_process_list(self):
		
		
		
		self.process_list=[]
		
		p=subprocess.Popen(["ps","aux"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		output=p.communicate()[0]
		lst=output.split("\n")
		lst.pop(0)
		
		for item in lst:
			processed_line=item.split(" ")
			tmp_list=[]
			
			if len(processed_line) >= 10:
				for object in processed_line:
					if object!="":
						tmp_list.append(object)
				processed_line=tmp_list
				
				process={}
				process["user"]=processed_line[0]
				process["pid"]=processed_line[1]
				process["cpu"]=processed_line[2]
				process["mem"]=processed_line[3]
				process["vsz"]=processed_line[4]
				process["rss"]=processed_line[5]
				process["tty"]=processed_line[6]
				process["stat"]=processed_line[7]
				process["start"]=processed_line[8]
				process["time"]=processed_line[9]
				cmd=""
				for string in processed_line[10:]:
					if cmd!="":
						cmd+=" "
					cmd+=string
					
				process["command"]=cmd
				self.process_list.append(process)
		
	#def get_process_list
	
	
	def get_user_process_list(self,user):
		
		ret_list=[]
		
		for process in self.process_list:
			if process["user"]==user:
				ret_list.append(process)
				
		return ret_list
		
	#def get_user_process_list
	
	def find_process(self,filter):
		
		ret_list=[]
		for process in self.process_list:
			if filter in process["command"]:
				ret_list.append(process)
				
		return ret_list
		
	#def find_process
	
	
#class SystemProcess



"""
The eXe main script
"""

import os
import sys

# Try to work even with no python path
try:
    from exe.application import Application
except ImportError, error:
    if str(error) == "No module named exe.application":
        exePath = os.path.abspath(sys.argv[0])
        exeDir  = os.path.dirname(exePath)
        pythonPath = os.path.split(exeDir)[0]
        sys.path.insert(0, pythonPath)
        from exe.application import Application
    else:
        import traceback
        traceback.print_exc()
        sys.exit(1)

def main():
    application = Application()
    application.main()

if __name__ == "__main__":
    #lliurex
    sp=SystemProcess()
    for process in sp.find_process("python /usr/bin/exe"):
        if os.getpid() != int(process["pid"]):
            p=subprocess.Popen(["kill","-9",process["pid"]])
            p.communicate()
    #lliurex
    main()
