#!/usr/bin/env python
#

import gtk,os,re,getpass,sys
from xml.dom import minidom, Node

class networksettings:
	if os.name == "nt":
		WIRELESS_OPTS = "C:\\python24\\pdaxrom\\misc\\wireless.opts"
		NETWORK_OPTS = "C:\\python24\\pdaxrom\\misc\\network.opts"
		i686_NETWORK_OPTS = "C:\\python24\\pdaxrom\\misc\\network"
		i686_WIRELESS_OPTS = "C:\\python24\\pdaxrom\\misc\\wireless"
		CFG_FILENAME = "network.cfg"
	else:
		WIRELESS_OPTS = "/etc/pcmcia/wireless.opts"
		NETWORK_OPTS = "/etc/pcmcia/network.opts"
		i686_NETWORK_OPTS = "/etc/sysconfig/network"
		i686_WIRELESS_OPTS = "/etc/sysconfig/wireless"
		CFG_FILENAME = os.environ['HOME'] + "/Choices/network.cfg"
	
	NOTINUPDATEMODE = True
	
	PROFILELIST = []
	SETTING_NAME = "default"
	DELETE_PROFILE_NAME = ""
	
	OUTPUT_WIRELESS = ""
	OUTPUT_NETWORK = ""
	
	is_wireless = False
	use_any_essid = True
	use_dhcp = True
	get_dns_auto = True
	w_mode = "managed"
	w_modes = ["Managed", "Ad-Hoc", "Master", "Repeater","Secondary","Auto"]
	w_auth = "open"
	w_auths = ["Open","Restricted"]
	wepkey_type = "Disabled"
	wepkey_types = ["Disabled", "Hex", "Text"]
	wireless_header = """# Wireless LAN adapter configuration
#
# The address format is "scheme,socket,instance,hwaddr".
#
# Theory of operation : all the Wireless specific configuration is done
# through the Wireless Extensions, so we will just call 'iwconfig' with
# the right parameters defined below.
# Of course, you need to have iwconfig installled on your system.
# To download iwconfig, or for more info on Wireless Extensions :
#	http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html
#
# Note : you don't need to fill all parameters, leave them blank, in most
# cases the driver will initialise itself with sane defaults values or
# automatically figure out the value... And not all drivers do support
# all settings...
#
# Finally, send comments and flames to me, Jean Tourrilhes <jt@hpl.hp.com>
#

# DISABLED the WIRELESS_USE - should be no need for that anymore
# if [ "$WIRELESS_USE" != "" ]; then
#  if [ -e $WIRELESS_USE.opts ]; then
#    . $WIRELESS_USE.opts
#  else
#    . ./wlng2wt.opts
#  fi
# else

case "$ADDRESS" in

"""
	wireless_footer = "\nesac\n# fi\n";

	network_header = """
# Network adapter configuration
#
# The address format is "scheme,socket,instance,hwaddr".
#
# Note: the "network address" here is NOT the same as the IP address.
# See the Networking HOWTO.  In short, the network address is the IP
# address masked by the netmask.
#

case "$ADDRESS" in
"""
	network_footer = "\nesac"
	network_standard = """
\tstart_fn () { return; }
\tstop_fn () { return; }
\tIF_PORT=""
\tDHCP_HOSTNAME=""
\tSEARCH=""
\tMOUNTS=""
\tMTU=""
\tNO_CHECK=""
\tNO_FUSER=""
\tBOOTP=n
\tNETWORK=""
\tBROADCAST=""
"""


	def __init__(self):
		if (getpass.getuser().lower() != "root" and os.name != "nt"):
			Warningdialog = gtk.MessageDialog(None,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"You need to be root in order to run this program.")
			Warningdialog.run()
			Warningdialog.destroy()
			sys.exit()
	        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	        self.window.set_title("Network settings")
	        self.window.set_border_width(4)
	        self.window.set_position(gtk.WIN_POS_CENTER)
	        self.window.set_resizable(gtk.FALSE)
	        self.window.connect("delete_event", gtk.main_quit)
	        self.window.connect("destroy", gtk.main_quit)

	        MainBox = gtk.VBox(gtk.FALSE, 5)
	        self.window.add(MainBox)

		self.notebook = gtk.Notebook()
		self.notebook.set_tab_pos(gtk.POS_TOP)
		MainBox.pack_start(self.notebook, gtk.TRUE, gtk.TRUE, 5)

		# Tabbed interface
		self.profileframe = gtk.Frame()
		label = gtk.Label("Network profiles")
		self.notebook.append_page(self.profileframe, label)
	     	profilebox = gtk.VBox(gtk.FALSE, 5)
		self.profileframe.add(profilebox)

		tcpipframe = gtk.Frame()
		label = gtk.Label("TCP/IP & DNS")
		self.notebook.append_page(tcpipframe, label)
	     	tcpipbox = gtk.VBox(gtk.FALSE, 5)
		tcpipframe.add(tcpipbox)

		self.wirelessframe = gtk.Frame()
		label = gtk.Label("Wireless")
		self.notebook.append_page(self.wirelessframe, label)
	     	wirelessbox = gtk.VBox(gtk.FALSE, 5)
		self.wirelessframe.add(wirelessbox)

