plugins {
  id "nebula.ospackage" version "5.0.4"
}

Properties props = new Properties()
props.load(new FileInputStream(rootDir.path + '/freeplane/src/viewer/resources/version.properties'))

allprojects {

//buildscript {
//  repositories {
//    mavenCentral()
//  }
//  dependencies {
//    classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:4.4.0'
//  }
//}

    // in a multi-project setup, all projects must have the same version number!
    // the real (specific) version number is in freeplane/viewer-resources/version.properties!
	ext.majorVersion = props['freeplane_version']
	ext.versionStatus = props['freeplane_version_status']
	ext.minorVersion = System.getProperty('minor', '')
	ext.distVersion = "$majorVersion${versionStatus.empty?'':'-'+versionStatus}${minorVersion.empty?'':'-pre' + minorVersion}"
    version = ext.majorVersion

    // WARNING: this is removed with "gradle clean"!!
    ext.globalBin = rootDir.path + '/BIN'

    repositories {
		mavenCentral()
		maven { url "http://www.knopflerfish.org/releases/6.1.0/maven2" }
		maven { url "${project.gradle.gradleUserHomeDir}/local-artifacts" }
		maven { url "http://dl.bintray.com/freeplane/freeplane" }
		maven { url "https://repo.spring.io/plugins-release/"}

        // this is necessary to grab both binary and source jars
        // for local (git) dependencies
        flatDir name: 'localGitDepsRepository',
                dirs: [rootDir.path + "/freeplane/lib",
                       rootDir.path + "/freeplane_plugin_jsyntaxpane/lib"]
    }

}

// this is used for (linux) packages, where the dependencies
// live on the file system (/usr/share/java/*.jar on Debian):
def externalizeJar(File jar) {
    // do not externalize, jars are copied over to /BUILD
    // in development workflow!
    return "lib/${jar.name}"
}

// this is overridden in linux packages where this might be named
// knopflerfish-framework.jar
def isKnopflerfishJar(fileName) {
    return fileName.startsWith('framework-') &&
           fileName.endsWith('.jar');
}

def filterAndExternalizePluginDependencies(runtime_files) {
    return runtime_files.findAll {
        File file -> !isKnopflerfishJar(file.name)
    }.findAll {
        File file ->
        file.name != "freeplane-${project.version}.jar" &&
        !(file.name.startsWith('freeplane_plugin_') &&
          file.name.endsWith('-' + project.version + '.jar'))
    }.collect {
        File file -> externalizeJar(file)
    }
}

subprojects {
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'idea'

	targetCompatibility='1.8'
	sourceCompatibility='1.8'


    tasks.withType(JavaCompile) {
      options.encoding = "UTF-8"
    }
    javadoc {
      options.encoding = "UTF-8"
      options.docEncoding = "UTF-8"
      options.charSet = "UTF-8"
      enabled = false
      failOnError = false
    }

    repositories {
       maven  {
        url "http://repo1.maven.org/maven2"
       }
    }

    configurations {
        lib
        compile.extendsFrom(lib)
    }
    
    dependencies {
		testCompile 'junit:junit:4.12',
				'org.hamcrest:hamcrest-all:1.3',
				'org.mockito:mockito-core:2.21.0',
			 	'org.assertj:assertj-core:2.6.0'
    }

    task copyEclipseSettings(type: Copy) {
        from(rootDir.path + "/freeplane_framework/eclipse/settings-templates/") {
            include("*.prefs")
        }
        into(project.file(".settings/"))
    }
    eclipseJdt.dependsOn copyEclipseSettings

    task cleanEclipseSettings(type: Delete) {
        delete(project.file(".settings"))
    }
    cleanEclipseJdt.dependsOn cleanEclipseSettings

	if (project.hasProperty('TestLoggingFull')) {
		test {
			testLogging {
				events "failed"
				exceptionFormat "full"
			}
		}
	}
}

// OSGi projects (/plugin/, freeplane) need this for compilation (e.g. resolve Bundle),
// and freeplane_framework needs to copy it to BUILD/framework.jar
configure(subprojects.findAll {it.name =~ /plugin/ || it.name =~ /^freeplane$/ || it.name =~ /^freeplane_framework$/}){
    dependencies {
        compile group: 'org.knopflerfish.kf6', name:'framework', version: '8.0.4'
    }
}

