import com.epam.deltix.gradle.tasks.installer.BuildTimebaseInstallerTask

plugins {
    id 'com.ullink.msbuild' version '3.12'
}

apply from: "$rootDir/distribution/scripts.gradle"

project.description = "Timebase Installer Packager"

configurations {
    izpack.extendsFrom compile
}

apply plugin: 'java-library'
apply plugin: 'de.undercouch.download'

//todo: with source compatibility 11 installer won't work
sourceCompatibility = 8
targetCompatibility = 8

group = 'org.finos.timebase-ce'

if (!project.hasProperty('instDir'))
    ext.instDir = project.file('build')

if (!project.hasProperty('instVersion'))
    ext.instVersion = new java.text.SimpleDateFormat('yyyyMMdd').format(new java.util.Date())

if (!project.hasProperty('qoVersion'))
    ext.qoVersion = 'UNDEFINED'

def customPacksArray = []
if (project.hasProperty('customPacks')) {
    customPacksArray = project.properties['customPacks'].split(';')
}

repositories {
    mavenCentral()
}

dependencies {
    izpack 'org.codehaus.izpack:izpack-compiler:5.2.3'
    izpack 'org.codehaus.izpack:izpack-ant:5.2.3'
    izpack 'org.apache.tika:tika-core:2.9.2'
    izpack 'org.apache.tika:tika-parsers:1.28.5'

    izpack 'com.fasterxml.jackson.core:jackson-databind:2.13.5'
    izpack 'com.fasterxml.jackson.core:jackson-core:2.13.5'
    izpack 'com.fasterxml.jackson.core:jackson-annotations:2.13.5'

    izpack 'org.apache.commons:commons-compress:1.19'
    izpack 'commons-io:commons-io:2.7'

    izpack 'org.apache.pdfbox:pdfbox:3.0.3'
    izpack 'org.apache.cxf:cxf-rt-transports-http:3.5.3'

    izpack 'org.bouncycastle:bcmail-jdk15on:1.70'
    izpack 'org.bouncycastle:bcpkix-jdk15on:1.70'
    izpack 'org.bouncycastle:bcprov-ext-jdk15on:1.70'
}

compileJava {
    classpath = configurations.izpack
}

javadoc {
    classpath = configurations.izpack
}

def generatedDir = file('build/generated')

clean.doLast {
    generatedDir.deleteDir()
}

// Timebase installer
['windows', 'linux'].each { installerPlatform ->
    task("${installerPlatform}TimebaseInstaller", type: BuildTimebaseInstallerTask) {
        description = "Creates an IzPack based Timebase installer."
        dependsOn = [':build',
                     ':java:installer:build',
                     ':generateSetQsVersionScript',
                     'generateScriptsTimebase',
                     'copyTimebaseJars',
                     'copyNativeUtils'
//                     ,'timebaseWebGateway' todo:
        ]

        platform = installerPlatform
        classpath = configurations.izpack.asPath
        jarpath = jar.outputs.files[0].absolutePath
        generatedDirectory = generatedDir
        instDirectory = instDir
        instVersion = this.instVersion
        tbVersion = version
        customPacks = [
            file("izpack/timebase/resources/$installerPlatform/tb.xml"),
//            file("izpack/timebase/resources/$installerPlatform/tbwg.xml")
        ]
    }
}

def timebaseJars = []
task copyTimebaseJars
['java:timebase:server',
 'java:timebase:client',
 'java:timebase:s3',
 'java:timebase:aerondirect',
 'java:timebase:api',
 'java:timebase:pub'
].forEach { projectName ->
    def projectJar = rootProject.project(projectName).tasks.jar.getOutputs().files.getSingleFile()
    timebaseJars.add(projectJar)
    copyTimebaseJars.dependsOn += tasks.create(projectName.replace(':', '-') + "-copyjars", Copy) {
        mustRunAfter clean
        mustRunAfter ':clean' // Root clean
        from rootProject.project(projectName).configurations.runtimeClasspath
        from projectJar
        into generatedDir.absolutePath + '/lib'
        rename 'tools.*.jar', 'tools.jar'
    }
}

def cmdDir = file(generatedDir.absolutePath + '/cmd')
def timebaseScripts = []
ext.scripts.forEach { script ->
    if (timebaseJars.any{ jar -> script[2].contains(jar) }) {
        timebaseScripts.add(script)
    }
}

task generateScriptsTimebase

timebaseScripts.each() { row ->
    def script = row[0]
    def clazz = row[1]
    def jar = row[2]
    def jvmOpts = row[3]
    def startInNew = row[4]

    generateScriptsTimebase.dependsOn += tasks.create(name: 'make-' + script + '-installer-script', type: CreateStartScripts, dependsOn: tasks.getByPath(":java:build")) {
        mainClassName = clazz
        applicationName = script

        defaultJvmOpts = jvmOpts

        outputDir = cmdDir
        classpath = jar

        unixStartScriptGenerator.template = project(":distribution").resources.text.fromFile('scripts/installer/unixStartScriptTemplate.txt')
        windowsStartScriptGenerator.template = project(":distribution").resources.text.fromFile('scripts/installer/windowsStartScriptTemplate.txt')

        doLast {
            windowsScript.text = windowsScript.text.replace('APP_HOME', 'DELTIX_HOME')
            windowsScript.text = windowsScript.text.replace('DELTIX_INSTALL_PATH/QuantServer', '${INSTALL_PATH}')
            windowsScript.text = windowsScript.text.replace('START_IN_NEW', startInNew ? 'start "" ': '')
            windowsScript.text = windowsScript.text.replaceAll('JAVACOMMAND', startInNew ? 'javaw': 'java')
            unixScript.text = unixScript.text.replace('/QuantServer', '')
            unixScript.text = unixScript.text.replace('APP_HOME', 'DELTIX_HOME')
        }
        doLast {
            file(cmdDir.absolutePath + "/${script}.bat").renameTo(cmdDir.absolutePath + "/${script}.cmd")
            file(cmdDir.absolutePath + "/${script}").renameTo(cmdDir.absolutePath + "/${script}.sh")
        }
    }
}


// Must run on Windows with Visual Studio 2019 installed
// JAVA_HOME should point to JDK

def solutionFilePath = rootProject.file('cpp/utils/Utils.sln').absolutePath

task compileCppUtilsX64(type: com.ullink.Msbuild) {
    solutionFile = solutionFilePath
    platform = 'x64'
    configuration = 'Release'
    version = '16.0'
    targets = ['Rebuild']
    //verbosity = 'detailed'
}

task compileCppUtilsX86(type: com.ullink.Msbuild) {
    solutionFile = solutionFilePath
    platform = 'x86'
    configuration = 'Release'
    version = '16.0'
    targets = ['Rebuild']
    //verbosity = 'detailed'
}

task compileCppUtils(dependsOn: [compileCppUtilsX64, compileCppUtilsX86]) {
    mustRunAfter build
}

task copyNativeUtils(type: Copy, dependsOn: [compileCppUtils] ) {
    from rootProject.file("cpp/utils/Bin")
    into rootProject.file("bin")
    include 'windscamd64.dll'
    include 'windscx86.dll'
    include 'winsvcamd64.dll'
    include 'winsvcx86.dll'
    include 'launcheramd64.exe'
    include 'launcherx86.exe'
}