source scripts/update/utils

_version = $1
_versionFormatted = ($_version replaceAll '-' '.')

partial = (__FALSE__)

argsSplitted = $__ORIGIN_ARGS__ split " "

each $argsSplitted {

	_arg = $it
	_val = $_arg trim

	if { "partial" equals $_val } {
		partial = (__TRUE__)
	}

}

featureService = (service:get org.apache.karaf.features.FeaturesService)

_configFeature = ($featureService getFeature "entaxy-update-configuration" $_version)

__set_component_status = {
	_comp = $1
	_prop = "${_comp}.status"
	if { $_comp equals '' } {
		_prop = "update.status"
	}
	config:edit $_pid
	config:property-set "${_prop}" $2
	config:update
}

if { $_configFeature equals ''} {
	echo "!!!"
	echo "Update ${_version} not found"
} else {
	
	_pid = "entaxy.update.$_versionFormatted"

	configService = (service:get org.osgi.service.cm.ConfigurationAdmin)
	configuration = ($configService getConfiguration $_pid)
	properties = ($configuration getProperties)

	_components = ( $properties get "components") toString
	_componentsList = $_components split ","	

	total = ($_componentsList length)
	installed = new java.util.ArrayList
	toInstall = new java.util.ArrayList
	blocked = new java.util.ArrayList

	each $_componentsList {

		_component = $it
		_status = ($properties get "${_component}.status")
#		echo "${it} : ${_status}"

		if { $_status equals "INSTALLED" } {
			($installed add $_component)
			continue
		}

		if { $_status equals "VERSION_MISMATCH" } {
			echo "!!! ERROR !!!"
			echo "Update can not be installed: VERSION_MISMATCH for component \[${_component}\]"
			break
		}

		_repo = ($properties get "${_component}.update.repo")
		if { $_repo equals '' } {
			_status = "REPO_NOT_FOUND"

			__set_component_status ${_component} $_status

		} else {

#			echo " CHECK !!!"	
			_exists = __utils_check_install_repo $_repo

			if { NOT { $_exists } } {
				_status = "REPO_NOT_FOUND"
				__set_component_status ${_component} $_status

			}

		}

		if { $_status equals "REPO_NOT_FOUND" } {
			
			($blocked add $_component)

			if { $partial } {

				echo ""	
				echo "\-\-\- INFO \-\-\-"
				echo "Update can not be installed: REPO_NOT_FOUND for component \[${_component}\]"
				echo "Partial update is allowed, so the process will move on"
				echo ""	
				continue				

			} else {
				echo ""	
				echo "!!! ERROR !!!"
				echo "Update can not be installed: REPO_NOT_FOUND for component \[${_component}\]"
				echo "Partial update is NOT allowed, so the process will stop"
				echo ""	
				break
			}
		}

		($toInstall add $_component)

	}
	
#	echo $total
#	echo $installed
#	echo $toInstall
#	echo $blocked

	_processInstall = (__FALSE__)

	if { ($toInstall isEmpty) } {
		echo "Nothing to install"
	} else {
		sz = ($toInstall size)
		if { %(sz < total) } {
#			echo "Partial install"
			_processInstall = $partial	
		} else {
			_processInstall = (__TRUE__)
		}
	}

	_rebootNeeded = new (($.context bundle) loadClass java.lang.Boolean) 'false'

#	echo
#	echo "${toInstall}"
#	echo ($toInstall size)
#	echo

	totalToInstall = ($toInstall size)
#	echo "TOTAL :: ${totalToInstall}"

	if { $_processInstall } {
		__set_component_status '' "INSTALLING"
		each $toInstall {
			_component = $it
			_baseFeatureName = $properties get "${_component}.feature"
			_featureName = "${_baseFeatureName}-update"
			_feature = ($featureService getFeature "${_featureName}" $_version)
			_featureStatus = ($featureService getState $_feature) toString
			if { $_featureStatus equals "Uninstalled" } {
				feature:install -v -r "${_featureName}/$_version"
				_featureStatus = ($featureService getState $_feature) toString
#				echo " AFTER INSTALL :: ${_featureStatus}"
				if { NOT { $_featureStatus equals "Started" } } {
					__set_component_status ${_component} "FEATURE_INSTALL_FAILED"
					($blocked add $_component)
					continue
				}
			}

			karafRoot = ((($.context bundle) loadClass java.lang.System) getProperty 'karaf.home')
			cd $karafRoot
			cd updates/$_version
			_files = (shell:ls -m) toString
			cd $karafRoot
		
			_filesArr = ($_files split ",")
			_filesList = new java.util.ArrayList
			each $_filesArr {
				$_filesList add ($it trim)
			}
			_current = $properties get "${_component}.current.version"
			_componentFeatureName = $properties get "${_component}.feature"
			li = $_current length
			_script = ""
			while { %(li>0) } {
				
				_current = $_current substring 0 $li
				_scriptName = "${_componentFeatureName}.${_current}.update"

#				echo "TEST :: $_scriptName"
				if { $_filesList contains $_scriptName } {
					_script = $_scriptName
					break
				}

				li = $_current lastIndexOf "."


			}
			if { $_script equals '' } {

				_scriptName = "${_componentFeatureName}.update"
				echo "TEST :: $_scriptName"
			}

#			echo "SCRIPT :: ${_scriptName}"	

			echo "\>\> Running installations script"
			echo "\>\> updates/${_version}/${_script}"

			source updates/$_version/$_script

#			echo "RESULT :: ${__RESULT__}"
			_error = ($__RESULT__ get "error")
		
			if { $_error } {
				_message = $__RESULT__ get "message"
				echo ""	
				echo "!!! ERROR !!!"
				echo "${_message}"
				echo
			}
			
			_resultStatus = $__RESULT__ get "status"
			if { $_resultStatus equals 'ALREADY_INSTALLED' } {
				_resultStatus = "INSTALLED"
			}

			if { $_resultStatus equals 'INSTALLED' } {
				%(totalToInstall-=1)
			}
			
			if { NOT { $_resultStatus equals '' } } {
				__set_component_status ${_component} $_resultStatus
			}

			_reboot = ($__RESULT__ get "reboot")
			if { NOT { $_reboot equals "" } } {
				if { NOT { $_reboot equals "false" } } {
					_rebootNeeded = (__TRUE__)
					echo "** the system will reboot now to apply updates"
					echo
					echo "** PLEASE RUN THE SCRIPT AGAIN AFTER RESTART **"
					if { $_reboot equals "force" } {
						shutdown -r -f
					} else {
						shutdown -r
					}
					break
				}
			}
		}


	}

	blockedSize = ($blocked size)

	if { NOT { $_rebootNeeded } } {
	
		if { %(totalToInstall+blockedSize>0) } {
			__set_component_status '' "PARTIAL_INSTALLED"
		} else {
			__set_component_status '' "INSTALLED"
		}

		echo
		echo "*********"
		echo "** UPDATE FINISHED"
		echo "*********"
		source scripts/update/print-update-info $_version
		echo
	} 	

}