// common configuration for all OSGi projects...
configure(subprojects.findAll {it.name =~ /plugin/ || it.name =~ /^freeplane$/ }) {
    //apply plugin: 'biz.aQute.bnd.builder'
    apply plugin: 'osgi'
    ext.bundleImports = 'nothing.*'
    ext.bundleExports = ''
    if (project.name.equals("freeplane"))
       ext.pluginid = 'org.freeplane.core'

       

   afterEvaluate {

     if (it.name =~ /plugin/) {
       ext.bundleDeps = filterAndExternalizePluginDependencies(configurations.lib.files)
       bundleDeps.add(0, "lib/plugin-" + project.version + '.jar')
     }

     jar {

       manifest {

        name = pluginid
        symbolicName = pluginid

        instruction 'Bundle-ClassPath', '., ' + bundleDeps.join(', ')

        instruction 'Bundle-Vendor', 'Freeplane Project'
        instruction 'Bundle-Activator', bundleActivator
        instruction 'Bundle-RequiredExecutionEnvironment', 'JavaSE-1.8'
        instruction 'Import-Package', bundleImports.replaceAll("\\s+", "")
        instruction 'Export-Package', bundleExports.replaceAll("\\s+", "")
        if (it.name =~ /plugin/) {
            instruction 'Require-Bundle', 'org.freeplane.core'
        }

       }
        //bnd('Bundle-Name': pluginid,
        // 'Export-Package': bundleExports.replaceAll("\\s+", ""),
        // 'Bundle-Vendor': 'Freeplane Project',
        // 'Import-Package': bundleImports.replaceAll("\\s+", ""),
        // 'Bundle-Activator': bundleActivator,
        // 'Bundle-RequiredExecutionEnvironment': 'JavaSE-1.8',
        // 'Bundle-ClassPath': '., ' + bundleDeps.join(', ')
        // only in plugins: 'Require-Bundle', 'org.freeplane.core'
        //)

   }
   }

}

// common configuration for all plugins...
configure(subprojects.findAll {it.name =~ /plugin/}) {

   ext.pluginid = project.name.replace("freeplane_plugin_", "org.freeplane.plugin.")
   ext.bundleActivator = pluginid + ".Activator"

    task copyOSGiJars(type: Copy) {
        from ("$buildDir/libs") {
            include("*.jar")
            exclude('freeplane-' + project.version + '.jar')
            exclude('freeplane_plugin_*-' + project.version + '.jar')
        }
        from (configurations.lib) {
            include("*.jar")
        }
        from ('lib') {
            include("*.jar")
            exclude('*-sources.jar')
        }
        into(globalBin + '/plugins/' + pluginid + '/lib/')
    }

    task copyOSGiManifest(type: Copy) {
        from ("$buildDir/tmp/jar/") {
            include("MANIFEST.MF")
        }
        into(globalBin + '/plugins/' + pluginid + '/META-INF/')
    }

    task copyOSGiConfig(type: Copy) {
        from ("OSGI-INF")
        into(globalBin + '/plugins/' + pluginid + '/OSGI-INF/')
    }

    build.dependsOn copyOSGiJars
    build.dependsOn copyOSGiManifest
    build.dependsOn copyOSGiConfig

    // create a separate non-OSGi(!) jar for each plugin!
    task pluginJar(type: Jar) {
         baseName = 'plugin'
         dependsOn classes

         from (sourceSets.main.output) {
             include("**")
         }
         // unfortunately some resource (xml,properties) files (e.g. preferences.xml in latex plugin)
         // are in src/main/java...
         from (sourceSets.main.allSource) {
             include("**/*.xml")
             include("**/*.properties")
         }
         includeEmptyDirs = false

         // use a non-OSGi manifest (this jar is referenced from an OSGi bundle)!
         project.manifest { }
    }

    // jar must execute after pluginJar so that the OSGi manifest can still be
    // picked up from build/tmp/jar (and isn't overwritten by plugin*.jar's non-OSGi
    // manifest!)
    jar.dependsOn pluginJar
}

apply plugin: 'base' // necessary to get the global 'clean' task

// remove globalBin/**
task cleanBUILD(type: Delete) {
    delete globalBin
}
clean.dependsOn(cleanBUILD)

task check_translation {
    dependsOn ':JOrtho_0.4_freeplane:check_translation'
    dependsOn ':freeplane:check_translation'
}
task format_translation {
    dependsOn ':JOrtho_0.4_freeplane:format_translation'
    dependsOn ':freeplane:format_translation'
}

apply from: './dist.gradle'
apply from: './jdt-config.gradle'
