import static org.opendatakit.aggregate.gradle.Util.setPropertiesValue
import static org.opendatakit.aggregate.gradle.Util.getVersionName

String buildTarget = "${buildDir}/docker".toString()
String classRoot = "${buildTarget}/webapps/ROOT/WEB-INF/classes".toString()

task dockerClean() {
  delete "${buildTarget}"
}

task dockerPrepare(dependsOn: [dockerClean], type: Copy) {
  into "${buildTarget}"
  from fileTree(dir: 'docker')

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

  doLast {

    file("${classRoot}/jdbc.properties.example").renameTo(file("${classRoot}/jdbc.properties"))
    file("${classRoot}/security.properties.example").renameTo(file("${classRoot}/security.properties"))
    file("${classRoot}/odk-settings.xml.example").renameTo(file("${classRoot}/odk-settings.xml"))

    setPropertiesValue("${classRoot}/jdbc.properties", "jdbc.url", "jdbc:postgresql://127.0.0.1/aggregate?autoDeserialize=true")
    setPropertiesValue("${classRoot}/jdbc.properties", "jdbc.username", "aggregate")
    setPropertiesValue("${classRoot}/jdbc.properties", "jdbc.password", "aggregate")
    setPropertiesValue("${classRoot}/jdbc.properties", "jdbc.schema", "aggregate")
    setPropertiesValue("${classRoot}/security.properties", "security.server.realm.realmString", "ODK Aggregate")
    setPropertiesValue("${classRoot}/security.properties", "security.server.channelType", "ANY_CHANNEL")
    setPropertiesValue("${classRoot}/security.properties", "security.server.superUserUsername", "administrator")
    setPropertiesValue("${classRoot}/security.properties", "security.server.superUser", "")
    setPropertiesValue("${classRoot}/security.properties", "security.server.port", "8080")
    setPropertiesValue("${classRoot}/security.properties", "security.server.securePort", "8443")
    setPropertiesValue("${classRoot}/security.properties", "security.server.deviceAuthentication", "digest")
    setPropertiesValue("${classRoot}/security.properties", "security.server.hostname", "")
    setPropertiesValue("${classRoot}/security.properties", "security.server.secureChannelType", "ANY_CHANNEL")
    setPropertiesValue("${classRoot}/security.properties", "security.help.about", "auto-generated on 1970-01-01T00:00:00+0000 for ODK Aggregate")
  }
}

task dockerBuild(dependsOn: [build, dockerPrepare], type: Exec) {
  workingDir "${buildTarget}"

  commandLine 'docker', 'build', '-t', "aggregate:${getVersionName()}".toString(), '.'

  doLast {
    println ""
    println "Your Aggregate Docker image is ready to run."
    println "Please, refer to https://github.com/getodk/aggregate/tree/master/docs/build-and-run-a-docker-image.md for instructions."
  }
}
