#!/usr/bin/env python
# gdm-setup by Nick Glynn (exosyst@gmail.com)
# Simple setup for GDM, I made use of ImageMagick to keep my life simplish, go install it
# This is GPL2 so fix it and tell me what/where and why

import subprocess
import gtk
import gconf
import os.path


def GetAutoLogin():
	if not os.path.isfile("/etc/gdm/custom.conf"):
		SetAutoLogin(False)
		return False
	file = open("/etc/gdm/custom.conf",'r')
	index = file.read().find("AutomaticLoginEnable=true")
	AutoLogin = False
	if index > 0:
		AutoLogin=True
	file.close()	
	return AutoLogin

def SetAutoLogin(DoIt, User=""):
	file = open("/etc/gdm/custom.conf", 'w')
	if DoIt == False:
		file.write("\n[daemon]\nTimedLoginEnable=false\nAutomaticLoginEnable=false\nTimedLogin="+User+"\nAutomaticLogin="+User+"\nTimedLoginDelay=30\n")
	if DoIt == True and User != "":
		file.write("\n[daemon]\nTimedLoginEnable=false\nAutomaticLoginEnable=true\nTimedLogin="+User+"\nAutomaticLogin="+User+"\nTimedLoginDelay=30\n")
	file.close()

def GetAvailableThemes():
	ThemeList = []
	retcall = subprocess.Popen(["ls", "/usr/share/themes/"], stdout=subprocess.PIPE)
	for Theme in retcall.stdout.readlines():
		Theme = Theme.strip('\n')
		if '.' not in Theme:
			ThemeList.append(Theme)
	return ThemeList	

def GetAvailableIconThemes():
	IconThemeList = []
	retcall = subprocess.Popen(["ls", "/usr/share/icons/"], stdout=subprocess.PIPE)
	for Theme in retcall.stdout.readlines():
		Theme = Theme.strip('\n')
		if '.' not in Theme:
			IconThemeList.append(Theme)
	return IconThemeList	

def SetWallpaper(WallpaperLocation, DoBlur):
	""" This is the only setter that does craaaazy stuff """
	#print WallpaperLocation
	#print DoBlur
	commandToDo = "convert" + (' -blur','')[not DoBlur] + (' 4x20','')[not DoBlur] + " " +WallpaperLocation+ " /usr/share/images/xsplash/bg.jpg"
	retcall = subprocess.Popen(commandToDo, shell=True, stdout=subprocess.PIPE)
	for blah in retcall.stdout.readline():
		print "Convert: " + blah
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_800x600.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_1024x768.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_1280x800.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_1280x1024.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_1440x900.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_1680x1050.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_1920x1200.jpg"], stdout=subprocess.PIPE).wait()
	retcall = subprocess.Popen(["ln", "-s", "-f", "-T", "/usr/share/images/xsplash/bg.jpg", "/usr/share/images/xsplash/bg_2560x1600.jpg"], stdout=subprocess.PIPE).wait()
	
def GetWallpaper(): #This is nigh on useless as the picture is always the same location when we're done with it
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-g", "/desktop/gnome/background/picture_filename"], stdout=subprocess.PIPE)
	return retcall.stdout.readline().strip('\n')

def SetLoginSound(MakeNoise):
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-s", "/desktop/gnome/sound/event_sounds", "--type", "bool", ('true','false')[not MakeNoise]], stdout=subprocess.PIPE).wait()

def GetLoginSound():
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-g", "/desktop/gnome/sound/event_sounds"], stdout=subprocess.PIPE)
	if 'false' in retcall.stdout.readline():
		return False
	else:
		return True

#These two are backwards as the hide is the special case HURR DURR!
def SetShowUserList(ShowIt):
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-s", "/apps/gdm/simple-greeter/disable_user_list", "--type", "bool", ('false', 'true')[not ShowIt]], stdout=subprocess.PIPE).wait()

def GetShowUserList():
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-g", "/apps/gdm/simple-greeter/disable_user_list"], stdout=subprocess.PIPE)
	if 'false' in retcall.stdout.readline():
		return True
	else:
		return False

def SetLoginTheme(Theme):
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-s", "/desktop/gnome/interface/gtk_theme", "--type", "string", Theme], stdout=subprocess.PIPE).wait()

def GetLoginTheme():
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-g", "/desktop/gnome/interface/gtk_theme"], stdout=subprocess.PIPE)
	return retcall.stdout.readline().strip('\n')

def SetLoginIconTheme(Theme):
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-s", "/desktop/gnome/interface/icon_theme", "--type", "string", Theme], stdout=subprocess.PIPE).wait()

def GetLoginIconTheme():
	retcall = subprocess.Popen(["sudo", "-u", "gdm", "gconftool-2", "-g", "/desktop/gnome/interface/icon_theme"], stdout=subprocess.PIPE)
	return retcall.stdout.readline().strip('\n')

def GetAvailableUsers():
	retcall = subprocess.Popen(["ck-history", "--frequent", "--seat=Seat1","--session-type="], stdout=subprocess.PIPE)
	UserList = []
	for user in retcall.stdout.readlines():
		UserList.append(user.split()[0])
	return UserList

