#!/usr/bin/env python
from snack import *
import sys
import re
sys.path.append('../interface/')
sys.path.append('../new_partition/')

import ri_data
import partition_data as p_d
import interface_partition

config_xml = "../xml/install_cfg.xml"

class Screen:
	global screen
	#global dict
	dict = {}
	d_cbl = {}
	def __init__(self, name='screen', title='Welcome to Rocky Security OS', helpline='', text=''):
		Screen.screen = SnackScreen()
		Screen.screen.drawRootText(0, 0, title)
		helpline='<Tab>/<Alt-Tab> between elments  |  <Space> selects  |  <F5> Next  |  <F11> Cancel  |  <F12> OK/Edit/Install  | <ESC> Quit'
		Screen.screen.pushHelpLine(helpline)
		Screen.dict[name] = self
		Screen.buttonlist0 = [('OK','ok','F12'),('Cancel','cancel','F11')]
		Screen.buttonlist1 = [('OK','ok','F12'),('Cancel','cancel','F11'),('Quit','quit','ESC')]
		Screen.buttonlist2 = [('OK','ok','F12'),('Cancel','cancel','F11'),('Next','next','F5'),('Quit','quit','ESC')]
		Screen.buttonlist3 = [('Edit','ok','F12'),('Cancel','cancel','F11'),('Next','next','F5'),('Quit','quit','ESC')]
		Screen.buttonlist4 = [('Install','ok','F12'),('Back','cancel','F11')]
		Screen.buttonlist5 = [('OK','ok','F12'),('Cancel','cancel','F11'),('Next','next','F5')]

	@staticmethod
	def container_gridform(gridtitle, gridx, gridy):
		Screen.gridform = GridForm(Screen.screen, gridtitle, gridy, gridx)

	@staticmethod
	def container_grid(x, y, *widget):
		Screen.grid = Grid(y, x)
		row = 0
		for w in widget:
			Screen.grid.setField(w, 0, row)
			row = row + 1

	@staticmethod
	def container_grid_complex(x, y, *widget):
		Screen.grid_complex = Grid(y, x)
		row = 0
		col = 0
		for w in widget:
			Screen.grid_complex.setField(w, col, row )
			if col < y-1:
				col = col + 1
			else:
				row = row + 1
				col = 0

	@staticmethod
	def widget_textboxreflowed(width, text):
		Screen.textboxreflowed = TextboxReflowed(width, text)

	@staticmethod
	def widget_textbox(width, height, text):
		Screen.textbox = Textbox(width, height, text, scroll=1, wrap=1)

	@staticmethod
	def widget_clistbox(list_col_widths, list_col_labels, list_col_label_align, h=0):
		w = 0
		for i in list_col_widths:
			w = w + i + 2
		c = len(list_col_widths)

		Screen.clistbox = CListbox(height=h, cols=c,
			col_widths = list_col_widths,
			scroll=1, returnExit =1,
			width=w, col_pad=2,
			col_labels = list_col_labels,
			col_label_align=list_col_label_align)

	@staticmethod
	def widget_buttonbar(*buttonlist):
		Screen.bb = ButtonBar(Screen.screen, *buttonlist)

	@staticmethod
	def widget_checkboxlist(li_item):
		Screen.d_cbl = {}
		for item in li_item:
			Screen.d_cbl[item] = Checkbox(item)

	@staticmethod
	def widget_checkboxtree(h, li_item):
		Screen.checkboxtree = CheckboxTree(h, scroll=1)
		for item in li_item:
			Screen.checkboxtree.append(item)

	@staticmethod
	def widget_label(string):
		Screen.label = Label(string)

	@staticmethod
	def widget_entry(width, text=''):
		Screen.entry = Entry(width, text)

	@staticmethod
	def widget_checkbox(text):
		Screen.checkbox = Checkbox(text)

	@staticmethod
	def widget_listbox(h, *lis):
		Screen.listbox = Listbox(height=h, scroll=1)
		for i in lis:
			Screen.listbox.append(i, i)

	@staticmethod
	def initial_static_net():
		Screen.label_hostname = Label('     hostname: ')
		Screen.entry_hostname = Entry(20, getattr(ri_data.Network, 'hostname'))
		Screen.grid_hostname = Grid(2,1)
		Screen.grid_hostname.setField(Screen.label_hostname, 0, 0)
		Screen.grid_hostname.setField(Screen.entry_hostname, 1, 0)

		Screen.label_domain = Label('       domain: ')
		Screen.entry_domain = Entry(20, getattr(ri_data.Network, 'domain'))
		Screen.grid_domain = Grid(2,1)
		Screen.grid_domain.setField(Screen.label_domain, 0, 0)
		Screen.grid_domain.setField(Screen.entry_domain, 1, 0)

		Screen.label_ip = Label('           ip: ')
		Screen.entry_ip = Entry(20, getattr(ri_data.Network, 'ip'))
		Screen.grid_ip = Grid(2,1)
		Screen.grid_ip.setField(Screen.label_ip, 0, 0)
		Screen.grid_ip.setField(Screen.entry_ip, 1, 0)

		Screen.label_netmask = Label('      netmask: ')
		Screen.entry_netmask = Entry(20, getattr(ri_data.Network, 'mask'))
		Screen.grid_netmask = Grid(2,1)
		Screen.grid_netmask.setField(Screen.label_netmask, 0, 0)
		Screen.grid_netmask.setField(Screen.entry_netmask, 1, 0)

		Screen.label_gateway = Label('      gateway: ')
		Screen.entry_gateway = Entry(20, getattr(ri_data.Network, 'gateway'))
		Screen.grid_gateway  = Grid(2,1)
		Screen.grid_gateway.setField(Screen.label_gateway, 0, 0)
		Screen.grid_gateway.setField(Screen.entry_gateway, 1, 0)

		Screen.label_primary_dns = Label('  primary_dns: ')
		Screen.entry_primary_dns = Entry(20, getattr(ri_data.Network, 'primary_dns')) 
		Screen.grid_primary_dns = Grid(2,1)
		Screen.grid_primary_dns.setField(Screen.label_primary_dns, 0, 0)
		Screen.grid_primary_dns.setField(Screen.entry_primary_dns, 1, 0)

		Screen.label_secondary_dns = Label('secondary_dns: ')
		Screen.entry_secondary_dns = Entry(20, getattr(ri_data.Network, 'secondary_dns')) 
		Screen.grid_secondary_dns = Grid(2,1)
		Screen.grid_secondary_dns.setField(Screen.label_secondary_dns, 0, 0)
		Screen.grid_secondary_dns.setField(Screen.entry_secondary_dns, 1, 0)

	@staticmethod
	def yesno(gridtitle, gridx, gridy, *widget):
		Screen.form = Form()
		Screen.container_gridform(gridtitle, gridy, gridx)
		count = 0
		for i in widget:
			if i == 'TextboxReflowed':		
				Screen.gridform.add(Screen.textboxreflowed, 0, count)
				count = count + 1
			elif i == 'Textbox':
				Screen.gridform.add(Screen.textbox, 0, count)
				count = count + 1
			elif i == 'Entry':
				Screen.gridform.add(Screen.entry, 0, count)
				count = count + 1
			elif i == 'Checkbox':
				Screen.gridform.add(Screen.checkbox, 0, count)
				count = count + 1
			elif i == 'eLabel':
				Screen.gridform.add(Label(""), 0, count)
				count = count + 1
			elif i == "ButtonBar":
				Screen.gridform.add(Screen.bb, 0, count)
				count = count + 1
			elif i == "Label":
				Screen.gridform.add(Screen.label, 0, count)
				count = count + 1
			elif i == 'Listbox':
				Screen.gridform.add(Screen.listbox, 0, count)
				count = count + 1
			elif i == 'CListbox':
				Screen.gridform.add(Screen.clistbox, 0, count)
				count = count + 1
			elif i == 'CheckboxList':
				for i in Screen.d_cbl:
					Screen.gridform.add(Screen.d_cbl[i], 0, count, padding=(13,0,0,0), anchorLeft=1)
					count = count + 1
			elif i == 'CheckboxTree':
				Screen.gridform.add(Screen.checkboxtree,0,count)
				count = count + 1
			elif i == 'Grid':
				Screen.gridform.add(Screen.grid, 0, count)
				count = count + 1
			elif i == 'Grid_Complex':
				Screen.gridform.add(Screen.grid_complex, 0, count)
				count = count + 1
				
		Screen.form.add(Screen.gridform)
		Screen.screen.gridWrappedWindow(Screen.gridform, gridtitle)
		Screen.form.addHotKey("F12")
		res = Screen.form.run()
		Screen.screen.popWindow()
		#res = Screen.gridform.runOnce()
		if Screen.bb.buttonPressed(res) == "ok":
			s = 0
		elif Screen.bb.buttonPressed(res) == "cancel":
			s = -1
		elif Screen.bb.buttonPressed(res) == "next":
			s = 'help'
		elif Screen.bb.buttonPressed(res) == "quit":
			Screen.screen.finish()
			sys.exit(-1)
		if locals().has_key('s'):
			return s
	
	@staticmethod
	def pop_window(title, text, width, button='one'):
		Screen.p_window = GridForm(Screen.screen, title, 1, 2)
		Screen.p_window.add(TextboxReflowed(width, text),0,0)
		if button == 'one':
			Screen.p_window.add(Button('OK'),0,1)
			Screen.p_window.runOnce()
		else:
			p_bb = ButtonBar(Screen.screen,(('Yes','yes'),('No','no')))
			Screen.p_window.add(p_bb,0,1)
			p_res = Screen.p_window.runOnce()
			if p_bb.buttonPressed(p_res) == 'yes':
				return 0
			else:
				pass


		