# Profile start
		profileloadframe = gtk.Frame("Profiles")
		profileloadframe.set_border_width(4)
		profilebox.pack_start(profileloadframe, gtk.FALSE, gtk.FALSE, 5)
		
		vbox = gtk.VBox(gtk.FALSE, 5)
		profileloadframe.add(vbox)

		hbox = gtk.HBox(gtk.FALSE, 5)
		vbox.pack_start(hbox, gtk.FALSE, gtk.FALSE, 5)
		
		label = gtk.Label("Network type:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 5)
	        self.connectiontype1 = gtk.RadioButton(None, "Normal")
		self.connectiontype1.connect("clicked", self.set_network_type, False)
		hbox.pack_start(self.connectiontype1, gtk.FALSE, gtk.FALSE, 5)
	        
	        self.connectiontype2 = gtk.RadioButton(self.connectiontype1, "Wireless")
		self.connectiontype2.connect("clicked", self.set_network_type, True)
		hbox.pack_start(self.connectiontype2, gtk.FALSE, gtk.FALSE, 5)

		self.profilecombo = gtk.combo_box_new_text()
	        self.profilecombo.set_border_width(4)
		vbox.pack_start(self.profilecombo, gtk.FALSE, gtk.FALSE, 5)

		hbox = gtk.HBox(gtk.TRUE, 5)
	        vbox.pack_start(hbox, gtk.FALSE, gtk.TRUE, 5)
	        
	        make_newprofile = gtk.Button("Create new")
		hbox.pack_start(make_newprofile, gtk.TRUE, gtk.TRUE, 2)
		make_newprofile.connect("clicked", self.make_new_profile)
	        
	        profile_ok = gtk.Button("Rename")
		hbox.pack_start(profile_ok, gtk.TRUE, gtk.TRUE, 2)
		profile_ok.connect("clicked", self.rename_profile)
		
	        profile_save = gtk.Button("Save")
		hbox.pack_start(profile_save, gtk.TRUE, gtk.TRUE, 5)
		profile_save.connect("clicked", self.save_prefs)

	        profile_remove = gtk.Button("Delete")
		hbox.pack_start(profile_remove, gtk.TRUE, gtk.TRUE, 5)
		profile_remove.connect("clicked", self.delete_profile)

		hintframe = gtk.Frame("Hint:")
		label = gtk.Label("\nYou can select between the different profiles\nfrom terminal/shell using:\ncardctl scheme \"profilename\"\n")
		hintframe.set_border_width(4)
		hintframe.add(label)
		profilebox.pack_start(hintframe, gtk.FALSE, gtk.FALSE, 5)
# profile end

# tcpip start
	     	vbox = gtk.VBox(gtk.FALSE)
		tcpipbox.pack_start(vbox, gtk.FALSE, gtk.FALSE)

	# DHCP yes/no
		self.use_dhcp_check = gtk.CheckButton("Obtain TCP/IP info. automatically (DHCP)")
		self.use_dhcp_check.connect("toggled", self.toggle_use_dhcp)
		vbox.pack_start(self.use_dhcp_check, gtk.FALSE, gtk.FALSE)
		self.use_dhcp_check.set_border_width(4)

		content_frame = gtk.Frame("TCP/IP")
		content_frame.set_border_width(4)
		vbox.pack_start(content_frame, gtk.FALSE, gtk.FALSE)
		vbox2 = gtk.VBox(gtk.FALSE,8)
		vbox2.set_border_width(6)
		content_frame.add(vbox2)

	#IP Address
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

		label = gtk.Label("IP address:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE,4)

	        self.ip_adr = gtk.Entry(0)
	        self.ip_adr.set_size_request(250,22)
		hbox.pack_end(self.ip_adr, gtk.FALSE, gtk.FALSE,4)

	#Subnet mask
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

		label = gtk.Label("Subnet mask:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE,4)

	        self.subnet = gtk.Entry(0)
	        self.subnet.set_size_request(250,22)
		hbox.pack_end(self.subnet, gtk.FALSE, gtk.FALSE,4)

	#Gateway
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

		label = gtk.Label("Gateway:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE,4)

	        self.gateway = gtk.Entry(0)
	        self.gateway.set_size_request(250,22)
		hbox.pack_end(self.gateway, gtk.FALSE, gtk.FALSE,4)

	# DNS Settings

		self.get_dns_auto_check = gtk.CheckButton("Auto-detect domain name servers (DNS)")
		self.get_dns_auto_check.connect("toggled", self.toggle_get_dns_auto)
		vbox.pack_start(self.get_dns_auto_check, gtk.FALSE, gtk.FALSE)
		self.get_dns_auto_check.set_border_width(4)

		content_frame = gtk.Frame("DNS")
		content_frame.set_border_width(4)
		vbox.pack_start(content_frame, gtk.FALSE, gtk.FALSE)
		vbox2 = gtk.VBox(gtk.FALSE,8)
		vbox2.set_border_width(6)
		content_frame.add(vbox2)

	#DNS 1
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

		label = gtk.Label("1. DNS:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE,4)

	        self.dns_1 = gtk.Entry(0)
	        self.dns_1.set_size_request(250,22)
		hbox.pack_end(self.dns_1, gtk.FALSE, gtk.FALSE,4)

	#DNS 2
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

		label = gtk.Label("2. DNS:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE,4)

	        self.dns_2 = gtk.Entry(0)
	        self.dns_2.set_size_request(250,22)
		hbox.pack_end(self.dns_2, gtk.FALSE, gtk.FALSE,4)

	#Default domain
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

		label = gtk.Label("Default domain:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE,4)

	        self.def_domain = gtk.Entry(0)
	        self.def_domain.set_size_request(250,22)
		hbox.pack_end(self.def_domain, gtk.FALSE, gtk.FALSE,4)
# tcp ip end

# Wireless start
	     	vbox = gtk.VBox(gtk.FALSE)
		wirelessbox.pack_start(vbox, gtk.FALSE, gtk.FALSE)

	# Use any ESSID checkbox
		self.use_any_essid_check = gtk.CheckButton("Use \"any\" ESSID")
		self.use_any_essid_check.connect("toggled", self.toggle_use_any_essid)
		vbox.pack_start(self.use_any_essid_check, gtk.FALSE, gtk.FALSE)
		self.use_any_essid_check.set_border_width(4)

		content_frame = gtk.Frame("Config")
		content_frame.set_border_width(4)
		vbox.pack_start(content_frame, gtk.FALSE, gtk.FALSE)
		vbox2 = gtk.VBox(gtk.FALSE, 8)
		vbox2.set_border_width(6)
		content_frame.add(vbox2)

		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

	# ESSID input
		label = gtk.Label("ESSID:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 4)

	        self.essid = gtk.Entry(0)
	        self.essid.set_size_request(250,22)
		hbox.pack_end(self.essid, gtk.FALSE, gtk.FALSE, 4)

		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE, 4)

	# Operation mode
		label = gtk.Label("Operation mode:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 4)

		self.networktype_select = gtk.combo_box_new_text()
	      	for strtxt in self.w_modes:
	        	self.networktype_select.append_text(strtxt)    
	        self.networktype_select.connect('changed', self.wmode_select)
	        self.networktype_select.set_size_request(130,30)
		hbox.pack_start(self.networktype_select, gtk.FALSE, gtk.FALSE)

		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)

	# Channel select
		label = gtk.Label("Channel:")
	        hbox.pack_start(label, gtk.FALSE, gtk.TRUE,  4)

		adj = gtk.Adjustment(0, 0, 14, 1, 0, 0)
		self.channel_input = gtk.SpinButton(adj)
	        self.channel_input.set_wrap(gtk.TRUE)
	        hbox.pack_start(self.channel_input, gtk.FALSE, gtk.TRUE,  4)

		label = gtk.Label("0 = \"auto channel\"")
	        hbox.pack_start(label, gtk.FALSE, gtk.TRUE,  4)

		content_frame = gtk.Frame("WEP security")
		content_frame.set_border_width(4)
		vbox.pack_start(content_frame, gtk.FALSE, gtk.FALSE)
		vbox2 = gtk.VBox(gtk.FALSE, 8)
		vbox2.set_border_width(6)
		content_frame.add(vbox2)

	# Wep crypting
		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE)
		label = gtk.Label("Crypting:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 4)
		
		self.wepkeytype_select = gtk.combo_box_new_text()
	      	for strtxt in self.wepkey_types:
	        	self.wepkeytype_select.append_text(strtxt)    
	        self.wepkeytype_select.connect('changed', self.change_wepkey_type)
	        self.wepkeytype_select.set_size_request(110,30)

		hbox.pack_start(self.wepkeytype_select, gtk.FALSE, gtk.FALSE, 4)

	# Wep auth
	
		self.authtype_select = gtk.combo_box_new_text()
	      	for strtxt in self.w_auths:
	        	self.authtype_select.append_text(strtxt)    
	        self.authtype_select.connect('changed', self.change_auth_type)
	        self.authtype_select.set_size_request(110,30)

		hbox.pack_end(self.authtype_select, gtk.FALSE, gtk.FALSE, 4)

		label = gtk.Label("Auth.:")
		hbox.pack_end(label, gtk.FALSE, gtk.FALSE, 4)

		hbox = gtk.HBox(gtk.FALSE)
		vbox2.pack_start(hbox, gtk.FALSE, gtk.FALSE, 4)

	# Wep key entry
		label = gtk.Label("Key:")
		hbox.pack_start(label, gtk.FALSE, gtk.FALSE, 4)

	        self.wepkey = gtk.Entry(26)
	        self.wepkey.set_size_request(250,22)
		hbox.pack_end(self.wepkey, gtk.FALSE, gtk.FALSE, 4)
# Wireless end

# Ok and Cancel buttons
	        bbox = gtk.HButtonBox()
		MainBox.pack_start(bbox, gtk.FALSE, gtk.FALSE, 0)
	        bbox.set_layout(gtk.BUTTONBOX_END)

	        cancel_button = gtk.Button("Cancel",gtk.STOCK_CANCEL)
	        cancel_button.connect("clicked", gtk.main_quit)
	        bbox.add(cancel_button)

	        okbutton = gtk.Button("Ok",gtk.STOCK_OK)
	        okbutton.connect("clicked", self.close_and_update)
	        bbox.add(okbutton)
	        okbutton.set_flags(gtk.CAN_DEFAULT)
	        okbutton.grab_default()
		self.load_prefs()
		
		n = 0
	      	for strtxt in self.PROFILELIST:
	        	self.profilecombo.append_text(strtxt)   
	        	if (self.SETTING_NAME == strtxt):
	        		self.profilecombo.set_active(n)
	        	n += 1

	        self.profilecombo.connect('changed', self.changed_profile)
	        self.window.show_all()
		if (self.is_wireless):
			self.wirelessframe.show()
		else:
			self.notebook.set_current_page(2)
			self.wirelessframe.hide()
	        self.notebook.set_current_page(0)

	def set_network_type(self,widget,iswireless):
		if (iswireless):
			self.is_wireless = True
			self.wirelessframe.show()
			self.notebook.set_current_page(2)
			self.notebook.set_current_page(0)
		else:
			self.is_wireless = False
			self.wirelessframe.hide()
		return

	def toggle_use_dhcp(self,widget):
		if (self.use_dhcp):
			self.ip_adr.set_sensitive(gtk.STATE_INSENSITIVE)
			self.subnet.set_sensitive(gtk.STATE_INSENSITIVE)
			self.gateway.set_sensitive(gtk.STATE_INSENSITIVE)
			self.use_dhcp = False
		else:
			self.ip_adr.set_sensitive(gtk.STATE_NORMAL)
			self.subnet.set_sensitive(gtk.STATE_NORMAL)
			self.gateway.set_sensitive(gtk.STATE_NORMAL)
			self.use_dhcp = True
		return

	def toggle_get_dns_auto(self,widget):
		if (self.get_dns_auto):
			self.dns_1.set_sensitive(gtk.STATE_INSENSITIVE)
			self.dns_2.set_sensitive(gtk.STATE_INSENSITIVE)
			self.get_dns_auto = False
		else:
			self.dns_1.set_sensitive(gtk.STATE_NORMAL)
			self.dns_2.set_sensitive(gtk.STATE_NORMAL)
			self.get_dns_auto = True
		return

	def toggle_use_any_essid(self,widget):
		if (self.use_any_essid):
			self.essid.set_sensitive(gtk.STATE_INSENSITIVE)
			self.networktype_select.set_sensitive(gtk.STATE_INSENSITIVE)
			self.channel_input.set_sensitive(gtk.STATE_INSENSITIVE)
			self.wepkeytype_select.set_sensitive(gtk.STATE_INSENSITIVE)
			self.authtype_select.set_sensitive(gtk.STATE_INSENSITIVE)
			if (self.wepkey_type == "Disabled"):
				self.wepkey.set_sensitive(gtk.STATE_NORMAL)
				self.authtype_select.set_sensitive(gtk.STATE_NORMAL)
			else:
				self.wepkey.set_sensitive(gtk.STATE_INSENSITIVE)
				self.authtype_select.set_sensitive(gtk.STATE_INSENSITIVE)
			self.use_any_essid = False
		else:
			self.essid.set_sensitive(gtk.STATE_NORMAL)
			self.networktype_select.set_sensitive(gtk.STATE_NORMAL)
			self.channel_input.set_sensitive(gtk.STATE_NORMAL)
			self.wepkeytype_select.set_sensitive(gtk.STATE_NORMAL)
			self.authtype_select.set_sensitive(gtk.STATE_NORMAL)
			self.wepkey.set_sensitive(gtk.STATE_NORMAL)
			self.use_any_essid = True
		return

	def change_wepkey_type(self,combobox):
		model = combobox.get_model()
		active = combobox.get_active()
		data = model[active][0]
		self.wepkey_type = data
		if (data == "Disabled"):
			self.wepkey.set_sensitive(gtk.STATE_NORMAL)
			self.authtype_select.set_sensitive(gtk.STATE_NORMAL)
		else:
			if (data == "Hex"):
				self.wepkey.set_max_length(26)
			elif (data == "Text"):
				self.wepkey.set_max_length(13)
			self.wepkey.set_sensitive(gtk.STATE_INSENSITIVE)
			self.authtype_select.set_sensitive(gtk.STATE_INSENSITIVE)
		return

	def change_auth_type(self,combobox):
		model = combobox.get_model()
		active = combobox.get_active()
		self.w_auth = model[active][0]
		return

	def wmode_select(self,combobox):
		model = combobox.get_model()
		active = combobox.get_active()
    		self.w_mode = model[active][0]
		return

# ------------------- Setting/Profiles load & savde ------------------- 
	def set_defaults(self):
		self.def_domain.set_text("")
		self.is_wireless = False
		self.use_any_essid = True
		self.use_dhcp = True
		self.get_dns_auto = True
		self.w_mode = "managed"
		self.w_auth = "open"
		self.wepkey_type = "Disabled"
		self.def_domain.set_text("")
		self.dns_1.set_text("")
		self.dns_2.set_text("")
		self.ip_adr.set_text("")
		self.subnet.set_text("")
		self.gateway.set_text("")
		self.essid.set_text("")
		self.wepkey.set_text("")
		self.networktype_select.set_active(0)
		self.channel_input.set_value(0)
		self.wepkeytype_select.set_active(0)
		self.wepkeytype_select.set_active(0)
		self.authtype_select.set_active(0)
		self.connectiontype1.set_active(gtk.TRUE)
		self.connectiontype2.set_active(gtk.FALSE)


	def make_new_profile(self,widget):
		dialog = gtk.Dialog("Create new profile",self.window,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT,gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
		label = gtk.Label("Enter new profile name..")
		dialog.vbox.pack_start(label, gtk.FALSE, gtk.FALSE, 0)
		label.show()
	        newprofilename = gtk.Entry(0)
	        newprofilename.set_size_request(200,30)
	        # newprofilename.connect("changed", self.updatefilename)
	        dialog.vbox.pack_start(newprofilename, gtk.FALSE, gtk.FALSE, 0)
		newprofilename.show()
		result = dialog.run()
		dialog.destroy()
		if (result == gtk.RESPONSE_ACCEPT):
			if (newprofilename.get_text() != ""):
				isalready = False
				for strtxt in self.PROFILELIST:
					if (newprofilename.get_text().lower() == strtxt.lower()):
						isalready = True
						break
				if (newprofilename.get_text().isalnum() and isalready == False):
					self.PROFILELIST.append(newprofilename.get_text())
					self.SETTING_NAME = newprofilename.get_text()
					self.set_defaults()
					self.save_prefs()
					self.profilecombo.append_text(self.SETTING_NAME)
					self.profilecombo.set_active(len(self.PROFILELIST)-1)
				else:
					Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"Illegal charactes in profile name or profilename is in use.")
					Warningdialog.run()
					Warningdialog.destroy()
		return
		
	def changed_profile(self, combobox):
		model = combobox.get_model()
		active = combobox.get_active()
		if (self.NOTINUPDATEMODE):
			if (model[active][0] != self.SETTING_NAME):
				self.load_profile(model[active][0])

	def find_profile_name(self):
		model = self.profilecombo.get_model()
		active = self.profilecombo.get_active()
		return model[active][0]

	def load_profile(self,profilename):
		self.SETTING_NAME = profilename
		self.load_prefs()
		return True

	def rename_profile(self,widget):
		if ("default" != self.find_profile_name()):
			# Add the new name to profile list and set the old to be the one to be deleted..
			dialog = gtk.Dialog("Rename profile",self.window,gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT,gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
			label = gtk.Label("Enter profile name..")
			dialog.vbox.pack_start(label, gtk.FALSE, gtk.FALSE, 0)
			label.show()
		        newprofilename = gtk.Entry(0)
		        newprofilename.set_text(self.find_profile_name())
		        newprofilename.set_size_request(200,30)
		        dialog.vbox.pack_start(newprofilename, gtk.FALSE, gtk.FALSE, 0)
			newprofilename.show()
			result = dialog.run()
			dialog.destroy()
			if (result == gtk.RESPONSE_ACCEPT):
				if (newprofilename.get_text() != "" and newprofilename.get_text() != self.find_profile_name()):
					isalready = False
					for strtxt in self.PROFILELIST:
						if (newprofilename.get_text().lower() == strtxt.lower()):
							isalready = True
							break
					if (newprofilename.get_text().isalnum() and isalready == False):
						self.NOTINUPDATEMODE = False
						self.SETTING_NAME = newprofilename.get_text()
						self.DELETE_PROFILE_NAME = self.find_profile_name()
						self.save_prefs()
						self.profilecombo.remove_text(self.profilecombo.get_active())
						self.profilecombo.append_text(self.SETTING_NAME)
						self.profilecombo.set_active(len(self.PROFILELIST)-1)
						self.DELETE_PROFILE_NAME = ""
						self.NOTINUPDATEMODE = True
						self.load_prefs()
						self.profilecombo.set_active(len(self.PROFILELIST)-1)
					else:
						Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"Illegal charactes in profile name or profilename is in use.")
						Warningdialog.run()
						Warningdialog.destroy()
			return
		else:
			Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"Can't rename the default profile.")
			Warningdialog.run()
			Warningdialog.destroy()
		return


	def delete_profile(self,widget):
		if ("default" != self.find_profile_name()):
			Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_QUESTION,gtk.BUTTONS_YES_NO,"Are you sure you want to delete \""+self.SETTING_NAME+"\" profile?")
			result = Warningdialog.run()
			Warningdialog.destroy()
			if (result == gtk.RESPONSE_YES):		
				self.NOTINUPDATEMODE = False
				self.DELETE_PROFILE_NAME = self.find_profile_name()
				self.save_prefs()
				self.DELETE_PROFILE_NAME = ""
				self.NOTINUPDATEMODE = True
				self.profilecombo.remove_text(self.profilecombo.get_active())
		elif ("default" == self.find_profile_name()):
			Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"Can't delete the default profile.")
			Warningdialog.run()
			Warningdialog.destroy()
		return

	def load_prefs(self):
		if os.path.isfile(self.CFG_FILENAME):
			try:
				xmldoc = minidom.parse(self.CFG_FILENAME)
			except:
				return False
			else:
				self.PROFILELIST = []
				self.PROFILELIST.append(self.SETTING_NAME)
				tags = xmldoc.getElementsByTagName("NETWORKSETTINGS")
				for tag in tags:
					Network = tag.getElementsByTagName("Network")
					for Networkset in Network:
						if (self.SETTING_NAME == Networkset.getAttribute("SETTINGNAME")):
							if (Networkset.getAttribute("DHCP") == "1"):
								self.use_dhcp = False
								self.use_dhcp_check.set_active(gtk.TRUE)
								self.use_dhcp = True
								self.ip_adr.set_text("")
								self.subnet.set_text("")
								self.gateway.set_text("")
							else:
								self.use_dhcp = True
								self.use_dhcp_check.set_active(gtk.FALSE)
								self.use_dhcp = False
								self.ip_adr.set_text(Networkset.getAttribute("IP_ADR")+"")
								self.subnet.set_text(Networkset.getAttribute("SUBNET"))
								self.gateway.set_text(Networkset.getAttribute("GATEWAY"))

							if (Networkset.getAttribute("AUTO_DNS") == "1"):
								self.get_dns_auto = False
								self.get_dns_auto_check.set_active(gtk.TRUE)
								self.get_dns_auto = True
								self.dns_1.set_text("")
								self.dns_2.set_text("")
							else:
								self.get_dns_auto = True
								self.get_dns_auto_check.set_active(gtk.FALSE)
								self.get_dns_auto = False
								self.dns_1.set_text(Networkset.getAttribute("DNS_1"))
								self.dns_2.set_text(Networkset.getAttribute("DNS_2"))
							if (Networkset.getAttribute("DEF_DOMAIN") != ""):
								self.def_domain.set_text(Networkset.getAttribute("DEF_DOMAIN"))
							else:
								self.def_domain.set_text("")
							
							if (Networkset.getAttribute("IS_WIRELESS") == "1"):
								self.is_wireless = False
								self.connectiontype1.set_active(gtk.FALSE)
								self.connectiontype2.set_active(gtk.TRUE)
								self.is_wireless = True
								self.wirelessframe.show()
								self.notebook.set_current_page(2)
								self.notebook.set_current_page(0)
							else:
								self.is_wireless = True
								self.connectiontype1.set_active(gtk.TRUE)
								self.connectiontype2.set_active(gtk.FALSE)
								self.is_wireless = False
								self.wirelessframe.hide()
							
							if (Networkset.getAttribute("USE_ANY_ESSID") == "1"):
								self.use_any_essid = False
								self.use_any_essid_check.set_active(gtk.TRUE)
								self.use_any_essid = True
								self.essid.set_text("")
								self.networktype_select.set_active(0)
								self.channel_input.set_value(0)
								self.wepkeytype_select.set_active(0)
								self.wepkey.set_text("")
								self.authtype_select.set_active(0)
							else:
								self.use_any_essid = True
								self.use_any_essid_check.set_active(gtk.FALSE)
								self.use_any_essid = False
								self.essid.set_text(Networkset.getAttribute("ESSID"))
								i = 0
								for strtxt in self.w_modes:
									if (strtxt.lower() == Networkset.getAttribute("WMODE").lower()):
										self.networktype_select.set_active(i)
									i += 1

								if (Networkset.getAttribute("CHANNEL") <> ""):
									self.channel_input.set_value(int(Networkset.getAttribute("CHANNEL")))
								else:
									self.channel_input.set_value(0)
								i = 0
								for strtxt in self.wepkey_types:
									if (strtxt.lower() == Networkset.getAttribute("WEPKEY_TYPE").lower()):
										self.wepkeytype_select.set_active(i)
									i = i + 1
								i = 0
								for strtxt in self.w_auths:
									if (strtxt.lower() == Networkset.getAttribute("WEP_AUTHTYPE").lower()):
										self.authtype_select.set_active(i)
									i = i + 1
								self.wepkey.set_text(Networkset.getAttribute("WEPKEY"))
						else:
							self.PROFILELIST.append(Networkset.getAttribute("SETTINGNAME"))
				return True
		else:
			self.set_defaults()
			self.save_prefs()
			self.load_prefs()
			return False

	def save_prefs(self,widget=None):
		if (self.test_wepkey() == False):
			return False
		self.OUTPUT_WIRELESS = ""
		self.OUTPUT_NETWORK = ""
		conf_tree = minidom.Document()
		conf_tree.appendChild(conf_tree.createComment("pdaXrom settings file"))
		root_node = conf_tree.createElement("NETWORKSETTINGS")
		try:
			xmldoc = minidom.parse(self.CFG_FILENAME)
		except:
			net_node = conf_tree.createElement("Network")
			net_node.setAttribute("SETTINGNAME", self.SETTING_NAME)
			
			self.make_xml_save(net_node)
			
			root_node.appendChild(net_node)
			conf_tree.appendChild(root_node)
			FD = open(self.CFG_FILENAME, "w")
			FD.write(conf_tree.toprettyxml())
			FD.close()
		else:
			tags = xmldoc.getElementsByTagName("NETWORKSETTINGS")
			savedcurrent = False
			for tag in tags:
				Network = tag.getElementsByTagName("Network")
				for Networkset in Network:
					if (self.DELETE_PROFILE_NAME != Networkset.getAttribute("SETTINGNAME")):
						if (self.SETTING_NAME == Networkset.getAttribute("SETTINGNAME")):
							net_node = conf_tree.createElement("Network")
							net_node.setAttribute("SETTINGNAME", self.SETTING_NAME)
							
							self.make_xml_save(net_node)
							
							root_node.appendChild(net_node)
							savedcurrent = True
						else:
							root_node.appendChild(Networkset)

				conf_tree.appendChild(root_node)

			if (savedcurrent == False and self.DELETE_PROFILE_NAME != self.SETTING_NAME):
				net_node = conf_tree.createElement("Network")
				net_node.setAttribute("SETTINGNAME", self.SETTING_NAME)
				
				self.make_xml_save(net_node)
				
				root_node.appendChild(net_node)
				conf_tree.appendChild(root_node)

			FD = open(self.CFG_FILENAME, "w")
			FD.write(conf_tree.toprettyxml())
			FD.close()
		
		self.make_output_files()

	        if os.path.isdir("/etc/pcmcia"):
			if (self.OUTPUT_WIRELESS <> ""):
				f=open(self.WIRELESS_OPTS, 'w')
				f.write(self.wireless_header + self.OUTPUT_WIRELESS.strip() + self.wireless_footer)
				f.close()
	
			if (self.OUTPUT_NETWORK <> ""):
				f=open(self.NETWORK_OPTS, 'w')
				f.write(self.network_header + self.OUTPUT_NETWORK.strip() + self.network_footer)
				f.close()


		if (self.default_append_wireless <> ""):
			f=open(self.i686_WIRELESS_OPTS, 'w')
			self.default_append_wireless = self.default_append_wireless.replace(";;","")
			self.default_append_wireless = self.default_append_wireless.replace("*,*,*,*|default,*,*,*)","")
			f.write(self.default_append_wireless)
			f.close()

		if (self.default_append <> ""):
			f=open(self.i686_NETWORK_OPTS, 'w')
			self.default_append = self.default_append.replace(";;","")
			self.default_append = self.default_append.replace("*,*,*,*|default,*,*,*)","")
			f.write(self.default_append)
			f.close()
		return True

	def make_xml_save(self,net_node):
		if (self.is_wireless):
			net_node.setAttribute("IS_WIRELESS", "1")
		else:
			net_node.setAttribute("IS_WIRELESS", "0")

		if (self.use_dhcp):
			net_node.setAttribute("DHCP", "1")
			net_node.setAttribute("IP_ADR", "")
			net_node.setAttribute("SUBNET", "")
			net_node.setAttribute("GATEWAY", "")
		else:
			net_node.setAttribute("DHCP", "0")
			net_node.setAttribute("IP_ADR", self.ip_adr.get_text())
			net_node.setAttribute("SUBNET", self.subnet.get_text())
			net_node.setAttribute("GATEWAY", self.gateway.get_text())

		if (self.get_dns_auto):
			net_node.setAttribute("AUTO_DNS", "1")
			net_node.setAttribute("DNS_1", "")
			net_node.setAttribute("DNS_2", "")
		else:
			net_node.setAttribute("AUTO_DNS", "0")
			net_node.setAttribute("DNS_1", self.dns_1.get_text())
			net_node.setAttribute("DNS_2", self.dns_2.get_text())
		
		net_node.setAttribute("DEF_DOMAIN",self.def_domain.get_text())

		if (self.use_any_essid):
			net_node.setAttribute("USE_ANY_ESSID", "1")
			net_node.setAttribute("ESSID", "")
			net_node.setAttribute("WMODE", "Managed")
			net_node.setAttribute("CHANNEL", "0")
			net_node.setAttribute("WEPKEY_TYPE", "Disabled")
			net_node.setAttribute("WEPKEY", "")
			net_node.setAttribute("WEP_AUTHTYPE", "")
		else:
			net_node.setAttribute("USE_ANY_ESSID", "0")
			net_node.setAttribute("ESSID", self.essid.get_text())
			net_node.setAttribute("WMODE", self.w_mode)
			net_node.setAttribute("CHANNEL", str(int(self.channel_input.get_value())))
			if (self.wepkey_type == "Disabled"):
				net_node.setAttribute("WEPKEY_TYPE", self.wepkey_type)
				net_node.setAttribute("WEPKEY", "")
			else:
				net_node.setAttribute("WEPKEY_TYPE", self.wepkey_type)
				net_node.setAttribute("WEPKEY", self.wepkey.get_text())
			net_node.setAttribute("WEP_AUTHTYPE", self.w_auth)
		
		return

	def make_output_files(self):
		returnstr_wireless = ""
		returnstr_network = ""
		self.default_append_wireless = ""
		self.default_append = ""
		if os.path.isfile(self.CFG_FILENAME):
			try:
				xmldoc = minidom.parse(self.CFG_FILENAME)
			except:
				return False
			else:
				tags = xmldoc.getElementsByTagName("NETWORKSETTINGS")
				for tag in tags:
					Network = tag.getElementsByTagName("Network")
					for Networkset in Network:
						if (Networkset.getAttribute("SETTINGNAME") == "default"):
							returnstr_network = "*,*,*,*|"+Networkset.getAttribute("SETTINGNAME")+",*,*,*)\n"
							returnstr_network += "\tINFO=\""+Networkset.getAttribute("SETTINGNAME")+"\""
						else:
							returnstr_network = Networkset.getAttribute("SETTINGNAME") + ",*,*,*)\n"
							returnstr_network += "\tINFO=\""+Networkset.getAttribute("SETTINGNAME")+"\""
						
						returnstr_network += self.network_standard

						if (Networkset.getAttribute("DHCP") == "1"):
							returnstr_network += "\tDHCP=\"y\"\n"
							returnstr_network += "\tIPADDR=\"\"\n"
							returnstr_network += "\tNETMASK=\"\"\n"
							returnstr_network += "\tGATEWAY=\"\"\n"
						else:
							returnstr_network += "\tDHCP=\"n\"\n"
							if (Networkset.getAttribute("IP_ADR") <> ""):
								returnstr_network += "\tIPADDR=\""+Networkset.getAttribute("IP_ADR")+"\"\n"
							if (Networkset.getAttribute("SUBNET") <> ""):
								returnstr_network += "\tNETMASK=\""+Networkset.getAttribute("SUBNET")+"\"\n"
							if (Networkset.getAttribute("GATEWAY") <> ""):
								returnstr_network += "\tGATEWAY=\""+Networkset.getAttribute("GATEWAY")+"\"\n"

						if (Networkset.getAttribute("AUTO_DNS") == "1"):
							returnstr_network += "\tDNS_1=\"\"\n"
							returnstr_network += "\tDNS_2=\"\"\n"
							returnstr_network += "\tDNS_3=\"\"\n"
						else:
							if (Networkset.getAttribute("DNS_1") <> ""):
								returnstr_network += "\tDNS_1=\""+Networkset.getAttribute("DNS_1")+"\"\n"
							if (Networkset.getAttribute("DNS_2") <> ""):
								returnstr_network += "\tDNS_2=\""+Networkset.getAttribute("DNS_2")+"\"\n"
							returnstr_network += "\tDNS_3=\"\"\n"

						if (Networkset.getAttribute("DEF_DOMAIN") <> ""):
							returnstr_network += "\tDOMAIN=\""+Networkset.getAttribute("DEF_DOMAIN")+"\"\n"
						else:
							returnstr_network += "\tDOMAIN=\"\"\n"
						
						returnstr_network += "\t;;"
						returnstr_network = returnstr_network.strip()+"\n\n"

						if (Networkset.getAttribute("SETTINGNAME") == "default"):
							self.default_append = returnstr_network
						else:
							self.OUTPUT_NETWORK += returnstr_network

						if (Networkset.getAttribute("IS_WIRELESS") == "1" or Networkset.getAttribute("SETTINGNAME") == "default"):
							if (Networkset.getAttribute("SETTINGNAME") == "default"):
								returnstr_wireless = "*,*,*,*|default,*,*,*)\n"
							else:
								returnstr_wireless = Networkset.getAttribute("SETTINGNAME") + ",*,*,*)\n"
							
							if (Networkset.getAttribute("IS_WIRELESS") == "0"):
								returnstr_wireless += "\tINFO=\""+Networkset.getAttribute("SETTINGNAME")+"\"\n"
								returnstr_wireless += "\tESSID=\"any\"\n"
								returnstr_wireless += "\tMODE=\"Managed\"\n"
								returnstr_wireless += "\tKEY=\"\"\n"
							else:
								returnstr_wireless += "\tINFO=\""+Networkset.getAttribute("SETTINGNAME")+"\"\n"
								
								if (Networkset.getAttribute("USE_ANY_ESSID") == "1"):
									returnstr_wireless += "\tESSID=\"any\"\n"
									returnstr_wireless += "\tMODE=\"Managed\"\n"
									returnstr_wireless += "\tKEY=\"\"\n"
								else:
									if (Networkset.getAttribute("ESSID") <> ""):
										returnstr_wireless += "\tESSID=\"" + Networkset.getAttribute("ESSID") + "\"\n"
									if (Networkset.getAttribute("WMODE") <> ""):
										returnstr_wireless += "\tMODE=\"" + Networkset.getAttribute("WMODE") + "\"\n"
									if (int(Networkset.getAttribute("CHANNEL")) <> "" and int(Networkset.getAttribute("CHANNEL")) > 0):
										returnstr_wireless += "\tCHANNEL=\"" + str(int(Networkset.getAttribute("CHANNEL"))) + "\"\n"
									if (Networkset.getAttribute("WEPKEY") <> "" and Networkset.getAttribute("WEPKEY_TYPE") <> "Disabled"):
										if (Networkset.getAttribute("WEPKEY_TYPE") == "Text"):
											key = Networkset.getAttribute("WEPKEY")
											# hexkey = ""
											# i = 1
											# while i <= len(key):
											#	hexkey += hex(ord(key[i-1:i]))[2:]
											#	i = i + 1
											# returnstr_wireless += "\tKEY=\"" + hexkey + "\"\n"
											returnstr_wireless += "\tKEY=\"s:" + key + " "+ Networkset.getAttribute("WEP_AUTHTYPE") +"\"\n"
										else:
											returnstr_wireless += "\tKEY=\"" + Networkset.getAttribute("WEPKEY") + " "+ Networkset.getAttribute("WEP_AUTHTYPE") +"\"\n"
									else:
										returnstr_wireless += "\tKEY=\"\"\n"

							returnstr_wireless += "\t;;"
							returnstr_wireless = returnstr_wireless.strip() + "\n\n"
							
							if (Networkset.getAttribute("SETTINGNAME") == "default"):
								self.default_append_wireless = returnstr_wireless
							else:
								self.OUTPUT_WIRELESS += returnstr_wireless
				print self.OUTPUT_WIRELESS
				if (self.default_append != ""):
					self.OUTPUT_NETWORK += self.default_append

				if (self.default_append_wireless != ""):
					self.OUTPUT_WIRELESS += self.default_append_wireless

				return True
		else:
			return False

	def test_wepkey(self):
		if (self.wepkey_type == "Hex"):
			if (self.wepkey.get_text() <> ""):
				if (len(self.wepkey.get_text()) < 9 or len(self.wepkey.get_text()) > 26):
					Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"The Hex key must be at least 9 chars\nand no more than 26 chars.")
					Warningdialog.run()
					Warningdialog.destroy()
					self.notebook.set_current_page(2)
					self.wepkey.grab_focus()
					return False

		elif (self.wepkey_type == "Text"):
			if (self.wepkey.get_text() <> ""):
				if (len(self.wepkey.get_text()) < 5 or len(self.wepkey.get_text()) > 13):
					Warningdialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,"The Text key must be at least 5 chars\nand no more than 13 chars.")
					Warningdialog.run()
					Warningdialog.destroy()
					self.notebook.set_current_page(2)
					self.wepkey.grab_focus()
					return False
		return True

	def close_and_update(self,widget):
		if (self.save_prefs() == False):
			return False
		else:
			os.system("/sbin/cardctl eject")
			os.system("/bin/sleep 1")
			os.system("/sbin/cardctl scheme " + self.SETTING_NAME + " >/dev/null 2>&1")
			os.system("/bin/sleep 1")
			os.system("/sbin/cardctl insert")
			gtk.main_quit()

	def main(self):
        	gtk.main()

if __name__ == "__main__":
	networksettings = networksettings()
	networksettings.main()