/******************************************************************************
 * Copyright (c) 2016 TypeFox and others.
 * 
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0,
 * or the Eclipse Distribution License v. 1.0 which is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 * 
 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
 ******************************************************************************/
apply plugin: "biz.aQute.bnd.builder"

def baseVersion = project.version
if (baseVersion.endsWith('-SNAPSHOT'))
	baseVersion = baseVersion.substring(0, baseVersion.length() - 9)
else if (baseVersion.split('\\.').length == 4)
	baseVersion = baseVersion.substring(0, baseVersion.lastIndexOf('.'))
def qualifiedVersion = baseVersion + '.v' + buildTime

jar.bundle.bnd (
	'Bundle-Version': qualifiedVersion,
	'Bundle-Vendor': 'Eclipse LSP4J',
	'Bundle-RequiredExecutionEnvironment': 'JavaSE-11',
	"-exportcontents": "org.eclipse.lsp4j.*",
	"-savemanifest": "build/tmp/bnd/MANIFEST.MF",
)

//------------------------------------------------------
// Generate a manifest for the source bundle

def sourcesManifestFile = "$buildDir/tmp/sourcesJar/MANIFEST.MF"

task genSourcesManifest {
	outputs.file(sourcesManifestFile)
	doLast {
		def f = new File(sourcesManifestFile)
		f.parentFile.mkdirs()
		def writer = new PrintWriter(f)
		writer.println("Manifest-Version: 1.0")
		writer.println("Bundle-ManifestVersion: 2")
		writer.println("Bundle-SymbolicName: ${project.name}.source")
		writer.println("Bundle-Version: ${qualifiedVersion}")
		if (project.hasProperty('title'))
			writer.println("Bundle-Name: ${project.title} Sources")
		else
			writer.println("Bundle-Name: Sources")
		writer.println("Bundle-Vendor: Eclipse LSP4J")
		writer.println("Eclipse-SourceBundle: ${project.name};version=\"${qualifiedVersion}\"")
		writer.close()
	}
}

sourcesJar {
	dependsOn genSourcesManifest
	inputs.file(sourcesManifestFile)
	manifest {
		from sourcesManifestFile
	}
}

//------------------------------------------------------
// Task to copy the generated manifest into the project

task eclipseManifest(type: Copy) {
	dependsOn(jar)
    from "$buildDir/tmp/bnd/MANIFEST.MF"
    into 'META-INF'
}

tasks['eclipse'].dependsOn(eclipseManifest)
