import static org.opendatakit.aggregate.gradle.Util.*

task installerClean() {
  delete 'build/installer'
  delete 'build/installers'
}

task installerBuild(dependsOn: [installerClean], type: Copy) {
  into "${buildDir}/installer"
  from fileTree(dir: 'installer/project')

  into('files') {
    from "${buildDir}/libs/${archivesBaseName}-${version}.war"
  }

  into('files/conf/common') {
    from files(
        'src/main/resources/logging.properties',
        'src/main/resources/odk-common-security-settings.xml',
        'src/main/resources/odk-security-settings.xml',
        'src/main/resources/security.properties'
    )
  }

  doLast {
    setXmlValue("${buildDir}/installer/buildWar.xml", "version", version)
    file("${buildDir}/installer/files/${archivesBaseName}-${version}.war").renameTo(file("build/installer/files/ODKAggregate.war"))

    if (installBuilderHome != null) {
      run("mkdir", "${buildDir}/installers")
      setXmlValue("${buildDir}/installer/buildWar.xml", "outputDirectory", "${buildDir}/installers")

      [["linux-x64", "Linux-x64.run"],
       ["linux", "Linux.run"],
       ["windows", "Windows.exe"],
       ["osx", "macOS.app"]
      ].forEach({ pair ->
        setXmlValue("${buildDir}/installer/buildWar.xml", "installerFilename", "ODK-Aggregate-${version}-${pair[1]}")
        run("${installBuilderHome}/bin/builder", "build", "${buildDir}/installer/buildWar.xml", "${pair[0]}")
        runInWorkingDir("${buildDir}/installers", "zip", "-r", "ODK-Aggregate-${version}-${pair[1]}.zip", "ODK-Aggregate-${version}-${pair[1]}")
        runInWorkingDir("${buildDir}/installers", "rm", "-r", "ODK-Aggregate-${version}-${pair[1]}")
      })
    }
  }
}