class Welcome(Screen):
	#def __init__(self, helpline='<Tab>/<Alt-Tab> between elments  |  <Space> selects  |  <F5> Next  |  <F12> OK'):
	def __init__(self):
		Screen.__init__(self, name='welcome')
		#Screen.screen.pushHelpLine(Screen.helpline)

		self.text = 'Welcome!\n\nThis script will guide you through the installation of RSS packages.\n\nIf you want to install the system, then     please continue, else abort the installation and come back later.\n\nAre you really sure you want to continue?'
		Screen.widget_textboxreflowed(50, self.text)
		Screen.widget_buttonbar(Screen.buttonlist0)

	def set_data(self):
		s = Screen.yesno('welcome', 1, 3, 'TextboxReflowed', 'eLabel', 'ButtonBar')	
		return s

class SerialNumber(Screen):
	def __init__(self):
		Screen.__init__(self, name='serialnumber')

		self.text = 'please input a serial number'
		Screen.widget_textboxreflowed(50, self.text)
		Screen.widget_buttonbar(Screen.buttonlist1)

	def set_data(self):
		Screen.widget_entry(20, text=getattr(ri_data.SerialNumber,'value'))
		s = Screen.yesno('serialnumber', 1, 4, 'TextboxReflowed', 'Entry', 'eLabel', 'ButtonBar')
		if s == 0:
			ri_data.SerialNumber.value = Screen.entry.value()
		return s

