buildscript {
	repositories {
		mavenCentral()
		maven {
			url "https://plugins.gradle.org/m2/"
		}
	}
}

plugins {
	id "java"
	id "scala"
	id "signing"
	id "maven-publish"
	id "com.bmuschko.docker-remote-api" version "4.0.5"
	id "com.diffplug.gradle.spotless" version "3.18.0"
	id "io.codearte.nexus-staging" version "0.20.0"
	id "de.marcphilipp.nexus-publish" version "0.2.0"
}

repositories {
	mavenCentral()
	jcenter()
}

description = "Mongoose is a high-load storage performance testing tool"
group = "com.github.emc-mongoose"
sourceCompatibility = 11
targetCompatibility = 11
version = "4.3.16"


ext {
	installResourcesFileName = "install_resources.txt"
	jarFileName = rootProject.name
	javaHome = System.properties["java.home"]
	jreOutputDir = "${rootProject.buildDir}${File.separator}jre"
	rootPkg = "com.emc.mongoose"
	modulesDepsFilePath = "${rootProject.buildDir}${File.separator}modules.deps"
}

configurations {
	extension {
		extendsFrom(compileOnly)
	}
}

dependencies {
	compile(
		"${group}:mongoose-base:${baseVersion}",
	)
	extension(
		"${group}:mongoose-load-step-pipeline:${loadStepPipelineVersion}",
		"${group}:mongoose-load-step-weighted:${loadStepWeightedVersion}",
		"${group}:mongoose-storage-driver-coop:${storageDriverCoopVersion}",
		"${group}:mongoose-storage-driver-netty:${storageDriverNettyVersion}",
		"${group}:mongoose-storage-driver-nio:${storageDriverNioVersion}",
		"${group}:mongoose-storage-driver-http:${storageDriverHttpVersion}",
		"${group}:mongoose-storage-driver-fs:${storageDriverFsVersion}",
		"${group}:mongoose-storage-driver-atmos:${storageDriverAtmosVersion}",
		"${group}:mongoose-storage-driver-s3:${storageDriverS3Version}",
		"${group}:mongoose-storage-driver-swift:${storageDriverSwiftVersion}",
	)
}

// travis deploy stage runs "./gradlew check" again which is unnecessary
check.dependsOn -= test

javadoc {
	classpath += configurations.compile
}

signing {
	required {
		gradle.taskGraph.hasTask("uploadArchives")
	}
	sign configurations.archives
}

wrapper {
	gradleVersion = "4.10.3"
}

task mergeInstallResourcesFile {
	doLast {
		def dstFile = new File("${project.buildDir}${File.separator}${installResourcesFileName}")
		if(!dstFile.parentFile.exists()) {
			dstFile.parentFile.mkdirs()
		}
		configurations.compile.copyRecursive().collect {
			zipTree(it).filter {
				it.toString().endsWith(installResourcesFileName)
			} forEach {
				it.readLines().forEach {
					dstFile << it
					dstFile << System.lineSeparator()
				}
			}
		}
		configurations.extension.copyRecursive().collect {
			dstFile << "ext/${it.name}"
			dstFile << System.lineSeparator()
		}
	}
}

jar.dependsOn += mergeInstallResourcesFile

jar {
	baseName = rootProject.name
	duplicatesStrategy = DuplicatesStrategy.EXCLUDE
	excludes = [
		"**/*.css",
		"**/*.html",
		"META-INF/*.DSA",
		"META-INF/*.LIST",
		"META-INF/*.RSA",
		"META-INF/*.SF",
		"module-info.class",
	]
	manifest {
		attributes(
			"Automatic-Module-Name": rootPkg,
			"Implementation-Title": rootProject.name,
			"Implementation-Version": version,
			"Main-Class": "${rootPkg}.base.Main",
			"Multi-Release": "true",
		)
	}
	from "${project.buildDir}${File.separator}${installResourcesFileName}"
	from configurations.compile.copyRecursive().collect {
		zipTree(it)
	}
	into("${File.separator}ext") {
		from configurations.extension.copyRecursive().collect {
			it
		}
	}
}

task sourcesJar(type: Jar, dependsOn: classes) {
	classifier = "sources"
	from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
	classifier = "javadoc"
	from javadoc.destinationDir
}

// Maven Central deployment ////////////////////////////////////////////////////////////////////////////////////////////

artifacts {
	archives jar
	archives sourcesJar
	archives javadocJar
}

nexusStaging {
	packageGroup = project.group
	username = project.hasProperty("ossrhUsername") ? project.property("ossrhUsername") : null
	password = project.hasProperty("ossrhPassword") ? project.property("ossrhPassword") : null
	numberOfRetries = 100
	delayBetweenRetriesInMillis = 10000
}

