#%%PYTHON_PATH%%
# -*- 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.
#

import os, requests, re, sys, yaml, zipfile, subprocess, urllib, base64


sCurrentInfiniteVersion = '%%VERSION%%'
sInstallForm = r'%%INSTALL_FORM_PATH%%'
sInstallPackageFolder = r'%%INSTALL_PACKAGE_FOLDER%%'
sPython = 'python' if sys.platform == 'win32' else 'python3'

if __name__ == '__main__':
	lRootFolder = os.path.dirname( os.path.realpath( __file__ ) )
	os.chdir(lRootFolder)

	lPackagePostFix = '-win' if sys.platform == 'win32' else '-lin'
	with open(sInstallForm,'r',encoding='utf-8') as fd:
		lForm = yaml.safe_load(fd)
		if lForm['general']['docker_install']:
			lPackagePostFix = lPackagePostFix + '-docker'
	
	lAptCredentials = {
		'https://apt.3djuump.com':None
	}
	print('Current version : %s' % sCurrentInfiniteVersion)
	if lForm['general']['juump_apt'] != '' and lForm['general']['juump_apt'] != None:
		lUrl = urllib.parse.urlparse(lForm['general']['juump_apt'])
		lCredentials = None
		if not lUrl.username is None and not lUrl.password is None:
			lCredentials = base64.b64encode(('%s:%s' % (lUrl.username,lUrl.password)).encode('ascii')).decode('ascii')
		lAptCredentials['%s://%s' % (lUrl.scheme,lUrl.hostname)] = lCredentials
	lPatchBuildRef = sCurrentInfiniteVersion.split('-')[0].split('.')[2:4]
	lAptVersion = None
	lAptHost = None
	for e in lAptCredentials.keys():
		print('# %s ...' % e)
		lMajorMinor = '.'.join(sCurrentInfiniteVersion.split('.')[:2])
		lHeaders = {}
		if not lAptCredentials[e] is None:
			lHeaders['Authorization'] = "Basic %s" % lAptCredentials[e]
		lGetRes = requests.get('%s/package/infinite/%s/' % (e,lMajorMinor),timeout=10,headers=lHeaders)
		lFoundVersion = None
		lVersionRe = re.compile('(%s.[0-9]+\\.[0-9]+-[0-9a-z]+(?:-lin-docker|-lin|-win|-win-docker)?)' % lMajorMinor)
		if lGetRes.status_code != 200:
			print('\t- Fail to retrieve version from apt server : %s' % lGetRes.text)
			continue
		lSearchRes = lVersionRe.search(lGetRes.text)
		for v in lSearchRes.groups():
			lFoundVersion = v
		if lFoundVersion is None:
			print('\t- Fail to retrieve version on apt server')
			continue
		print('\t- Found version %s' % (lFoundVersion))
		lPatchBuildFound = lFoundVersion.split('-')[0].split('.')[2:4]
		if lPatchBuildFound == lPatchBuildRef:
			print('\t- Skip, same version as current one')
			continue
		if (int(lPatchBuildRef[0]) > int(lPatchBuildFound[0])) or ((int(lPatchBuildRef[0]) == int(lPatchBuildFound[0])) and (int(lPatchBuildRef[1]) >= int(lPatchBuildFound[1]))):
			print('\t- Skip, version is older than current one')
			continue
		if not lAptVersion is None:
			lPatchBuildSelected = lAptVersion.split('-')[0].split('.')[2:4]
			if (int(lPatchBuildSelected[0]) > int(lPatchBuildFound[0])) or ((int(lPatchBuildSelected[0]) == int(lPatchBuildFound[0])) and (int(lPatchBuildSelected[1]) >= int(lPatchBuildFound[1]))):
				print('\t- Skip, version is older than the one from %s' % (lAptHost))
				continue
		lAptVersion = lFoundVersion
		lAptHost = e
	if lAptVersion is None:
		print('No update found')
		sys.exit(0)
	lVal = input('Found a newer version %s, from %s, install ? [Y/n]' % (lAptVersion,lAptHost)).upper()
	if not lVal in ['Y','']:
		sys.exit(1)
	
	lPackageName = lAptVersion + lPackagePostFix
	
	if not os.path.exists(os.path.join(sInstallPackageFolder,lPackageName)):
		lDownloadUrl = '%s/package/infinite/%s/subpackages/%s.zip' % (lAptHost,lMajorMinor,lPackageName)
		lHeaders = {}
		if not lAptCredentials[lAptHost] is None:
			lHeaders['Authorization'] = "Basic %s" % lAptCredentials[lAptHost]
		
		print('Downloading %s ...' % lDownloadUrl)
		lGetRes = requests.get(lDownloadUrl, stream=True,headers=lHeaders)
		if lGetRes.status_code != 200:
			raise Exception('Fail to download install package %s' % lGetRes.text)
		lZipFile = os.path.join(os.path.join(sInstallPackageFolder,lPackageName + '.zip'))
		lTmpZipFile = lZipFile + '.tmp'
		with open(lTmpZipFile, 'wb') as fd:
			for chunk in lGetRes.iter_content(chunk_size=4*1024*1024):
				if not chunk:
					continue
				fd.write(chunk)
				fd.flush()
		os.rename(lTmpZipFile,lZipFile)
		
		print('Unzip install package to %s ...' % sInstallPackageFolder)
		lZip = zipfile.ZipFile(lZipFile, 'r')
		lZip.extractall(sInstallPackageFolder)
		lZip.close()
		os.unlink(lZipFile)
	
	lInfiniteInstallPackage = os.path.join(sInstallPackageFolder,lPackageName,'install form')
	
	print('Start installing %s package' % lPackageName)
	os.chdir(os.path.join(lInfiniteInstallPackage))
	subprocess.run([sPython,'install.py',sInstallForm,'--accept-eula','-f'])
	os.chdir(lRootFolder)