#!/usr/bin/env python
# coding=utf-8

##	Qemulator 0.3 - a qemu gui written in python and GTK/Glade.
##	Copyright (C) 2006  rainer haage
##
##	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.
##	
##	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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
import threading
from threading import Thread
import gobject
import string
import sys
import os
from os import path
import shutil
import tempfile
import getopt
import re
import pickle
import time
from copy import copy
import webbrowser

import locale
import gettext

gobject.threads_init()

try:
	import pygtk
	pygtk.require("2.0")
	
except:
	  print "pygtk 2.0 is not installed"
try:
	import gtk
	import gtk.glade
	
except:
	print "gtk and/or glade is not installed - exiting..."
	sys.exit(1)

APP = 'Install'
DIR = 'locale'

locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
gettext.install(APP, DIR, unicode=1)
_ = gettext.gettext

gtk.glade.bindtextdomain(APP, DIR)
gtk.glade.textdomain(APP)
tooltips = gtk.Tooltips() 

basedir = os.path.dirname(os.path.realpath(__file__))
print "basedir: " + str(basedir)

## Configuration variables for this installation
## All relative paths have to be entered without leading slash!

## Set the path for the install resources relative to the installer home directory whithout trailing but with leading slash##
sourcefolder = "/usr/local"
## Set the absolute path to the default prefix folder for your application whithout trailing slash##
default_prefix = "/usr/local"
## The URL to your donation site. If donation button should not be visible, leave blank ##
donateurl = "http://qemulator.createweb.de/index.php4?aliasdoc=210"

## Define which optional extra buttons will be shown
## possible values are True/False
show_button_licence = True
show_button_relnotes = True
show_button_donate = True

## Set the paths for all document files relative to the installer home directory
licence_file = "LICENCE"
licence_wintitle = "GNU General Public Licence"
relnotes_file = "release_notes"
relnotes_wintitle = "Release notes"

# End of configuration area. Don't touch anything from here!

## This is the template class for any installation. It defines the structure
## of the installation to be used for all install/uninstall proceedings.
class Installation:
    def __init__(self):
    	
    	
        self.installfiles = []
        self.installdirs = []
        #self.prefix = "/usr/local"
        self.prefix = default_prefix
        self.defaultprefix = default_prefix

        print "prefix: " + self.prefix
    def get_removedirs(self):
        removedirs = []
        dirsfile = open( "uninstalldirs" ,"r")
        checkdirs = dirsfile.readlines()
        dirsfile.close()
        for dir in self.installdirs:
            #print "------------\nInstallation removedir: \n%s\n" %dir
            dir = string.strip(dir)
            for checkdir in checkdirs:
                checkdir = string.strip(checkdir)
                #print "---\nInstallation checkdir: %s" %checkdir
                if checkdir != "":
                    expression = self.prefix + checkdir
                    #print "expression: \n" + expression + "\n dir: \n" + dir
                    re_fdir = re.match(expression, dir)
                    if re_fdir != None:
                        fdir = str(re_fdir.group())
                        #print fdir
                        #print "expression2: " + expression + 
                        #print " dir: " + dir
                        removedirs.append(dir)
                    else:
                        #print "not found: " + str(re_fdir)
                        pass

        return removedirs

