@Library('SHS.Platforms') _
node {
	properties([
		parameters(
			[booleanParam(name: 'RPi_make_sysroot', defaultValue: false, description: 'Rebuild raspbian sysroot, or only execute Dockerfile'), booleanParam(name: 'no_docker_cache', defaultValue: false, description: 'Build dockers without use docker cache')]
		)
	])
	def jobs = 4
	if (env.JOBS_COUNT) {
		jobs = "${env.JOBS_COUNT}"
	}
	def jobs_qt = 2
	if (env.JOBS_QT_COUNT) {
		jobs_qt = "${env.JOBS_QT_COUNT}"
	}
	def docker_cache_arg = ""
	if (Boolean.valueOf(no_docker_cache)) {
	docker_cache_arg = "--no-cache"
	}
	stage("Download SRC") {
		 checkout scm
	}
	
	def pl = new org.SHS.Platforms(this)
	pl.get()

	stage("Debian-base") {
		docker.build("${env.DOCKER_PREFIX}/debian-base", "./debian-base ${docker_cache_arg}")
	}
	
	if (pl.root().platforms.OSX.enabled) {
		stage("OSXcross") {
			docker.build("${env.DOCKER_PREFIX}/osxcross", "./osxcross ${docker_cache_arg} --build-arg XCODE_XIP=172.17.0.1/Xcode_10.3.xip")
		}
	}
	
	if (pl.root().platforms["Raspbian 10"].enabled) {
		stage("Raspbian SYSROOT") {
			if (Boolean.valueOf(RPi_make_sysroot)) {
				echo 'Building Raspbian sysroot ...'
				sh 'cd ./pi && bash ./umount_sysroot.sh && bash ./mount_sysroot.sh'
				sh 'mkdir -p $HOME/rpi_image'
				docker.image('${env.DOCKER_PREFIX}/debian-base').inside('-u root:root -v $HOME/rpi_image:/soft/rpi_image') {
					sh 'cd ./pi && bash make_sysroot.sh'
				}
				sh 'cd ./pi && bash ./umount_sysroot.sh'
			}
			sh 'cp -vf $HOME/rpi_image/sysroot.tar.bz2 ./pi/'
		}
	}

	pl.forEach ({ dist ->
			def args = "./${dist.docker.directory} ${docker_cache_arg}"
			for (arg in dist.docker.build_options) {
				args += " --build-arg ${arg.key}=\"${arg.value}\""
			}
			args += " --build-arg JOBS_COUNT=${jobs}"
			args += " --build-arg JOBS_QT_COUNT=${jobs_qt}"
			def dprefix = "${env.DOCKER_PREFIX}"
			if (dprefix != "" && !dprefix.endsWith("/")) dprefix += "/"
			args += " --build-arg DOCKER_PREFIX=${dprefix}"
			//print "${env.DOCKER_PREFIX}/${dist.docker.image_basename} -> ${args}"
			docker.build("${env.DOCKER_PREFIX}/${dist.docker.image_basename}", args)
		},
		ondemand: true
	)
	
	stage("docker prune") {
		sh 'docker system prune -f'
	}
}