class Raid(Screen):
	def __init__(self):
		Screen.__init__(self, name='raid')
		self.title = 'Making Raid devices'

	@staticmethod
	def init_from_internal():
		''' initialize raid raw devices partition with id 'fd' '''
		# get all component devices already in raid
		dev_in_raid = ri_data.Raid.dev_in_raid()
		
		#raw_devs = [ d for d in p_d.Partition.get_raid_devices() and d not in dev_in_raid ]
		raw_devs = []
		for d in p_d.Partition.get_raid_devices():
			if d.split('/dev/')[1] not in dev_in_raid:
				raw_devs.append(d.split('/dev/')[1])
		raw_devs.sort()
		return raw_devs

	def raid_raw_map(self):
		list=[]
		fd=Raid.init_from_internal()
		for d in fd:
			list.append((d,'','off'))
		return list

	def raid_raw_to_active(self,level,dname):
		list=self.raid_raw_map()
		actives = []

		if not list:
			return 0

		list_ct = []
		for i in list:
			list_ct.append(i[0])

		h = 5 if len(list_ct) > 5 else len(list_ct)
		Screen.widget_checkboxtree(h,list_ct)
		
		Screen.widget_buttonbar(Screen.buttonlist0)
		Screen.widget_textboxreflowed(47, 'Please select the active fd')
		while True:
			s = Screen.yesno(self.title, 1, 5, 'TextboxReflowed', 'eLabel', 'CheckboxTree', 'eLabel', 'ButtonBar')

			if s == 0:
				actives = []
				for i in Screen.checkboxtree.getSelection():
					actives.append(i)
				if int(level) < 2 and len(actives) < 2 :
					Screen.pop_window('Tips', 'Making a raid0 or raid1 needs two or more partitions.',30)
				elif int(level) == 5 and len(actives) < 3:
					ButtonChoiceWindow(Screen.screen, 'Warning', 'Making a raid5 needs three or more partitions.')
				else:
					#(dev, from_os, level, a_devs, s_devs=[]):
					if dname not in ri_data.Raid.dict.keys():
						ri_data.Raid(dname,'no',level,'','no','',actives,[])
					else:
						#print 'get_next_name error in active?'
						#print dname
						ri_data.Raid.dict[dname].active_components=actives
					break
			else:
				return s
		return s

	def raid_raw_to_spare(self,level,dname):
		if dname not in ri_data.Raid.dict.keys():
			return
		
		list=self.raid_raw_map()
		if not list:
			return 0
		
		list_ct = []
		for i in list:
			list_ct.append(i[0])

		h = 5 if len(list_ct) > 5 else len(list_ct)

		Screen.widget_checkboxtree(h, list_ct)

		Screen.widget_textboxreflowed(47, 'Please select the spare fd')
		Screen.widget_buttonbar(Screen.buttonlist0)

		s = Screen.yesno(self.title, 1, 5, 'TextboxReflowed', 'eLabel', 'CheckboxTree', 'eLabel', 'ButtonBar')

		if s == 0:
			spares = []
			for i in Screen.checkboxtree.getSelection():
				spares.append(i)

			#(dev, from_os, level, a_devs, s_devs=[]):
			if dname not in ri_data.Raid.dict.keys():
				ri_data.Raid(dname,'no',level,[],spares)
			else:
				ri_data.Raid.dict[dname].spare_components=spares
		return s

	def make_raid(self):
		fd_devices=Raid.init_from_internal()

		# from os 
		raid_text=''
		for R in ri_data.Raid.dict.values():
			raid_text+='%s (%s):\n active %s; spare %s\n'%(R.device,R.from_os,R.active_components,R.spare_components)
			
		#fd
		fd_devices_text='fd: '+','.join(fd_devices)

		raidx = ['raid0','raid1','raid5']
		Screen.widget_listbox(3, *raidx)
		Screen.widget_buttonbar(Screen.buttonlist0)
		Screen.widget_textboxreflowed(50, 'Please select make raidX\n%s\n%s' %(raid_text, fd_devices_text))
		
		s = Screen.yesno(self.title, 1, 6, 'TextboxReflowed', 'eLabel', 'Listbox', 'eLabel', 'ButtonBar')
		
		
		if s == 0:
			raid = Screen.listbox.current()
			dname = ri_data.Raid.get_next_device()
			self.raid_raw_to_active(raid[-1],dname)
			if raid[-1] != '0':
				self.raid_raw_to_spare(raid[-1],dname)
		else:
			return s

	def del_raid(self):
		# from os
		raid_text=''
		raid_choices=[]

		#for R in [ d for d in ri_data.Raid.dict.values() if d.from_os == 'no' ]:
		for R in [ d for d in ri_data.Raid.dict.values() ]:
			raid_text+='%s (%s):\n active %s; spare %s\n'%(R.device,R.from_os,R.active_components,R.spare_components)
			raid_choices.append((R.device,''))

		len_raid_choices = len(raid_choices)
		h = 5 if len(raid_choices) > 5 else len(raid_choices)
		
		Screen.widget_buttonbar(Screen.buttonlist0)
		Screen.listbox = Listbox(height=h, scroll=1)
		for i in raid_choices:
			Screen.listbox.append(i[0],i[0])
		Screen.widget_textboxreflowed(50, 'Please select raid wanted to delete\n%s' %(raid_text))
		
		s =  Screen.yesno(self.title, 1, 5, 'TextboxReflowed', 'eLabel', 'Listbox', 'eLabel', 'ButtonBar')

		if s == 0:
			device = Screen.listbox.current()
			del ri_data.Raid.dict[device]
			try:
				os.system('umount /dev/%s >/dev/null 2>&1' %(device))
			except:
				pass
			try:
				os.system('mdadm --stop /dev/%s >/dev/null 2>&1' %(device))
			except:
				pass
		return s

	def set_data(self):
		while True:
			list = ['Making the raid device','Delect raid device']
			fd_devices=Raid.init_from_internal()
			fd_devices_text=''
			raid_text=''
			
			#from_os_list= [ R.from_os for R in ri_data.Raid.dict.values() if R.from_os == 'no' ]
			from_os_list= [ R.from_os for R in ri_data.Raid.dict.values() ]
			
			if len(fd_devices) < 2 and  not from_os_list :
				return 0

			if not fd_devices :
				del list[list.index('Making the raid device')]
			else:
				fd_devices_text='fd: '+','.join(fd_devices)

			if not from_os_list:
				del list[list.index('Delect raid device')]
			else:
				for R in ri_data.Raid.dict.values():
					raid_text+='%s (%s):\n active %s; spare %s\n'%(R.device,R.from_os,R.active_components,R.spare_components)
			
			len_list = len(list)
			Screen.widget_listbox(len_list, *list)
			Screen.widget_buttonbar(Screen.buttonlist2)
			Screen.widget_textboxreflowed(50, 'Tip:if have finished making raid or wanna skip making\n    raid, you can press "Next" button to continue.\n\n%s\n%s' %(raid_text, fd_devices_text))

			s =  Screen.yesno(self.title, 1, 6, 'TextboxReflowed', 'eLabel', 'Listbox', 'eLabel', 'ButtonBar')
			
			if s == 0:
				string = Screen.listbox.current()

			if s == 0 and string == "Making the raid device":
				self.make_raid()
			elif s == 0 and string == "Delect raid device" :
				self.del_raid()
			else:
				return ( s == 'help' and '0' or s)