class Installer(Thread):
	def __init__(self):
		Thread.__init__(self)
		#self.prefix = "/home/rainer/usr/local"
		#gtk.main()
		self.runcommand = None
		self.prefix = default_prefix
		self.defaultprefix = copy(default_prefix)
		self.sourcefolder = sourcefolder
		self.basedir = str(basedir)
		print "basedir: " + self.basedir
		
		self.installset = ()
		self.instdirs = []
		self.instfiles = []
		self.donateurl = donateurl		
		self.workstep = 1
		self.do_uninstall = False
		self.password = ""
		
		self.gladefile = "./setup.glade"
		self.dialog_setup = gtk.glade.XML(self.gladefile, "dialog_setup", APP)
		
		self.frame1 = self.dialog_setup.get_widget("frame1")
		self.frame2 = self.dialog_setup.get_widget("frame2")
		self.frame3 = self.dialog_setup.get_widget("frame3")
		self.frame4 = self.dialog_setup.get_widget("frame4")
		self.frame5 = self.dialog_setup.get_widget("frame5")
		
		self.closebutton = self.dialog_setup.get_widget("closebutton")
		self.cancelbutton = self.dialog_setup.get_widget("cancelbutton")
		self.installbutton = self.dialog_setup.get_widget("installbutton")
		self.nextbutton = self.dialog_setup.get_widget("nextbutton")
		self.backbutton = self.dialog_setup.get_widget("backbutton")
		
		self.button_relnotes = self.dialog_setup.get_widget("button_relnotes")
		self.button_licence = self.dialog_setup.get_widget("button_licence")
		self.donatebutton = self.dialog_setup.get_widget("donatebutton")
		
		if show_button_licence == False:
			self.button_licence.hide()
		if show_button_relnotes == False:
			self.button_relnotes.hide()
		if show_button_donate == False:
			self.donatebutton.hide()						
			
		self.radiobutton_install = self.dialog_setup.get_widget("radiobutton_install")
		self.radiobutton_update = self.dialog_setup.get_widget("radiobutton_update")
		self.radiobutton_uninstall = self.dialog_setup.get_widget("radiobutton_uninstall")
		
		#self.checkbutton_gnomenu = self.dialog_setup.get_widget("checkbutton_gnomenu")
		#self.checkbutton_kdemenu = self.dialog_setup.get_widget("checkbutton_kdemenu")
		
		self.entry_installprefix = self.dialog_setup.get_widget("entry_installprefix")
		
		self.checkbutton_starmenu_gnome = self.dialog_setup.get_widget("checkbutton_starmenu_gnome")
		self.checkbutton_starmenu_kde = self.dialog_setup.get_widget("checkbutton_starmenu_kde")
		
		self.label_prefixtitle = self.dialog_setup.get_widget("label_prefixtitle")
		self.label_installtitle = self.dialog_setup.get_widget("label_installtitle")
		self.label_summarytitle = self.dialog_setup.get_widget("label_summarytitle")
		self.label_prefixtext = self.dialog_setup.get_widget("label_prefixtext")
		self.label_summarytext = self.dialog_setup.get_widget("label_summarytext")
		self.label_sum_installprefix = self.dialog_setup.get_widget("label_sum_installprefix")
		self.label_intro = self.dialog_setup.get_widget("label_intro")
		self.label_startmenuentrys = self.dialog_setup.get_widget("label_startmenuentrys")
		self.label_done = self.dialog_setup.get_widget("label_done")
		
		#self.checkbutton_gnomenu = self.dialog_setup.get_widget("checkbutton_gnomenu")
		#self.checkbutton_kdemenu = self.dialog_setup.get_widget("checkbutton_kdemenu")		
		self.progressbar_total = self.dialog_setup.get_widget("progressbar_total")
		#self.progressbar_total.pulse()
		self.frame2.hide()
		self.frame3.hide()
		self.frame4.hide()
		self.frame5.hide()
		
		self.closebutton.hide()
		self.installbutton.hide()
		
		introtext_nodonation = "Qemulator is free software under the terms of the GPL. "\
		"For details see the LICENCE Document in the installation folder or read "\
		"licence informations under help in the installed application."
		
		if self.donateurl == "":
			self.donatebutton.hide()
			self.label_intro.set_text(introtext_nodonation)
		
		dic = {"on_dialog_setup_response" : self.dialog_setup_response,
			   "on_dialog_setup_close" : self.destroy_event,
			   "on_dialog_setup_delete_event" : self.destroy_event,
			   "on_nextbutton_clicked" : self.gonext,
			   "on_backbutton_clicked" : self.goback,
			   "on_installbutton_clicked" : self.doaction,
			   "on_donatebutton_clicked" : self.dodonate,
			   "on_button_relnotes_clicked" : self.open_releasenotes,
			   "on_button_licence_clicked" : self.open_licence,
		}
		self.dialog_setup.signal_autoconnect(dic)
		if os.environ["PWD"] != basedir:
			print "please run this script from inside it's folder!"
			exit
		else:	
			print "Qemulator installer"

	def print_srcfiles(self):
		instdirs, instfiles = self.read_srcfiles()
		print "----------------------------------------------------"		
		print "Dirs to install: "
		for sdir, tdir in instdirs:
			print sdir + " -- " + tdir
		print "----------------------------------------------------"
		print "Files to install: "
		for sfile, tfile in instfiles:
			#print line
			print sfile + " -- " + tfile
		print "----------------------------------------------------"
		
						
	def read_srcfiles(self):
		#command = "ls -R " + basedir + self.sourcefolder + "/* " + self.prefix + "/"
		outputs = []
		instdirs = []
		instfiles = []
		command = "ls -R ." + self.sourcefolder
		child_stdin, child_stdout, child_stderr  = os.popen3(command)
		child_stdin.flush()
		child_stdin.close()
		outputs = child_stdout.readlines()
		child_stderr.close()
		child_stdout.close()
		dir = ""	
		sourcefolder = str(path.realpath(basedir + "/" + self.sourcefolder))
		#print "sourcefolder: " + sourcefolder
		for line in outputs:
			
			line = string.strip(line)
			dircheck = re.match(".+\:$", line)  
			if dircheck != None:
				dir = line.replace(':', '')
				dir = str(path.abspath(dir))
				tdir = dir.replace(sourcefolder, '')
				tdir = self.prefix + tdir
				if dir != sourcefolder:
					instdirs.append((dir, tdir))
				#print "tdir: " + str(tdir)
			else:
				#print "file: " + str(dir + "/" + line)
				#file = str(path.abspath(dir + "/" + line))
				file = str(dir + "/" + line)
				#print "file: " + str(file)
				tfile = file.replace(sourcefolder, '')
				tfile = self.prefix + tfile
				#file = str(line)
				if not path.isdir(file):
					instfiles.append((file, tfile))
					#print file
		#print "----------------------------------------------------" 
		return (instdirs, instfiles)
	                
	def dialog_setup_response(self, widget, response, *entry):
	    if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_CLOSE:
	        self.destroy_event(widget)
	        
	        
	def run(self):

		self.check_installed()	
		gtk.gdk.threads_init()
		#gtk.threads_enter()
		gtk.main()
		#gtk.threads_leave()			

	def open_releasenotes(self, *widget):
		Textbrowser(relnotes_file, _(relnotes_wintitle))
		
	def open_licence(self, *widget):
		Textbrowser(licence_file, _(licence_wintitle))		
		
		
	def gonext(self,widget):
		if self.frame1.flags() & gtk.VISIBLE:
			self.frame1.hide()
			self.frame2.show()
			self.check_installed(widget)
			print "2 VISIBLE!"
			
		elif self.frame2.flags() & gtk.VISIBLE:
			self.frame2.hide()
			self.prefix = self.entry_installprefix.get_text()
			self.label_sum_installprefix.set_text(self.prefix)
			self.installset = self.read_srcfiles()
			self.print_srcfiles()
			
			if self.do_uninstall == True:
				self.frame4.show()
				self.installbutton.show()
				self.nextbutton.hide()	
							
			else:
				self.frame4.show()
				self.installbutton.show()
				self.nextbutton.hide()		
			print "3 VISIBLE!"		
			
		elif self.frame3.flags() & gtk.VISIBLE:
			self.frame3.hide()
			self.frame4.show()
			self.installbutton.show()
			self.nextbutton.hide()
			print "4 VISIBLE!"
									
		
	def goback(self,widget):
		if self.frame4.flags() & gtk.VISIBLE:
			print "3 VISIBLE!"
			self.frame4.hide()
			self.installbutton.hide()
			self.nextbutton.show()
			if self.do_uninstall == True:
				self.frame2.show()
			else:
				self.frame2.show()			
		elif self.frame3.flags() & gtk.VISIBLE:
			print "2 VISIBLE!"
			self.frame3.hide()
			self.frame2.show()
		elif self.frame2.flags() & gtk.VISIBLE:
			print "1 VISIBLE!"
			self.frame2.hide()
			self.frame1.show()	
			self.nextbutton.set_sensitive(True)
			
	def check_installed(self, *widget):
		self.do_uninstall = self.radiobutton_uninstall.get_active()
		self.do_update = self.radiobutton_update.get_active()
		self.do_install = self.radiobutton_install.get_active()
		
		print "do_uninstall " + str(self.do_uninstall)
		print "do_update " + str(self.do_update)
		print "do_install " + str(self.do_install)
		print "defaultprefix " + str(self.defaultprefix)				
		#self.do_uninstall = uninstat
		histavail = False
		print "histavail: " + str(histavail)
		button_icon = gtk.Image()
		print "Uninstall: " + str(self.do_uninstall)
		self.install_history = {}

		is_installed = self.check_installpath()
		try:
			self.install_history = getfromfile(self.prefix + "/lib/qemulator/install_history")
			print "History: " + str(self.install_history)
			histavail = True
			print "histavail: " + str(histavail)
			
			if self.install_history == {}:
				histavail = False
				print "histavail: " + str(histavail)
			else:
				print "Found install history at: " + self.prefix + "/lib/qemulator/install_history"
				histavail = True
				print "histavail: " + str(histavail)
		except:
			histavail = False
			print "histavail: " + str(histavail)
			
		if histavail == False:
			try:
				self.install_history = getfromfile(self.basedir + "/install_history")
				histavail = True
				print "histavail: " + str(histavail)
				if self.install_history == {}:
					histavail = False
					print "histavail: " + str(histavail)
				else:
					
					histavail = True	
					print "histavail: " + str(histavail)
					print "Found install history at: ./install_history"				
			except:
				histavail = False
				print "histavail: " + str(histavail)

		if self.do_install == True:
		    print "no Uninstall: " + str(self.do_uninstall)
		    self.label_prefixtitle.set_markup("<b>Enter the prefix path for the installation</b>")
		    self.label_installtitle.set_markup("<b>Ready to install</b>")
		    self.label_summarytitle.set_markup("<b>Install Settings:</b>")
		    self.label_prefixtext.set_text("Usually the default \"" + self.defaultprefix + "\" should work fine.\n"\
		    							   "If you don't know what to do just leave it with the default value.")
		    self.label_summarytext.set_text("Ok, we are ready for install now. Check your settings below and\n"\
		    								"hit \"Install\" if everything is fine.")
		    self.label_startmenuentrys.set_markup("<b>Startmenu entry(s): </b>")			
		    
		    self.label_done.set_markup("<b>Installation Starting</b>\n"\
		    						   "Waiting for your password...")
		    button_icon.set_from_icon_name("gtk-ok", gtk.ICON_SIZE_BUTTON)
		    self.installbutton.set_image(button_icon)
		    self.installbutton.set_label("Install")		
		    self.entry_installprefix.set_text(self.defaultprefix)	
		
		if histavail == True:
			self.radiobutton_install.set_sensitive(False)
			self.radiobutton_update.set_active(True)
			
			self.history_prefix = self.install_history.prefix
			self.entry_installprefix.set_text(self.history_prefix)
			histavail = True
			print "histavail: " + str(histavail)
			print "install history loaded"
							
			#print "Installed files:\n"
			#for file in self.install_history.installfiles:
			#	print file
			removedirs = self.install_history.get_removedirs()
			#if removedirs != []:
			    #print "Remove dirs: \n"
			    #for dir in removedirs:
			    #    print dir
			if self.do_uninstall == True:    
				self.label_prefixtitle.set_markup("<b>The prefix path of the installation</b>")
				self.label_installtitle.set_markup("<b>Ready to uninstall</b>")
				self.label_summarytitle.set_markup("<b>Uninstall Settings:</b>")
				
				if is_installed != True:
					self.label_prefixtext.set_markup("<span foreground='darkred'>No installation found. The path shown above is guessed from the last stored installation history."\
												   "If you installed qemulator in a locatinon that is not in the 'path' environment variable of the system,"\
												   "the installer can not detect the installation. In this case, enter the correct prefix here or go on with the"\
												   "suggestion if you think it's correct. In worst case just nothing happens.</span>")
				else:
					self.label_prefixtext.set_text("The installer detected an installation at \"" + self.prefix + "\"\n"\
											   "if you think this is correct, please continue without any changes")
				self.label_summarytext.set_text("Ok, we are ready for uninstall now. Check your settings below and\n"\
				"hit \"Uninstall\" if everything is fine.")
				self.label_startmenuentrys.set_markup("<b>Remove startmenu entry(s): </b>")
				self.label_done.set_markup("<b>Uninstall Starting</b>\n"\
		    						   "Waiting for your password...")
				button_icon.set_from_icon_name("gtk-ok", gtk.ICON_SIZE_BUTTON)
				self.installbutton.set_image(button_icon)			
				self.installbutton.set_label("Uninstall")
				self.entry_installprefix.set_text(self.history_prefix)	

			elif self.do_update == True:
				print "no Ininstall: " + str(self.do_uninstall)
				self.label_prefixtitle.set_markup("<b>Enter the prefix path for the installation</b>")
				self.label_installtitle.set_markup("<b>Ready to update</b>")
				self.label_summarytitle.set_markup("<b>Update Settings:</b>")
				self.label_prefixtext.set_text("Update will be installed in the same path as the old version.\n"\
											   "If you want to install it to an other location, change the prefix path to your needs.")
				self.label_summarytext.set_text("Ok, we are ready for update now. Check your settings below and\n"\
												"hit \"Update\" if everything is fine.")
				self.label_startmenuentrys.set_markup("<b>Startmenu entry(s): </b>")			
				
				self.label_done.set_markup("<b>Update Starting</b>\n"\
									   "Waiting for your password...")
				#self.installbutton.set_label("Install")
				button_icon.set_from_icon_name("gtk-ok", gtk.ICON_SIZE_BUTTON)
				self.installbutton.set_image(button_icon)
				self.installbutton.set_label("Update")		
				self.entry_installprefix.set_text(self.history_prefix)
		else:
			self.radiobutton_update.set_sensitive(False)
			self.radiobutton_uninstall.set_sensitive(False)
			self.radiobutton_install.set_active(True)			
			if self.do_uninstall == True or self.do_update == True:
			    print "No install history found. Uninstall not possible!"
			    self.label_prefixtext.set_markup("<span foreground='darkred'>No install history found. Uninstall not possible!</span>")
			    self.nextbutton.set_sensitive(False)			    		    

		#self.checkbutton_starmenu_gnome.set_label("Remove entry from the gnome startmenu")
	def check_installpath(self):
		checkinst = os.popen("which qemulator")
		installed = False
		returnval = checkinst.readlines()
		print "searching for an installation: "
		if returnval != "":
		    try:
		        installbin = str(string.strip(returnval[0]))
		        self.prefix = installbin.replace ( '/bin/qemulator', '' ) 
		        print "installation found: " + self.prefix
		        self.entry_installprefix.set_text(self.prefix)
		        installed = True
		    except:
		        self.entry_installprefix.set_text("")
		        #self.label_prefixtext.set_text("No installation found. If you installed qemulator in a direction that is not\n"\
		        #"in the path variable of the system, please enter the correct prefix here")
		        installed = False
		else:
			print "No installation found on check"
			installed = False
		return installed
	
	def check_passwd(self, password):
		check_command = "sudo -S echo password ok"	
		child_stdin, child_stdout, child_stderr  = os.popen3(check_command)
		child_stdin.write(password)	
		child_stdin.flush()
		child_stdin.close()
		outputs = child_stdout.readlines()				
		print "Result passcheck: " + str(outputs)
		#print "Error: " + str(errors)
		#print "Start uninstall Errors: "
		if outputs == []:
			installerror = "You entered a wrong password, please reenter your password:\n"
			print "No pass return!"
			inst_error = True
			child_stderr.close()
			child_stdout.close()
			#if self.pwderr_func != None:
			#	self.pwderr_func(installerror)		 		
			return False
		else:
			return True	

	def doaction(self,widget):
	
	    if self.do_uninstall == True:
	    	#self.uninstall()
	    	self.run_uninstall()
	    else:
	    	self.run_install()

	def storetofile(self, indata, filename):
	    dumpf = open("./" + filename ,"w")
	    pickle.dump(indata, dumpf)
	    dumpf.close()
	    
	def storetotmp(self, indata):
		tmpfile = tempfile.NamedTemporaryFile('w')
		tmpfile_name = str(tmpfile.name)
		tmppic = file(tmpfile_name,'w+')
		dopic = pickle.dump(indata, tmppic)
		tmppic.close()	    
		print "dopic: " + str(dopic)
		return tmpfile	    
	    
	def getfromfile(self, filename):
	    outdata  = { }
	    try:
	        abs_path = path.abspath("./" + filename)
	        abs_path = filename
	        print "opened file absolute path: " + abs_path
	        dumpf = open( abs_path ,"r")
	        outdata = pickle.load(dumpf)
	        dumpf.close()
	        return outdata
	    except:
	        outdata  = { }
	        print "no install history file found"
	        return outdata     

	def run_install(self):
		self.frame4.hide()
		self.frame5.show()
		self.closebutton.show()
		self.installbutton.hide()
		self.cancelbutton.set_sensitive(False)
		self.backbutton.set_sensitive(False)
		self.closebutton.set_sensitive(False)		

		curruser = os.environ['USER']
		print "user: " +curruser
		if curruser != "root":
			print "run sudo"
			self.su_install()  
		else:        
			if self.do_update == True:
				#doinstall = Doinstall("update", "root", self.finishedfunc)
				doinstall = Doinstall("update", self.prefix, self.installset, "root")
				doinstall.start()
				time.sleep(0.3)
			else:
				#doinstall = Doinstall("install", "root", self.finishedfunc)
				doinstall = Doinstall("install", self.prefix, self.installset, "root")
				doinstall.start()
				time.sleep(0.3)					
		    
	def run_uninstall(self):
		self.frame4.hide()
		self.frame5.show()
		self.closebutton.show()
		self.installbutton.hide()
		self.cancelbutton.set_sensitive(False)
		self.backbutton.set_sensitive(False)
		self.closebutton.set_sensitive(False)		

		curruser = os.environ['USER']
		print "user: " +curruser
		if curruser != "root":
			print "run sudo"
			self.su_install()  
		else:
			#douninstall = Doinstall("uninstall", "root", self.finishedfunc)
			douninstall = Doinstall("uninstall", self.prefix, None, "root")
			douninstall.start()	
									              
	def su_install(self, message=None):
		print "started suinstall"
		self.dialog_sudo = gtk.glade.XML(self.gladefile, "dialog_sudo", APP)
		self.dlg_sudo = self.dialog_sudo.get_widget("dialog_sudo")
		self.label_sudo_text = self.dialog_sudo.get_widget("label_sudo_text")
		self.entry_password = self.dialog_sudo.get_widget("entry_password")
		okbutton_sudo = self.dialog_sudo.get_widget("okbutton_sudo")
		
		if message != None:
			self.label_sudo_text.set_text(str(message))
		
		dic = {"on_dialog_sudo_response" : self.dialog_sudo_response,
			   "on_okbutton_sudo_clicked" : self.dummy,
		}
		self.dialog_sudo.signal_autoconnect(dic)
		self.password = self.entry_password.get_text()		
		
	def dialog_sudo_response(self, widget, response, *entry):
		print "sudo response"
		if response == gtk.RESPONSE_CANCEL:
			self.closebutton.set_sensitive(True)
			print "cancel clicked"
			#exit
			widget.destroy ()	
		if response == gtk.RESPONSE_OK:
			print "ok clicked"
			
			self.entry_password = self.dialog_sudo.get_widget("entry_password")
			self.password = copy(self.entry_password.get_text())
			#gtk.threads_enter()
			widget.destroy () 
			#gtk.threads_leave()	
			time.sleep(0.2)	
			self.sudo_response()
			
	def sudo_response(self):
		
			check_passwd = self.check_passwd(self.password)
			if check_passwd == True:
				if self.do_uninstall == True:
					print "starting uninstall as sudoer"
					#douninstall = Doinstall("uninstall", "sudo", self.finishedfunc, self.password, self.su_install)
					douninstall = Doinstall("uninstall", self.prefix, None, "sudo", self.password, self.su_install)
					douninstall.start()
					self.label_done.set_markup("<b>Uninstall running</b>\n"\
										   "Wait until finished...")				
				elif self.do_update == True:
					print "starting update as sudoer"	
					#doinstall = Doinstall("update", "sudo", self.finishedfunc, self.password, self.su_install)
					doinstall = Doinstall("update", self.prefix, self.installset, "sudo", self.password, self.su_install)
					doinstall.start()
					self.label_done.set_markup("<b>Update running</b>\n"\
										   "Wait until finished...")										
				else:
					print "starting install as sudoer"
					#doinstall = Doinstall("install", "sudo", self.finishedfunc, self.password, self.su_install)
					doinstall = Doinstall("install", self.prefix, self.installset, "sudo", self.password, self.su_install)
					doinstall.start()
					self.label_done.set_markup("<b>Installation running</b>\n"\
										   "Wait until finished...")
			else:
				installerror = "You entered a wrong password, please reenter your password:\n"
				print "No pass return!"
				self.su_install(installerror)
	
	def dummy(self):
		print "hello world!"
		
	def dodonate(self, *widget):
		print "donation clicked: " + self.donateurl
		browser = Webbrowser()  
		browser.url = self.donateurl
		browser.target = "new window"
		browser.start()  
		
	def destroy_event(self, widget, *event):
		print "exit"
		try:
			self.tmp_histfile.close()
		except:
			pass
		exit 
		gtk.main_quit()
		return False 	
	
	def delete_event(self, widget, *event):
		print "exit"
		try:
			self.tmp_histfile.close()
		except:
			pass
		exit 
		gtk.main_quit()
		return False
	
