#!./python-embeded-win/python.exe
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This program belongs to AKKODIS INGENIERIE PRODUIT SAS.
# It is considered a trade secret, and is not to be divulged or used
# by parties who have not received written authorization from the owner.
#

# the main class
# basically a collection of values for installation
import sys,os,time,glob
sys.path.append(os.path.dirname( os.path.realpath( __file__ ) ))
import infinite

class InstallationInfos(infinite.commonInstallationInfos) :
	
	#object init
	def __init__(self) :
		infinite.commonInstallationInfos.__init__(self)
	
	def checkDirectoryProxyInstallationSoftwares(self) :
		infinite.checkServerInstallationSoftwares(self,[])

	def configureApache(self):
		infinite.configureApache(self)

	def installBinary (self) :
		if sys.platform == 'win32':	
			paramsProxy = {
				'Setup' : {
					'Lang' : 'en',
					'Dir' : self.proxy_binary_folder,
					}
				}
			paramsDirectory = {
				'Setup' : {
					'Lang' : 'en',
					'Dir' : self.directory_binary_folder,
					}
				}
		else :
			paramsProxy = {
				'lib3djuump-infinite-cli/eula' : ('string', 'yes'),
			}
			paramsDirectory = {
				'lib3djuump-infinite-cli/eula' : ('string', 'yes'),
			}
		infinite.installInfiniteBinary(self,self.directory_binary_installer,self.directory_service_name, paramsDirectory, [self.directory_binary_installer,self.proxy_binary_installer])
		infinite.installInfiniteBinary(self,self.proxy_binary_installer,self.proxy_service_name, paramsProxy, [])
	
if __name__ == '__main__':
	
	lTimeStart = time.time();
	
	os.chdir(os.path.dirname( os.path.realpath( __file__ ) ))
	
	lInfos = InstallationInfos()
	
	lSourceForm = None
	if len(sys.argv) > 1 and not sys.argv[1].startswith('-'):
		lSourceForm = sys.argv[1]
	else:
		lSourceForms = []
		for p in ['.','../..']:
			lSourceForms = lSourceForms + glob.glob(p+'/*form_install_info*.yaml')
		if len(lSourceForms) == 0:
			raise Exception('Fail to locate *form_install_info*.yaml file(s) from . or ../..')
		elif len(lSourceForms) == 1:
			lSourceForm = lSourceForms[0]
		else:
			lSourceForms = sorted(lSourceForms)
			lPrompt = 'Select install form : '
			for i in range(0,len(lSourceForms)):
				lPrompt = lPrompt + '\n\t[%d] : %s' % (i+1,lSourceForms[i])
			lSelectRes = input(lPrompt+'\n')
			try:
				lSelectRes = int(lSelectRes)-1
			except:
				lSelectRes = -1
			if lSelectRes < 0 or lSelectRes >= len(lSourceForms):
				raise Exception('Abort')
			lSourceForm = lSourceForms[lSelectRes]
	lSourceForm = os.path.realpath(lSourceForm)
	print('Start install from %s' % lSourceForm)
	# read from csv or from code
	lInfos.fromYaml(lSourceForm,'./validation_schema/schema_form_install_info.schema.json')
	
	infinite.acceptEula(lInfos)
	
	if sys.platform != "win32" or not lInfos.isDockerInstall():
		# check admin rights
		infinite.checkIsAdmin()
	
	if sys.platform != "win32" and not lInfos.isDockerInstall():
		infinite.checkAptVersion(lInfos)

	if not lInfos.isDockerInstall():
		infinite.checkPreviousInstallationSoftwares(lInfos)
		infinite.stopAllServices(lInfos)

		# install redistributables
		infinite.prepareSystem(lInfos)
	
	# create user and/or group
	infinite.createUserAndGroup(lInfos)
	
	# create folder hierarchy
	infinite.createFolders(lInfos)

	# create ssl key certificate pair
	infinite.createSSLFiles(lInfos)

	if not lInfos.isDockerInstall():
		# install postgres
		infinite.installPostgres(lInfos)
		# configure postgres
		infinite.configurePostgres(lInfos)
		# install postgres plugins
		infinite.installPostgresPlugins(lInfos)
		# install elasticsearch
		lInfos.installElasticSearch()
		# register elastic search service and the like
		lInfos.patchElasticSearch()
		# configure elasticsearch
		lInfos.configureElasticSearch()
		# install apache
		infinite.installApache(lInfos)
		# install infinite directory and proxy
		infinite.installInfiniteBinary(lInfos)

		# configure service
		infinite.configureCliAndRegisterDirectoryCredentials(lInfos)
		infinite.configureInfiniteService(lInfos)
		
		# configure apache
		infinite.configureApache(lInfos)
		# start the services
		infinite.startInfiniteServices(lInfos)
	else:
		infinite.checkDockerInstall(lInfos)
		infinite.configureInfiniteService(lInfos)
		infinite.updatePostgresConfFile(os.path.join(lInfos.general.install_basepath,'postgres.conf'),lInfos,None,None)
		infinite.updateElasticSearchConfFile(os.path.join(lInfos.general.install_basepath,'elasticsearch.yaml'),lInfos)
		infinite.configureApache(lInfos)
		infinite.createDockerImages(lInfos)
		lDownTimeStart = time.time();
		# start or restart docker stack
		infinite.stopDockerStack(lInfos)
		infinite.startDockerStack(lInfos)
		print("Down time %d s" % int(time.time() - lDownTimeStart))
	
	lInfos.createUpdateScript(lSourceForm)
	lTimeEnd = time.time()
	
	print("Installation done in %d s" % int(lTimeEnd - lTimeStart))
	