class MountPoint(Screen):
	def __init__(self):
		Screen.__init__(self, name='mountpoint')
		self.title = 'MountPoint Configure'
		self.disks = p_d.Partition.dict.keys()
		self.disks.sort()
		self.mds = ri_data.Raid.dict.keys()
		self.mds.sort()

	def check_mountpoint(self,flag='one'):
		nonmount_dir = ['/dev','/etc','/lib64','/lib','/bin','/sbin','/proc','/sys']
		if flag == 'one':
			mountpoint = Screen.entry.value()
			fs = Screen.listbox.current()
			if not mountpoint:
				return True
			if fs == 'linux-swap' and mountpoint:
				return False
			for m in nonmount_dir:
				if re.match(m+'/',mountpoint) or m == mountpoint:
					return False
			if mountpoint[0] != '/':
				return False
			else:
				for i in mountpoint[1:len(mountpoint)]:
					if i == ' ':
						return False
				return True
		elif flag == 'all':
			list_mountpoint = []
			for m in ri_data.Raid.dict.keys():
			    R = ri_data.Raid.dict[m]
			    if R.mp != '':
				list_mountpoint.append(R.mp)

			for d in self.disks:
				if p_d.Partition.dict[d]['partition_table'] == '':
					continue
				for p in p_d.sort_partitions(p_d.Partition.dict, d, 'partition'):
					if p_d.Partition.dict[d]['partition'][p]['mount_point'] != '':
						list_mountpoint.append(p_d.Partition.dict[d]['partition'][p]['mount_point'])
			if len(list_mountpoint) != len(list(set(list_mountpoint))) or '/' not in list_mountpoint:
				return False
			else:
				return True

	def set_mountpoint(self, device):
		disk = device.split(':')[0]
		dev = device.split(':')[1]
		MD = True if re.search('md',disk) else False

		Screen.widget_buttonbar(Screen.buttonlist0)
		Screen.widget_textboxreflowed(30, 'Please input the mountpoint and select the file system type.')
		Screen.label_mp = Label('mountpoint : ')
		Screen.label_fs = Label('File System Type : ')
		Screen.widget_label('')
		fs_list = ['ext2','ext3', 'ext4', 'linux-swap', 'reiserfs', 'xfs', 'jfs']
		Screen.widget_listbox(3, *fs_list)
		Screen.widget_checkbox('Format the partition')
		Screen.listbox.setCurrent('ext3')

		if MD:
		    if ri_data.Raid.dict[disk].fmt == 'yes':
			Screen.checkbox.setValue('*')
		    try:
			Screen.listbox.setCurrent(ri_data.Raid.dict[disk].filesystem)
		    except:
			pass
		    Screen.widget_entry(15, text=ri_data.Raid.dict[disk].mp)
		else:
		    if p_d.Partition.dict[disk]['partition'][dev]['format'] == 'yes':
			Screen.checkbox.setValue('*')
		    try:
			Screen.listbox.setCurrent(p_d.Partition.dict[disk]['partition'][dev]['filesystem'])
		    except:
			pass
		    Screen.widget_entry(15, text=p_d.Partition.dict[disk]['partition'][dev]['mount_point'])

		Screen.container_grid_complex(3, 2, Screen.label_mp, Screen.entry, Screen.label, Screen.label, Screen.label_fs, Screen.listbox)
		while True:
			s =  Screen.yesno(self.title, 1, 8, 'TextboxReflowed', 'eLabel', 'Grid_Complex', 'eLabel', 'Checkbox','eLabel','ButtonBar')
			if s == 0:
				if not self.check_mountpoint(flag='one'):
					Screen.pop_window('Invalid mount point','The mount point you entered is invalid.\nMount point must start with "/".They cannot contain spaces.\nMount point cannot be "/dev","/etc","/lib","lib64","/bin","/sbin","/proc","/sys".\nAnd when formatted linux-swap filesystem, the partition can not be mounted.', 50)
					continue
				if MD:
				    if Screen.entry.value() != '' or Screen.checkbox.value() == 1:
					ri_data.Raid.dict[disk].fmt = 'yes'
				    else:
					ri_data.Raid.dict[disk].fmt = 'no'
				    ri_data.Raid.dict[disk].filesystem = Screen.listbox.current()
				    ri_data.Raid.dict[disk].mp = Screen.entry.value()
				    break
				    #p_d.Partition.dict[disk]['partition'][dev]['format'] = 'yes'
				else:
				    if Screen.entry.value() != '' or Screen.checkbox.value() == 1:
					p_d.Partition.dict[disk]['partition'][dev]['format'] = 'yes'
				    else:
					p_d.Partition.dict[disk]['partition'][dev]['format'] = 'no'
				    p_d.Partition.dict[disk]['partition'][dev]['filesystem'] = Screen.listbox.current()
				    p_d.Partition.dict[disk]['partition'][dev]['mount_point'] = Screen.entry.value()
				    break
			else:
				break
		return s

	def set_data(self):
		ri_data.MountPoint.init_from_internal()
		while True:
			#len_keys = len(keys)
			# 18 is length of '/dev/cciss/c0d0p1'
			list_col_widths = [18, 12, 10, 15, 10]
			list_col_labels = []
			list_col_label_align = [CENTER, CENTER, CENTER, CENTER, CENTER]
			Screen.widget_clistbox(list_col_widths, list_col_labels, list_col_label_align, h=5)
			for k in ri_data.Raid.dict.keys():
				R = ri_data.Raid.dict[k]
				dev = ri_data.Raid.dict[k].device
				Screen.clistbox.append(["/dev/%s" %(dev),
					"%s" %(R.mp.ljust(10)),
					"%s" %(R.filesystem.ljust(10)),
					"%s" %(R.fmt.ljust(5)),
					"%s" %(ri_data.Raid.get_size(dev))],
					"%s:%s" %(dev, 'p'),
					[LEFT, LEFT, LEFT, LEFT, CENTER])

			dev_in_raid = ri_data.Raid.dev_in_raid()
			for d in self.disks:
				if p_d.Partition.dict[d]['partition_table'] == '':
					continue
				partitions = p_d.sort_partitions(p_d.Partition.dict, d, 'partition')
				for p in partitions:
					# loop for nest dict to find partition
					for k in p_d.Partition.dict[d]['partition'].keys():
						if p == k:
							if p_d.Partition.dict[d]['partition'][p]['type'] == 'extended' or p.split('/dev/')[1] in dev_in_raid:
								continue
							size_pretty = interface_partition.pretty_unit(interface_partition.get_num(p_d.Partition.dict[d]['partition'][p]['size']))
							Screen.clistbox.append(["%s" %(p),
                        			"%s" %(p_d.Partition.dict[d]['partition'][p]['mount_point'].ljust(10)),
                        			"%s" %(p_d.Partition.dict[d]['partition'][p]['filesystem'].ljust(10)),
                        			"%s" %(p_d.Partition.dict[d]['partition'][p]['format'].ljust(5)),
                        			"%s" %(size_pretty)],
									"%s:%s" %(d, p),
                        			[LEFT, LEFT, LEFT, LEFT, CENTER])
							break
			
			Screen.widget_buttonbar(Screen.buttonlist3)
			Screen.widget_textboxreflowed(65, 'There are five colums in the mount point display frame:\n    { Device    Mountpoint    Filesystem    Format    Size }\nTip: if you have finished configured mountpoint,you can press\n    "Next" button to continue.')
			s =  Screen.yesno(self.title, 1, 6, 'TextboxReflowed', 'CListbox', 'eLabel', 'ButtonBar')
			
			if s == 0:
				try:
				    self.set_mountpoint(Screen.clistbox.current())
				except:
				    pass
				# edit mountpoint
			elif s == -1:
				break
			else:
				if not self.check_mountpoint(flag='all'):
					Screen.pop_window('Invalid mount point','Two file systems must not be assigned the same mount point.\nA root file system is needed.\nPlease correct this by changing mount points.', 50)
					continue
				break
		return (s == 'help' and '0' or s)
		
