#!/usr/bin/env python
#
# Copyright 2006-2016 Hunan Kylin, Inc.  All Rights Reserved.
# 
# NOTICE: ALL INFORMATION CONTAINED HEREIN IS, AND REMAINS THE PROPERTY OF
# HUNAN KYLIN, INC. AND ITS SUPPLIERS, IF ANY. THE INTELLECTUAL AND
# TECHNICAL CONCEPTS CONTAINED HEREIN ARE PROPRIETARY TO HUNAN KYLIN, INC.
# AND ITS SUPPLIERS AND MAY BE COVERED BY U.S. AND FOREIGN PATENTS, PATENTS IN
# PROCESS, AND ARE PROTECTED BY TRADE SECRET OR COPYRIGHT LAW. DISSEMINATION
# OF THIS INFORMATION OR REPRODUCTION OF THIS MATERIAL IS STRICTLY FORBIDDEN
# UNLESS PRIOR WRITTEN PERMISSION IS OBTAINED FROM HUNAN KYLIN, INC.
#
# -*- coding: utf-8 -*-

#
# Offer the Main KYLINOS configuration and management menu
#

import os
import pdb 
import sys
from os.path import join, dirname, abspath, basename

# Find our python libraries
sys.path.append(join(dirname(dirname(abspath(sys.argv[0]))), 'etc/python'))

from KsvdUtil import xl_
import KsvdEnv
import KsvdNetConfig
import KsvdNetDev
import KsvdUtil
import KsvdApp
import KsvdScreen