publishing {
	publications {
		mavenJava(MavenPublication) {
			artifactId = project.name
			groupId = project.group
			artifact jar
			artifact javadocJar
			artifact sourcesJar
			pom {
				name = project.name
				description = project.description
				url = "https://github.com/emc-mongoose/mongoose"
				scm {
					connection = "https://github.com/emc-mongoose/mongoose"
					developerConnection = "https://github.com/emc-mongoose/mongoose.git"
					url = "https://github.com/emc-mongoose/mongoose.git"
				}
				licenses {
					license {
						name = "The MIT License (MIT)"
						url = "https://github.com/emc-mongoose/mongoose/LICENSE"
					}
				}
				developers {
					developer {
						id = "akurilov"
						name = "Andrey Kurilov"
						email = "akurilov123@gmail.com"
					}
				}
			}
		}
	}
	repositories {
		maven {
			url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
			credentials {
				username = project.hasProperty("ossrhUsername") ? project.property("ossrhUsername") : null
				password = project.hasProperty("ossrhPassword") ? project.property("ossrhPassword") : null
			}
		}
	}
}

signing {
	sign publishing.publications
}

task releaseToMavenCentral {
	dependsOn += publishToNexus
	dependsOn += closeAndReleaseRepository
}

// Docker tasks ////////////////////////////////////////////////////////////////////////////////////////////////////////

import com.bmuschko.gradle.docker.tasks.image.*
import com.bmuschko.gradle.docker.tasks.container.*

task dockerBuildImage(type: DockerBuildImage) {
	inputDir = project.projectDir
	buildArgs = [
		"BASE_VERSION": baseVersion,
		"LOAD_STEP_PIPELINE_VERSION": loadStepPipelineVersion,
		"LOAD_STEP_WEIGHTED_VERSION": loadStepWeightedVersion,
		"STORAGE_DRIVER_COOP_VERSION": storageDriverCoopVersion,
		"STORAGE_DRIVER_NETTY_VERSION": storageDriverNettyVersion,
		"STORAGE_DRIVER_NIO_VERSION": storageDriverNioVersion,
		"STORAGE_DRIVER_FS_VERSION": storageDriverFsVersion,
		"STORAGE_DRIVER_HTTP_VERSION": storageDriverHttpVersion,
		"STORAGE_DRIVER_ATMOS_VERSION": storageDriverAtmosVersion,
		"STORAGE_DRIVER_S3_VERSION": storageDriverS3Version,
		"STORAGE_DRIVER_SWIFT_VERSION": storageDriverSwiftVersion,
	]
	dockerFile = project.file("ci${File.separator}docker${File.separator}Dockerfile")
	imageId = "emcmongoose/mongoose".toString()
	tags = [
		"emcmongoose/mongoose:${version}",
		"emcmongoose/mongoose:testing",
	]
}

task dockerPushProductionImage(type: DockerPushImage) {
	imageName = "emcmongoose/mongoose".toString()
	tag = "emcmongoose/mongoose:${version}".toString()
}

task dockerPushTestingImage(type: DockerPushImage, dependsOn: dockerBuildImage) {
	imageName = "emcmongoose/mongoose".toString()
	tag = "emcmongoose/mongoose:testing".toString()
}

// Robot Framework /////////////////////////////////////////////////////////////////////////////////////////////////////

task dockerBuildImageRobotest(type: DockerBuildImage) {
	inputDir = rootProject.projectDir
	dockerFile = project.file("ci${File.separator}docker${File.separator}Dockerfile.robotest")
	imageId = "emcmongoose/mongoose-robotest"
	tags = [
		"emcmongoose/mongoose-robotest:${version}",
	]
}

task dockerCreateContainerRobotest(type: DockerCreateContainer, dependsOn: [dockerBuildImage, dockerBuildImageRobotest]) {
	attachStderr = true
	attachStdout = true
	autoRemove = true
	binds = [
		"${rootProject.buildDir}": "/root/mongoose/build",
		"/var/run/docker.sock": "/var/run/docker.sock",
	]
	envVars = [
		"HOST_WORKING_DIR": rootProject.projectDir.absolutePath,
		"VERSION": version,
		"SERVICE_HOST": "localhost",
		"SUITE": System.getenv("SUITE"),
		"TEST": System.getenv("TEST"),
	]
	imageId = dockerBuildImageRobotest.getImageId()
	network = "host"
	tty = true
	doLast {
		println "Created the container for the ${System.env.SUITE}.${System.env.TEST} test"
	}
}

task dockerStartContainerRobotest(type: DockerStartContainer, dependsOn: dockerCreateContainerRobotest) {
	targetContainerId dockerCreateContainerRobotest.getContainerId()
}

task robotest(type: DockerWaitContainer, dependsOn: dockerStartContainerRobotest) {
	targetContainerId dockerCreateContainerRobotest.getContainerId()
	timeout = 600 // 10 min w/o output -> fail on Travis CI
	doLast {
		if(0 != exitCode) {
			throw new GradleException("Some robotests FAILED")
		} else {
			println "Robotests PASSED"
		}
	}
}