class Webbrowser ( Thread ):
    def __init__ (self):
        Thread.__init__(self)
        self.url = "http://qemulator.createweb.de"
        self.target = "new window"

    def run(self):
        self.open_website(self.url, self.target)  

    def open_website(self, url, target):
        if target == "new window":
            newin = 1
        else:
            newin = 0
                    
        print "open website: " + url
        runweb = webbrowser.open(self.url, new=newin)    
        print str(runweb)
        
class Textbrowser:
	def __init__ (self, textfile, title=_("Info Dialog")):
		self.textfile = textfile
		self.text = ""
		textbuffer = gtk.TextBuffer()
		
		self.gladefile = "./setup.glade"
		self.wTree = gtk.glade.XML(self.gladefile, "dialog_textbrowser", APP)
		self.dialog_textbrowser = self.wTree.get_widget("dialog_textbrowser")
		self.textview = self.wTree.get_widget("textview")
		self.dialog_textbrowser.set_title(title)
		if path.isfile(textfile):
			fd = open(textfile, "r")
			textlist = fd.readlines()
			for line in textlist:
			    print str(line)
			    self.text = self.text + line		
			print str(self.text)
			time.sleep(0.5)

		else:
			self.text = "Document not found!"
		textbuffer.set_text(self.text)
		self.textview.set_buffer(textbuffer)			
		dic = {"on_dialog_textbrowser_response" : self.dialog_textbrowser_response,

		}
		self.wTree.signal_autoconnect(dic)
					
	def dialog_textbrowser_response(self, widget, response, *entry):
	    if response == gtk.RESPONSE_CLOSE:
	        self.destroy_event(widget)	
	        
	def destroy_event(self, widget, *event):
		print "exit textbrowser"
		widget.destroy ()
		return False  
	