class ConfigWindow(gtk.Window):
	PlayLoginSound = True #Get from gconf
	LoginIconTheme = "" #Get from gconf
	LoginTheme = "" #Get from gconf
	LoginIconTheme = "" #Get from gconf
	AutoLogin = False
	WallpaperLocation = ""
	AutoLoginUser = "" #Get from file with grep
	BlurLoginImage = False
	UserList = []
	ThemeList = []
	IconThemeList = []
	ImageMagickInstalled = False #Get from running convert and checking for 0
	def __init__(self):
		super(ConfigWindow, self).__init__()
		self.set_title("Configure Login Settings") 
		self.set_size_request(360,580)
		self.connect("destroy", self.quit)
		self.set_border_width(10)
		
		#make sure we can write new backgrounds to the proper location
		retcall = subprocess.Popen(["sudo", "chmod", "-R","a+rw", "/usr/share/images/xsplash"], stdout=subprocess.PIPE)
		
		# Build sections 
			# Config
		configPageOuter = gtk.Frame("General")
		configPage = gtk.VBox()
		configPage.set_border_width(10)
		self.playSound = gtk.CheckButton("Play sound at login prompt")
		if GetLoginSound():
			self.playSound.set_active(True)
		self.playSound.connect("toggled", self.CheckButtonSelected, "playSound")
		self.showUserlist = gtk.CheckButton("Display user list at login")
		if GetShowUserList():
			self.showUserlist.set_active(True)
		self.showUserlist.connect("toggled", self.CheckButtonSelected, "showUserlist")
		
		#Figure out if we already autologin and check the proper button
		#and optionally grey out the dropdown with .set_sensitive(False)	
		HBox = gtk.HBox(False, 0)
		self.showLogin = gtk.RadioButton(None, "Show login screen")
		self.showLogin.connect("toggled", self.RadioButtonSelected, "showLogin")
		self.autoLogin = gtk.RadioButton(self.showLogin, "Login automatically as:")
	
		self.userSelect = gtk.combo_box_new_text()
		self.AutoLogin = GetAutoLogin()
		#print self.AutoLogin
		if not self.AutoLogin: 
			self.userSelect.set_sensitive(False)
			self.showLogin.set_active(True)
		else:
			self.showUserlist.set_active(True)
			self.autoLogin.set_active(True)
		self.UserList = GetAvailableUsers()	
		for user in self.UserList:
			self.userSelect.append_text(user)

		self.userSelect.connect("changed", self.UserSelected, "Userselect") # Connect afterwards to avoid spurious signals
		self.autoLogin.connect("toggled", self.RadioButtonSelected, "autoLogin")
		configPage.pack_start(self.playSound, True, False)
		configPage.pack_start(self.showUserlist, True, False)
		configPage.pack_start(self.showLogin, True, False)
		HBox.pack_start(self.autoLogin, False, False)
		HBox.pack_start(self.userSelect, False, False)
		configPage.pack_start(HBox, True, False)
	
		# Wallpaper
		wallpaperPageOuter = gtk.Frame("Wallpaper")
		wallpaperPageUp = gtk.HBox()
		wallpaperPage = gtk.VBox()
		wallpaperPage.set_border_width(10)
		wallpaperPageUp.set_border_width(10)
		self.PreviewThumb = gtk.Image()
		if os.path.isfile(GetWallpaper()): #If it aint there, don't use it
			self.PreviewThumb.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(GetWallpaper()).scale_simple(150,150,gtk.gdk.INTERP_BILINEAR))
			
		self.WallpaperBlurCheckbox = gtk.CheckButton("Blur login wallpaper and sharpen on login")
		self.WallpaperBlurCheckbox.connect("toggled", self.CheckButtonSelected, "blurWallpaper")
		self.SelectWallpaperBtn = gtk.Button("Select")
		self.SelectWallpaperBtn.connect("clicked", self.WallPaperSelector, None)
		wallpaperPageUp.pack_start(self.PreviewThumb, True, False)
		wallpaperPageUp.pack_start(self.SelectWallpaperBtn, True, False)
		wallpaperPage.pack_start(wallpaperPageUp, True, False)
		wallpaperPage.pack_start(self.WallpaperBlurCheckbox, True, False)
		
		# Theme	
		themePageOuter = gtk.Frame("Theme")
		themePage = gtk.VBox()
		themePage.set_border_width(10)
		self.themeSelect = gtk.combo_box_new_text()
		self.iconThemeSelect = gtk.combo_box_new_text()
		
		self.ThemeList = GetAvailableThemes()	
		for theme in self.ThemeList:
			self.themeSelect.append_text(theme)
		self.themeSelect.connect("changed", self.ThemeSelected, "ThemeSelect")
		
		self.IconThemeList = GetAvailableIconThemes()	
		for theme in self.IconThemeList:
			self.iconThemeSelect.append_text(theme)
		self.iconThemeSelect.connect("changed", self.IconThemeSelected, "IconThemeSelect")
		themePage.pack_start(gtk.Label("Select GTK Theme"), True, False)
		themePage.pack_start(self.themeSelect, True, False)
		themePage.pack_start(gtk.Label("Select Icon Theme:"), True, False)
		themePage.pack_start(self.iconThemeSelect, True, False)
			
		# And add them to the setup
		configPageOuter.add(configPage)
		themePageOuter.add(themePage)
		wallpaperPageOuter.add(wallpaperPage)

		#Buttons, buttons; who gots da buttons
		self.close_btn = gtk.Button("Close", gtk.STOCK_CLOSE)
		self.close_btn.connect("clicked", self.quit, None)

		self.MainDiv = gtk.VBox()
		self.buttonBox = gtk.HBox()
		self.buttonBox.pack_end(self.close_btn, False, False)
		self.MainDiv.pack_start(configPageOuter)
		self.MainDiv.pack_start(wallpaperPageOuter)
		self.MainDiv.pack_start(themePageOuter)
		self.MainDiv.pack_start(self.buttonBox, False, False)
		self.add(self.MainDiv)
		self.show_all()
	
	def WallPaperSelector(self, widget, data=None):
		chooser = gtk.FileChooserDialog("Select a new wallpaper:", None,
				gtk.FILE_CHOOSER_ACTION_OPEN,
				(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
				gtk.STOCK_OPEN, gtk.RESPONSE_OK))
		chooser.set_default_response(gtk.RESPONSE_OK)
		filter = gtk.FileFilter()
		filter.set_name("Images")
		filter.add_pattern("*.bmp")
		filter.add_pattern("*.jpg")
		filter.add_pattern("*.jpeg")
		filter.add_pattern("*.gif")
		filter.add_pattern("*.png")
		chooser.add_filter(filter)
		response = chooser.run()
		if response == gtk.RESPONSE_OK:
			self.WallpaperLocation = chooser.get_filename()
			SetWallpaper(self.WallpaperLocation, self.BlurLoginImage)
			if os.path.isfile(GetWallpaper()): #If it aint there, don't use it
				self.PreviewThumb.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(GetWallpaper()).scale_simple(150,150,gtk.gdk.INTERP_BILINEAR))
			self.PreviewThumb.queue_draw()
			self.queue_draw()
		chooser.destroy()
	
	def ThemeSelected(self, widget, data=None):
		self.ThemeSelected = (self.ThemeList)[widget.get_active()]
		#print "Theme %s " % self.ThemeSelected
		SetLoginTheme(self.ThemeSelected)

	def IconThemeSelected(self, widget, data=None):
		self.ThemeSelected = (self.IconThemeList)[widget.get_active()]
		#print "Icon theme %s " % self.ThemeSelected
		SetLoginTheme(self.ThemeSelected)

	def UserSelected(self, widget, data=None):
		self.AutoLoginUser = (self.UserList)[widget.get_active()]
		#print "%s was selected" % self.AutoLoginUser
		SetAutoLogin(True, self.AutoLoginUser)

	def RadioButtonSelected(self, widget, data=None):
		if data == 'autoLogin' and widget.get_active() == 1:
			self.userSelect.set_sensitive(True)
			#print 'Setting autologin'
		if data != 'autoLogin' and widget.get_active() == 1:
			self.userSelect.set_sensitive(False)
			SetAutoLogin(False, self.AutoLoginUser)
			#print 'Disabling autologin'

	def CheckButtonSelected(self, widget, data=None):
		if data == "showUserlist":
			if widget.get_active() == 1:
				#print 'Enabling user list'
				SetShowUserList(True)
			else:
				#print 'Disabling user list'
				SetShowUserList(False)
		if data == "playSound":
			if widget.get_active() == 1:
				#print 'Enabling sound'
				SetLoginSound(True)
			else:
				#print 'Disabling sound'
				SetLoginSound(False)
		if data == "blurWallpaper":
			if widget.get_active() == 1:
				self.BlurLoginImage = True
				#print 'Blurring wallpaper'
				if self.WallpaperLocation != "":
					SetWallpaper(self.WallpaperLocation, self.BlurLoginImage)
			else:
				self.BlurLoginImage = False 
				#print 'Normal wallpaper'
				if self.WallpaperLocation != "":
					SetWallpaper(self.WallpaperLocation, self.BlurLoginImage)


	def quit(self, widget, data=None):
		gtk.main_quit()
		quit()

if __name__ == '__main__':
	import os,sys
	if os.geteuid() != 0:
		dlg = gtk.Dialog("GDM Setup", None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                      (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
		dlg.set_border_width(10)
		dlg.vbox.set_border_width(10)
		dlgLabel = gtk.Label("This program needs to be run as root.\nTry again with using either\nsudo or gksudo")
		dlgLabel.set_justify(gtk.JUSTIFY_CENTER)
		dlgLabel.set_line_wrap(True)
		dlg.vbox.pack_start(dlgLabel)
		dlg.show_all()
		dlgResult = dlg.run()
		dlg.destroy()
	else:
		ConfigWindow()
		gtk.main()