class Network(Screen):
	def __init__(self):
		Screen.__init__(self, name='network')
		self.title = 'Network Configure'

		self.rb_static = SingleRadioButton("Static IP Address", None, 1)
		self.rb_dynamic = SingleRadioButton("Dynamic IP Address", self.rb_static)
		Screen.widget_buttonbar(Screen.buttonlist1)

	def check_network(self, n):
		try:
			if (re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",n) and \
				len([i for i in n.split('.') if (0 <= int(i) <= 255)]) == 4):
				return True
			else:
				return False
		except(ValueError):
			return False

	def set_network(self, t):
		if t == 'dynamic':
			Screen.widget_textboxreflowed(50, 'Please enter the hostname:')
			Screen.widget_entry(20, text=getattr(ri_data.Network, 'hostname'))
			s = Screen.yesno(self.title, 1, 6, 'TextboxReflowed', 'eLabel', 'Entry', 'eLabel', 'ButtonBar')
			if s == 0:
				setattr(ri_data.Network, 'hostname', Screen.entry.value())
				
		elif t == 'static':
			Screen.widget_buttonbar(Screen.buttonlist1)
			Screen.widget_textboxreflowed(50, 'Please configure the static net:')
			Screen.initial_static_net()
			Screen.container_grid(7, 1, Screen.grid_hostname, Screen.grid_domain, Screen.grid_ip,\
				Screen.grid_netmask, Screen.grid_gateway, Screen.grid_primary_dns, Screen.grid_secondary_dns)
			
			while True:
				s = Screen.yesno(self.title, 1, 6, 'TextboxReflowed', 'eLabel', 'Grid', 'eLabel', 'ButtonBar')
				if s == 0:
					if self.check_network(Screen.entry_ip.value()) and \
							self.check_network(Screen.entry_netmask.value()) and \
							self.check_network(Screen.entry_gateway.value()) and \
							self.check_network(Screen.entry_primary_dns.value()):
						
						setattr(ri_data.Network, 'hostname', Screen.entry_hostname.value())
						setattr(ri_data.Network, 'domain', Screen.entry_domain.value())
						setattr(ri_data.Network, 'ip', Screen.entry_ip.value())
						setattr(ri_data.Network, 'mask', Screen.entry_netmask.value())
						setattr(ri_data.Network, 'gateway', Screen.entry_gateway.value())
						setattr(ri_data.Network, 'primary_dns', Screen.entry_primary_dns.value())
						setattr(ri_data.Network, 'secondary_dns', Screen.entry_secondary_dns.value())
						break
					else:
						Screen.pop_window('Tips', 'There is something wrong with your input network address.', 30)
				elif s == -1:
					break
				#else:
				#	return (s == 'help' and '0' or s)
		return s 


	def set_data(self):
		Screen.container_grid(2,1,self.rb_static, self.rb_dynamic)
		Screen.widget_textboxreflowed(50, 'Please select the network type')	
		
		s = Screen.yesno(self.title, 1, 5, 'TextboxReflowed', 'eLabel', 'Grid', 'eLabel', 'ButtonBar')
		
		if s == 0 and self.rb_static.selected():
			ri_data.Network.configuration = 'static'
			s = self.set_network('static')

		elif s == 0 and self.rb_dynamic.selected():
			ri_data.Network.configuration = 'dynamic'
			s = self.set_network('dynamic')

		return s

class Group(Screen):
	def __init__(self):
		Screen.__init__(self, name='group')
		self.title = 'Package Group Selcect'

	def set_data(self):

		ri_data.Group.dict['base'].install = 'yes'
		ri_data.Group.dict['base'].selection = 'all'
		g_list = []
		for g in ri_data.Group.dict.keys():
			if g.encode('ascii') != 'base':
				g_list.append(g.encode('ascii'))

		Screen.widget_buttonbar(Screen.buttonlist1)
		Screen.widget_textboxreflowed(50, 'Please select the software package groups')
		h = 5 if len(g_list) > 5 else len(g_list)
		Screen.widget_checkboxtree(h, g_list)

		for g in g_list:
			if ri_data.Group.dict[g].install == 'yes':
				Screen.checkboxtree.setEntryValue(g, selected=1)
		
		s = Screen.yesno(self.title, 1, 5, 'TextboxReflowed', 'eLabel', 'CheckboxTree', 'eLabel', 'ButtonBar')
		
		if s == 0:		
			for g in g_list:
				if g in Screen.checkboxtree.getSelection():
					ri_data.Group.dict[g].install='yes'
					ri_data.Group.dict[g].selection='all'
				else:
					ri_data.Group.dict[g].install='no'

		return s


class Service(Screen):
	def __init__(self):
		Screen.__init__(self, name='service')
		self.title = 'Start Service'

	def set_data(self):
		ri_data.Service.change_state()
		
		s_list = ['check all']
		for s in ri_data.Service.list:
			if s.start != 'disable':
				s_list.append(s.name)
		
		Screen.widget_buttonbar(Screen.buttonlist1)
		Screen.widget_textboxreflowed(50, 'Please select the start services')
		h = 5 if len(s_list) > 5 else len(s_list)
		Screen.widget_checkboxtree(h, s_list)

		for service in ri_data.Service.list:
			if service.start == 'yes':
				Screen.checkboxtree.setEntryValue(service.name, selected=1)

		s = Screen.yesno(self.title, 1, 5, 'TextboxReflowed', 'eLabel', 'CheckboxTree', 'eLabel', 'ButtonBar')
		
		if s == 0:
			if 'check all' in Screen.checkboxtree.getSelection():
				for service in ri_data.Service.list:
					if service.start != 'disable':
						service.start='yes'
			else:
				for service in ri_data.Service.list:
					if service.start != 'disable':
						if service.name in Screen.checkboxtree.getSelection():
							service.start = 'yes'
						else:
							service.start = 'no'
			#ri_data.to_xml()

		return s

class FinishState(Screen):
	def __init__(self):
		Screen.__init__(self, name='finishstate')

		self.text = 'After finishing installed Rocky OS system, do you want to reboot, shutdown or just do nothing ?'
		Screen.widget_textboxreflowed(50, self.text)
		Screen.widget_buttonbar(Screen.buttonlist1)

        	reboot_value = 0
        	shutdown_value = 0
        	nothing_value = 0
        	default_value = getattr(ri_data.FinishState, 'flag')

	        if default_value == 'reboot':
        	    reboot_value = 1
	        elif default_value == 'shutdown':
        	    shutdown_value = 1
	        else:
        	    nothing_value = 1
	        self.rb = RadioBar(Screen,(('Reboot', 'reboot', reboot_value), ('Shutdown', \
            'shutdown', shutdown_value), ('Nothing', 'nothing', nothing_value)))
        
	        Screen.container_grid(1,1,self.rb)

	def set_data(self):
		#Screen.widget_entry(20, text=getattr(ri_data.FinishState,'flag'))
		s = Screen.yesno('finishstate', 1, 5, 'TextboxReflowed', 'eLable', 'Grid', 'eLabel', 'ButtonBar')
		if s == 0:
			ri_data.FinishState.flag = self.rb.getSelection()

			ri_data.to_xml()
		return s

class Prepar_installation(Screen):
	def __init__(self):
		Screen.__init__(self, name='information')
		self.title = 'Installation Information'

	def set_data(self):
		string = open('/var/install/install.xml').read()
		Screen.widget_textbox(100,30,string)
		Screen.widget_buttonbar(Screen.buttonlist4)
		s = Screen.yesno(self.title, 1, 3, 'Textbox', 'eLabel', 'ButtonBar')
		
		return s

