/*
 * WARNING
 *
 * This file should not be edited.
 *
 * GNU LIBRARY GENERAL PUBLIC LICENSE
 * Version 2, June 1991
 *
 * Bundle repository indexing tasks.
 */


/*
 * Create repository indexes
 *
 * Syntax:
 * ext.indexDirectories = \
 *   '<root directory>;<name>;<name of fileTree property>, ...'
 *
 *  root directory           : mandatory.
 *  name                     : optional. if not specified then the basename of
 *                             the root directory is used.
 *  name of fileTree variable: optional. if not specified then all *.jar files
 *                             below the root directory will be indexed
 */
if (!hasProperty('indexDirectories'    )) ext.indexDirectories     = ''

if (!hasProperty('indexOBRUncompressed')) ext.indexOBRUncompressed = false
if (!hasProperty('indexOBRCompressed'  )) ext.indexOBRCompressed   = false
if (!hasProperty('indexR5Uncompressed' )) ext.indexR5Uncompressed  = false
if (!hasProperty('indexR5Compressed'   )) ext.indexR5Compressed    = true


ext.indexBindexJar     = "${rootDir}/${bnd_cnf}/gradle/gradle/dependencies/org.osgi.impl.bundle.bindex/org.osgi.impl.bundle.bindex-3.0.0.jar"
ext.indexBindexMain    = 'org.osgi.impl.bundle.bindex.cli.Index'
ext.indexRepoindexJar  = "${rootDir}/${bnd_cnf}/gradle/dependencies/org.osgi.impl.bundle.repoindex.cli/org.osgi.impl.bundle.repoindex.cli-3.4.0.jar"
ext.indexRepoindexMain = 'org.osgi.impl.bundle.bindex.cli.Index'


void createIndexes(boolean r5, boolean uncompressed, boolean compressed) {
  def indexerClasspath
  def indexerMain
  if (!r5) {
    indexerClasspath = rootProject.files(rootProject.indexBindexJar )
    indexerMain      =                   rootProject.indexBindexMain
  } else {
    indexerClasspath = rootProject.files(rootProject.indexRepoindexJar )
    indexerMain      =                   rootProject.indexRepoindexMain
  }

  indexDirectories.trim().split('\\s*,\\s*').each { indexDirectory ->
    def parts        = indexDirectory.split('\\s*;\\s*')

    if (parts.length > 3) {
      throw new GradleException("Too many parts to the indexing configuration (${indexDirectory})")
    }

    if (parts.length > 1) {
      if (parts[0].empty) {
        throw new GradleException("Can't have an empty index directory (${indexDirectory})")
      }
      indexDirectory = parts[0]
    }
    def indexDirectoryFile = file(indexDirectory)

    def repoName     = indexDirectoryFile.name
    if (parts.length > 1 && !parts[1].empty) {
      repoName       = parts[1]
    }

    indexDirectoryFile.mkdirs()

    def bundlesToIndex
    if (parts.length > 2) {
      def treeProperty = parts[2]
      bundlesToIndex = properties.get(treeProperty)
      if (bundlesToIndex == null) {
        throw new GradleException("Property ${treeProperty} not found")
      }
      if (!(bundlesToIndex instanceof FileTree)) {
        throw new GradleException("Property ${treeProperty} is not an instance of FileTree")
      }
    } else {
      bundlesToIndex = fileTree(indexDirectoryFile).include("**/*.jar")
    }

    def uncompressedIndexFile
    def compressedIndexFile
    if (!r5) {
      uncompressedIndexFile = file("${indexDirectory}/repository.xml")
      compressedIndexFile   = file("${indexDirectory}/repository.zip")
    } else {
      uncompressedIndexFile = file("${indexDirectory}/index.xml")
      compressedIndexFile   = file("${indexDirectory}/index.xml.gz")
    }

    if (uncompressedIndexFile.exists()) {
      uncompressedIndexFile.delete()
    }
    if (compressedIndexFile.exists()) {
      compressedIndexFile.delete()
    }

    def indexes = [[false, uncompressed], [true, compressed]]
    indexes.each { indexesEntry ->
      def compress      = indexesEntry[0]
      def generateIndex = indexesEntry[1]
      if (generateIndex) {
        def indexFile
        if (!compress) {
          indexFile     = uncompressedIndexFile
        } else {
          indexFile     = compressedIndexFile
        }

        def indexArgs   = []
        if (!r5) {
          indexArgs    += ['-r', indexFile,
                           '-d', indexDirectoryFile.toURI(),
                           '-n', repoName]
        } else {
          if (!compress) {
            indexArgs  += ['--pretty']
          }
          indexArgs    += ['-r', indexFile,
                           '-d', indexDirectoryFile,
                           '-n', repoName]
        }

        if (!bundlesToIndex.empty) {
          bundlesToIndex.each {
            indexArgs  += relativePath(it)
          }
        }

        def result = javaexec {
          classpath     = indexerClasspath
          main          = indexerMain
          args          = indexArgs
        }
        if (result.exitValue != 0) {
          String msg = String.format("Could not create %s %s index in directory ${indexDirectory}",
            compress ? 'a compressed' : 'an uncompressed',
            r5 ? 'R5' : 'OBR')
          throw new GradleException(msg)
        }
      }
    }
  }
}


task index {
  description 'Generate OBR and R5 repository indexes (set the indexDirectories property)'
  group 'release'
  enabled !indexDirectories.isEmpty() &&
            (   indexOBRUncompressed
             || indexOBRCompressed
             || indexR5Uncompressed
             || indexR5Compressed)

  doLast {
    if (indexOBRUncompressed || indexOBRCompressed) {
      createIndexes(false, indexOBRUncompressed, indexOBRCompressed)
    }
    if (indexR5Uncompressed  || indexR5Compressed ) {
      createIndexes(true , indexR5Uncompressed , indexR5Compressed )
    }
  }
}
