import org.apache.tools.ant.taskdefs.condition.Os

static String getDeployCommand(Project project) {
    def payaraMicroJar = project.configurations.payaraMicro.asPath
    "java -jar ${payaraMicroJar} --autoBindHttp --clusterName app --deploy ${project.war.archivePath}"
}

static String getLibsDir(Project project) {
//    "${project.buildDir}/libs"
    "${project.buildDir}"
}

static String getOutputUberJar(Project project) {
    "${getLibsDir(project)}/${project.name}-${project.version}-microbundle.jar"
}

static String[] getCommand(String... suffix) {
    String[] prefix = Os.isFamily(Os.FAMILY_WINDOWS) ? ['cmd', '/c'] : ['sh', '-c']
    prefix + suffix
}

apply plugin: 'base'
defaultTasks('clean', 'bundle')

apply plugin: 'war'
// workaround for context-root: '/'
war.archiveName = 'ROOT.war'
// ear { archiveName = "${project.name}.ear" }

configurations { payaraMicro }
// 5.183 is broken, Uber Jar is fixed with 5.184
dependencies { payaraMicro 'fish.payara.extras:payara-micro:5.182' }

task bundle(type: Exec) {
    description('build payara uber jar from war')
    shouldRunAfter('clean', 'war')
    dependsOn('war')
    commandLine getCommand("${getDeployCommand(project)} --outputUberJar ${getOutputUberJar(project)}")
}

task start(type: Exec) {
    description("java -jar ${getOutputUberJar(project)}")
    shouldRunAfter('clean', 'war', 'bundle')
    dependsOn('bundle')
    commandLine getCommand("java -jar ${getOutputUberJar(project)}")
}

assemble.dependsOn(bundle)