class Doinstall ( Thread ):
	## The main installation function
	## procedure = procedure to perform

	def __init__ (self, procedure, prefix, installset=None, mode="sudo", password=None, pwderr_func=None):
		Thread.__init__(self)
		self.prefix = prefix
		self.defaultprefix = copy(default_prefix)
		self.sourcefolder = sourcefolder
		self.basedir = str(basedir)
		
		self.procedure = procedure
		self.mode = mode
		self.password = password 
		self.pwderr_func = pwderr_func
		self.installset = installset
		if self.installset != None:
			self.instdirs = self.installset[0]
			self.instfiles = self.installset[1]
	def run(self):
		runit = False	
		if self.procedure == "install":
			install = self.install(self.mode)  
		elif self.procedure == "uninstall":
			runit = self.uninstall(self.mode, False)
		elif self.procedure == "update":
			runit = self.uninstall(self.mode, True) 
			time.sleep(0.5)
			runit = self.install(self.mode)
		#if runit == True:
		time.sleep(0.2)
		self.finishedfunc()

	def install(self, mode):
		print "mode: " + mode
		errors = []
		outputs = []
		self.installfiles = []
		self.installdirs = []
		
		install_history = Installation()
		install_history.prefix = self.prefix
		inst_error = False
		#if mode == "sudo":
		#	self.install_dirs(self.instdirs, mode)
		#	self.install_files(self.instfiles, mode)
		#	self.progress_feedback()
		#	inst_error = False
						 				
		#else: 
		#inst_error = False 
		#print "user is allready root" 
		self.install_dirs(self.instdirs, mode)
		self.install_files(self.instfiles, mode)
		self.progress_feedback()
		print " files successfully installed. \n run uninstall.sh to uninstall Qemulator."
		self.password = ""
		print "thread install finished"
		#return True				
		if inst_error == False:
			install_history.installfiles = self.installfiles
			install_history.installdirs = self.installdirs			
			self.write_insthist(install_history, mode)
			return True
		else:
			return False


	def install_dirs(self, instdirs, mode):
		for sdir, tdir in instdirs:
			if not os.path.exists(os.path.realpath(tdir)):
				if mode == "sudo":
					#print "run instdir as sudo root"
					sucommand = "sudo mkdir -v " + tdir
					child_stdin, child_stdout, child_stderr  = os.popen3(sucommand)
					child_stdin.write(self.password)	
					time.sleep(0.1)
					try:
						child_stdin.flush()
						child_stdin.close()
					except:
						pass
				else:  
					#print "user is allready root"      
					command = "mkdir -v " + tdir
					child_stdin, child_stdout, child_stderr = os.popen3(command)
					child_stdin.close()	
				#print "Result: " + str(child_stdout.readlines())
				if child_stderr.readlines() != []:
					print "Dir Error: " + str(child_stderr.readlines())
					child_stderr.close()
	 				child_stdout.close()
	 				self.installdirs.append(tdir)
	 				#print "created dir: " + tdir
 				self.progress_feedback()
			else:
				print "Directory " + tdir + " allready exist"	
				
	def install_files(self, instfiles, mode):
		for sfile, tfile in instfiles:
			self.installfiles.append(tfile)
			if mode == "sudo":
				#print "run instfile as sudo root"
				sucommand = "sudo cp -dv " + sfile + " " + tfile
				child_stdin, child_stdout, child_stderr  = os.popen3(sucommand)
				child_stdin.write(self.password)	
				child_stdin.flush()
				child_stdin.close()
			else:  
				#print "user is allready root"      
				command = "cp -dv " + sfile + " " + tfile
				child_stdin, child_stdout, child_stderr = os.popen3(command)
				child_stdin.close()	
			if child_stderr.readlines() != []:
				print "Install Error: " + str(child_stderr.readlines())
				child_stderr.close()
 				child_stdout.close()
 			#print "installed file: " + tfile
 				
 				#time.sleep(0.1)
 			self.progress_feedback()
	
	def uninstall(self, mode, do_update):
		inst_error = False		
		errors = []
		outputs = []
		self.do_update = do_update
		self.install_history = getfromfile(self.prefix + "/lib/qemulator/install_history")
		#if mode == "sudo":
		#	check_command = "sudo -S echo password ok"
		#	child_stdin, child_stdout, child_stderr  = os.popen3(check_command)
			
		#	child_stdin.write(self.password)
		#	#time.sleep(0.3)	
		#	child_stdin.flush()
		#	child_stdin.close()
		#	outputs = child_stdout.readlines()				
		#	print "Result passcheck: " + str(outputs)
		#	if outputs == []:
		#		installerror = "You entered a wrong password, please reenter your password:\n"
		#		print "No pass return!"
		#		inst_error = True
		#		child_stderr.close()
		# 		child_stdout.close()
		#		if self.pwderr_func != None:
		#			self.pwderr_func(installerror)			 		
		# 		return True
		
		if inst_error != True:
			c = 0
			for file in self.install_history.installfiles:
				try:
					if mode == "sudo":
						#print "run uninstfile as sudo root"
						#password = self.password
						sucommand = "sudo -S rm " + file
						child_stdin, child_stdout, child_stderr  = os.popen3(sucommand)
						child_stdin.write(self.password)	
						child_stdin.flush()
						child_stdin.close()	
					else:
						#print "user is allready root"      
						command = "rm " + file
						child_stdin, child_stdout, child_stderr = os.popen3(command)
						child_stdin.close()
						#time.sleep(0.3)	
					errors = child_stderr.readlines()
					outputs = child_stdout.readlines()				
					#print "Result: " + str(outputs)
					#if errors != []:
					#	print "Error: " + str(errors)
					#time.sleep(0.3)	
					child_stderr.close()
			 		child_stdout.close()
					self.progress_feedback()
					if errors != []:
						print "Uninstall Errors: "
						installerror = "The system returned the following error message:\n"
						for rline in errors:
							print str(rline)
					#else:
					#	print "removed file : " + file
					# 	#print str(remove_file)
			 	except:
			 		print "File " + file + " not found"
				if inst_error == True:
					print "uninstall error: " + str(installerror)
					break	
				c = c + 1   
			removedirs = self.install_history.get_removedirs()
			removedirs.sort()
			if removedirs != []:
				print "Remove dirs: \n"
				for dir in removedirs:
					if os.path.exists(os.path.realpath(dir)):
						try:
							if mode == "sudo":
								#print "run uninstdir as sudo root"
								sucommand = "sudo rm -Rv " + dir
								child_stdin, child_stdout, child_stderr  = os.popen3(sucommand)
								child_stdin.write(self.password)
								#time.sleep(0.3)	
								child_stdin.flush()
								child_stdin.close()
							else:  
								#print "user is allready root"      
								command = "rm -Rv " + dir
								child_stdin, child_stdout, child_stderr = os.popen3(command)
								child_stdin.close()
								#time.sleep(0.3)	
							#print "Result: " + str(child_stdout.readlines())
							if child_stderr.readlines() != []:
								print "Uninstall Error: " + str(child_stderr.readlines())
							child_stderr.close()
			 				child_stdout.close()
			 				#time.sleep(0.3)
			 				#print "removed dir: " + dir
						except:
							print "Directory " + dir + " remove ERROR"
					else:
						print "Directory " + dir + " not found"	
					self.progress_feedback()					
											
		if self.do_update != True: 
			self.password = ""
		print "thread uninstall finished"
		#self.die = True
		#return True
			#self.closebutton.set_sensitive(True) 
		if inst_error == False:
			return True
		else:
			return False			 
			
	def write_insthist(self, insthist, mode):
		self.tmp_histfile = storetotmp(insthist)
		self.progress_feedback()
		self.tmp_histfilename = str(self.tmp_histfile.name)
		#print "tmpfile: " + str(self.tmp_histfilename)
		sudo_prefix = "sudo -S "
		createhist_command = "echo '' > " + self.prefix + "/lib/qemulator/install_history"
		createhist_sudo_c = sudo_prefix + createhist_command
		insthist_command = "cp " + self.tmp_histfilename + " " + self.prefix + "/lib/qemulator/install_history"
		chmodcommand = "chmod 645 " + self.prefix + "/lib/qemulator/install_history"
		insthist_sudo_c = sudo_prefix + insthist_command
		chmod_sudo_c = sudo_prefix + " " + chmodcommand
		
		print "copy install history to installation"
		if mode == "sudo":
			child_stdin, child_stdout, child_stderr  = os.popen3(insthist_sudo_c)
			child_stdin.write(self.password)
			#time.sleep(0.3)	
			child_stdin.flush()
			child_stdin.close()
			errors2 = child_stderr.readlines()
			outputs2 = child_stdout.readlines()
			if errors2 != []:
				print "error: " + str(errors2)
			print str(outputs2)
			self.progress_feedback()

			child_stderr.close()
	 		child_stdout.close()				
			#time.sleep(0.3)	 
			child_stdin1, child_stdout1, child_stderr1  = os.popen3(chmod_sudo_c)
			child_stdin1.write(self.password)
			#time.sleep(0.3)	
			child_stdin1.flush()
			child_stdin1.close()
			#time.sleep(0.3)	
			errors1 = child_stderr1.readlines()
			outputs1 = child_stdout1.readlines()
			if errors1 != []:
				print "errors during change rights of install_history: " + str(errors1)
			print str(outputs1)
			self.progress_feedback()	
			child_stderr1.close()
	 		child_stdout1.close()								
		else:  
			#print "user is allready root"      

			child_stdin, child_stdout, child_stderr  = os.popen3(insthist_command)
			errors2 = child_stderr.readlines()
			outputs2 = child_stdout.readlines()

			self.progress_feedback()

			child_stdin1, child_stdout1, child_stderr1  = os.popen3(chmodcommand)
			errors1 = child_stderr1.readlines()
			outputs1 = child_stdout1.readlines()
			#time.sleep(0.3)
			if errors1 != []:	
				print "errors during change rights of install_history: " + str(errors1)

		self.progress_feedback()
		self.tmp_histfile.close()
		child_stderr.close()
		child_stdout.close()
		child_stdin.close()	
		child_stderr1.close()
		child_stdout1.close()
		child_stdin1.close() 
			
	def progress_feedback(self):
		gtk.threads_enter()
		installer.progressbar_total.pulse()
		gtk.threads_leave()
		
	def finishedfunc(self):
		gtk.threads_enter()
		if self.procedure == "uninstall":
			installer.label_done.set_markup("<b>Uninstall Done!</b>\n"\
								   "I hope i was a usefull porgram for you!")				
		elif self.procedure == "update":
			installer.label_done.set_markup("<b>Update Done!</b>\n"\
								   "Launch Qemulator with the command \"qemulator\"\n"\
								   "Have Fun!")		
		elif self.procedure == "install":
			installer.label_done.set_markup("<b>Installation Done!</b>\n"\
								   "Launch Qemulator with the command \"qemulator\"\n"\
								   "Have Fun!")								
		installer.closebutton.set_sensitive(True)				
		gtk.threads_leave()
			
def getfromfile(filename):
    outdata  = { }
    try:
        abs_path = path.abspath("./" + filename)
        abs_path = filename
        print "opened file absolute path: " + abs_path
        dumpf = open( abs_path ,"r")
        outdata = pickle.load(dumpf)
        dumpf.close()
        time.sleep(0.3)
        return outdata
    except:
        outdata  = { }
        print "no install history file found"
        return outdata  			
			
def storetotmp(indata):
	tmpfile = tempfile.NamedTemporaryFile('w')
	tmpfile_name = str(tmpfile.name)
	tmppic = file(tmpfile_name,'w+')
	dopic = pickle.dump(indata, tmppic)
	tmppic.close()	    
	print "dopic: " + str(dopic)
	time.sleep(0.3)
	return tmpfile				        		
    				
def main():
	pass
	
if __name__ == "__main__":
	#main()
	installer = Installer()
	installer.start()