class KsvdVDEMenuApp(KsvdApp.KsvdApp):
	#
	# Initialize the application framework
	#
	def __init__(self, appArgs):
		KsvdApp.KsvdApp.__init__(
			self,
			appArgs)

	#
	# Options other than the standard ones (-v, -V, -i, -l)
	#
	def AddOptions(self):
		self.parser.add_option(
			'-g', '--get',
			action = 'store_true',
			help = xl_('Get Network Configuration'))
		self.parser.add_option(
			'-s', '--set',
			action = 'store_true',
			help = xl_('Set Network Configuration'))
		self.parser.add_option(
			'-S', '--setdhcp',
			action = 'store_true',
			help = xl_('Set DHCP Network Configuration'))
		self.parser.add_option(
			'-d', '--device',
			action = 'store',
			help=xl_('Device name used by Mdvs.'),
			metavar='NAME')
		self.parser.add_option(
			'-I', '--ipaddr',
			action = 'store',
			help=xl_('Ipaddr used by Mdvs.'),
			metavar='IPV4')
		self.parser.add_option(
			'-n', '--netmask',
			action = 'store',
			help=xl_('Netmask used by Mdvs.'),
			metavar='IPV4')
		self.parser.add_option(
			'-G', '--gateway',
			action = 'store',
			help=xl_('Gateway used by Mdvs.'),
			metavar='IPV4')
		self.parser.add_option(
			'-D', '--dnslist',
			action = 'store',
			help=xl_('Dnslist used by Mdvs, if more than one, separated by comma.'),
			metavar='IPV4')
		self.parser.add_option(
			'-j', '--json',
			action = 'store_true',
			help = xl_('Get Network Configuration in json format'))
		self.parser.add_option(
			'-e', '--effectaction',
			type='string',
			action='store',
			default='',
			help=xl_('take effect after setting pkl.'),
			metavar='ACTION')
		self.parser.add_option(
			'-r', '--role',
			type='string',
			action='store',
			default='VDI_Only',
			help=xl_('Ksvd server role.'),
			metavar='ROLE')
		self.parser.add_option(
			'-N', '--nicconf',
			action='store_true',
			help=xl_('Change nic conf after set pkl; default False, do not change.'))

	#
	# Execute the ksvd-menu panels
	#
	def InvokeApp(self):
		# Analyze the options
		# Invoke the panels

		inOption , inArgs = self.parser.parse_args()
		if self.options.get:
			if self.options.json:
				if not KsvdNetConfig.getNetInfo():
					return 1
			else:
				if not KsvdNetConfig.getVDENetInfo():
					KsvdScreen.PrintError(xl_('Get action args Error:'
						'\noption: %(inOption)s \nargs:\"%(inArgs)s\"')
						%{'inOption':inOption, 'inArgs':inArgs})
					return 1

		elif self.options.set:
			# check args
			if self.options.device == None or self.options.device == "" \
				or self.options.ipaddr == None or self.options.ipaddr == "" \
				or self.options.netmask == None or self.options.netmask == "" \
				or self.options.gateway == None \
				or self.options.dnslist == None \
				or self.options.role == None:
				KsvdScreen.PrintError(xl_('Set action args Error:'
									'\noption: %(inOption)s \nargs:\"%(inArgs)s\"')
									%{'inOption':inOption, 'inArgs':inArgs})
				return 1

			if 'networkAndService' in self.options.effectaction:
				KsvdEnv.SystemCall(['systemctl', 'stop', 'uniqbvded'])
				rc0 = KsvdEnv.SystemCall(['systemctl', 'stop', 'KSVD'])
				if rc0 != 0:
					KsvdScreen.PrintError(xl_('Failed to stop KSVD service.'))
					return rc0
				if 'Mdvs' in KsvdUtil.ListDir('/sys/devices/virtual/net/') and KsvdNetConfig.NetworkConfigExists():
					rc1 = KsvdEnv.SystemCall([KsvdEnv.FileDB('rc.ksvd-ovs-network'), '--stop'])
					if rc1 != 0:
						KsvdScreen.PrintError(xl_('Failed to stop network.'))
						return rc1
				os.system('touch /run/ksvd-vde-menu.flag')

			# add for debug
			# KsvdScreen.PrintMessage(xl_('Set action args:'
			# 	'\noption: %(inOption)s \nargs:\"%(inArgs)s\"')
			# 	%{'inOption':inOption, 'inArgs':inArgs})

			# delete KsvdNetConfig.pkl if exists.
			KsvdNetConfig.ResetConfiguration()
			# write net info to a new KsvdNetConfig.pkl
			CurrNetCfg = KsvdNetConfig.GatherPureNetworkConfiguration(
																self.options.device.replace(' ',''),
																self.options.ipaddr.replace(' ',''),
																self.options.netmask.replace(' ',''),
																self.options.gateway.replace(' ',''),
																self.options.dnslist.replace(' ',''),
																self.options.role.replace(' ',''))
			if not CurrNetCfg:
				KsvdScreen.PrintError(xl_('Failed to get info from KsvdNetConfig.pkl .'))
				return 1
			else:
				if CurrNetCfg.StoreServerConfiguration():
					if self.options.nicconf:
						if not KsvdNetDev.SetNicConfFile(device=self.options.device.replace(' ', ''),
											ipaddr=self.options.ipaddr.replace(' ', ''),
											netmask=self.options.netmask.replace(' ', ''),
											gateway=self.options.gateway.replace(' ', ''),
											dnslist=self.options.dnslist.replace(' ', '').split(';')):
							KsvdScreen.PrintError(xl_('Failed to set nic configuretion file: ifcfg-xxx .'))
							return 1
				else:
					KsvdScreen.PrintError(xl_('Failed to save info to KsvdNetConfig.pkl.'))
					return 1

				if 'reboot' in self.options.effectaction:
					return KsvdEnv.SystemCall(['reboot'])
				elif 'networkAndService' in self.options.effectaction:
					kRc0=KsvdEnv.SystemCall(['systemctl', 'start', 'KSVD'])
					if kRc0 != 0:
						KsvdScreen.PrintError(xl_('Failed to start KSVD service.'))
						return 1
					kRc1=KsvdEnv.SystemCall(['systemctl', 'start', 'uniqbvded'])
					if kRc1 != 0:
						KsvdScreen.PrintError(xl_('Failed to start uniqbvded service.'))
						return 1
					os.system('rm -f /run/ksvd-vde-menu.flag')
					return 0 
				else:
					return 0
		elif self.options.setdhcp:
			os.system('ip addr flush dev Mdvs')
			os.system('echo "" > /var/lib/dhclient/dhclient-Mdvs.lease')
			# check args
			if self.options.device == None or self.options.device == "" \
				or self.options.role == None:
				KsvdScreen.PrintError(xl_('Set action args Error:'
									'\noption: %(inOption)s \nargs:\"%(inArgs)s\"')
									%{'inOption':inOption, 'inArgs':inArgs})
				return 1

			if 'networkAndService' in self.options.effectaction:
				KsvdEnv.SystemCall(['systemctl', 'stop', 'uniqbvded'])
				rc0 = KsvdEnv.SystemCall(['systemctl', 'stop', 'KSVD'])
				if rc0 != 0:
					KsvdScreen.PrintError(xl_('Failed to stop KSVD service.'))
					return rc0
				if 'Mdvs' in KsvdUtil.ListDir('/sys/devices/virtual/net/') and KsvdNetConfig.NetworkConfigExists():
					rc1 = KsvdEnv.SystemCall([KsvdEnv.FileDB('rc.ksvd-ovs-network'), '--stop'])
					if rc1 != 0:
						KsvdScreen.PrintError(xl_('Failed to stop network.'))
						return rc1
				os.system('touch /run/ksvd-vde-menu.flag')

			# delete KsvdNetConfig.pkl if exists.
			KsvdNetConfig.ResetConfiguration()
			# write net info to a new KsvdNetConfig.pkl
			CurrNetCfg = KsvdNetConfig.GatherPureNetworkConfiguration(
																self.options.device.replace(' ',''),
																'',
																'',
																'',
																'',
																self.options.role.replace(' ',''), True)
			if not CurrNetCfg:
				KsvdScreen.PrintError(xl_('Failed to get info from KsvdNetConfig.pkl .'))
				return 1
			else:
				if CurrNetCfg.StoreServerConfiguration():
					if self.options.nicconf:
						if not KsvdNetDev.SetNicConfFile(device=self.options.device.replace(' ', ''),
											ipaddr=self.options.ipaddr.replace(' ', ''),
											netmask=self.options.netmask.replace(' ', ''),
											gateway=self.options.gateway.replace(' ', ''),
											dnslist=self.options.dnslist.replace(' ', '').split(';')):
							KsvdScreen.PrintError(xl_('Failed to set nic configuretion file: ifcfg-xxx .'))
							return 1
				else:
					KsvdScreen.PrintError(xl_('Failed to save info to KsvdNetConfig.pkl.'))
					return 1

				if 'reboot' in self.options.effectaction:
					return KsvdEnv.SystemCall(['reboot'])
				elif 'networkAndService' in self.options.effectaction:
					kRc0=KsvdEnv.SystemCall(['systemctl', 'start', 'KSVD'])
					if kRc0 != 0:
						KsvdScreen.PrintError(xl_('Failed to start KSVD service.'))
						return 1
					kRc1=KsvdEnv.SystemCall(['systemctl', 'start', 'uniqbvded'])
					if kRc1 != 0:
						KsvdScreen.PrintError(xl_('Failed to start uniqbvded service.'))
						return 1
					os.system('rm -f /run/ksvd-vde-menu.flag')
					return 0 
				else:
					return 0
		else:
			KsvdScreen.PrintError(xl_('Action is not get or set:'
								'\noption: %(inOption)s \nargs:\"%(inArgs)s\"')
								%{'inOption':inOption, 'inArgs':inArgs})
			return 1

#pdb.set_trace()
# Run this program, that's all.
KsvdVDEMenuApp(appArgs = sys.argv).RunApp()

