
buildscript {
    ext.cubaVersion = '7.2.11'
    ext.swaggerVersion = '2.5.0'

    repositories {

        ...
        
    }
    dependencies {
        classpath "cz.habarta.typescript-generator:typescript-generator-gradle-plugin:2.0.400"
        classpath "com.haulmont.gradle:cuba-plugin:$cubaVersion"
        classpath "com.moowork.gradle:gradle-node-plugin:1.1.0"
    }
}

def modulePrefix = 'crm'

def globalModule = project(":${modulePrefix}-global" )
def coreModule = project(":${modulePrefix}-core" )
def webModule = project(":${modulePrefix}-web" )
def angularClientModule = project(":${modulePrefix}-angular-client" )
def portalModule = project(":${modulePrefix}-portal" )

def servletApi = 'javax.servlet:javax.servlet-api:3.1.0'

def testDbHost = rootProject.hasProperty('testDbHost') ? rootProject.testDbHost : 'localhost'

def kaEnv = project.hasProperty('kaEnv') ? project.kaEnv : 'dev'
def buildBranch = project.hasProperty('buildBranch') ? project.buildBranch : '-'

configurations {
    bom
}
dependencies {
    bom("com.haulmont.cuba:cuba-global:$cubaVersion")
}

apply from: 'idea.gradle'
apply(plugin: 'cuba')

cuba {
    artifact {
        group = 'com.haulmont.kacrm'
        version = '1.29.0'
        isSnapshot = true
    }
    tomcat {
        port = 8080
        shutdownPort = 8005
        debugPort = 8787
        ajpPort = 8009
    }
}

dependencies {
    appComponent("com.haulmont.cuba:cuba-global:$cubaVersion")
    appComponent("com.haulmont.reports:reports-global:$cubaVersion")

}

def postgres = 'org.postgresql:postgresql:42.2.9'

task deploy {
    doLast {
        file("$rootProject.projectDir/env/$kaEnv").eachDir { moduleConf ->
            copy {
                from moduleConf
                into "$cuba.tomcat.dir/${moduleConf.name}"
            }
        }
        def fontsDir = new File(cuba.tomcat.dir, '/conf/fonts')
        if (fontsDir.isDirectory()) {
            ant.delete(includeemptydirs: true) {
                fileset(dir: fontsDir, includes: '**/*')
            }
        }
        def reportsDir = new File(cuba.tomcat.dir, '/conf/reports')
        if (reportsDir.isDirectory()) {
            ant.delete(includeemptydirs: true) {
                fileset(dir: reportsDir, includes: '**/*')
            }
        }
        file("$rootProject.projectDir/modules/core/fonts").listFiles().each { font ->
            copy {
                from font
                into "$cuba.tomcat.dir/conf/fonts/"
            }
        }
        file("$rootProject.projectDir/modules/core/reports").listFiles().each { report ->
            copy {
                from report
                into "$cuba.tomcat.dir/conf/reports/"
            }
        }
    }
}

configure([globalModule, coreModule, webModule, portalModule]) {
    apply(plugin: 'java')
    apply(plugin: 'maven')
    apply(plugin: 'cuba')

    dependencies {
        testCompile('junit:junit:4.12')
        testCompile('org.mockito:mockito-core:2.18.3')
        // Без servletApi в тестах не работает new Cookie(). Падает при инициализации при попытке
        // найти javax.servlet.http.LocalStrings bundle.
        testCompile(servletApi)
        testCompile('org.junit.jupiter:junit-jupiter-api:5.5.2')
        testCompile('org.junit.jupiter:junit-jupiter-engine:5.5.2')
        testCompile('org.junit.vintage:junit-vintage-engine:5.5.2')
    }

    task sourceJar(type: Jar) {
        from file('src')
        classifier = 'sources'
    }

    task testJava(dependsOn: 'test') {}

    artifacts {
        archives sourceJar
    }

    test {
        systemProperty "kacrm.test.db.host", "${testDbHost}"
    }

    test {
        useJUnitPlatform()
    }
}

configure(globalModule) {
    dependencies {
        if (!JavaVersion.current().isJava8()) {
            runtime('javax.xml.bind:jaxb-api:2.3.1')
            runtime('org.glassfish.jaxb:jaxb-runtime:2.3.1')
        }
    }
    entitiesEnhancing {
        main {
            enabled = true
        }
    }

    if (project.hasProperty("teamcity")) {
        def buildId = teamcity["teamcity.build.id"]
        def gitShortHash = teamcity["build.vcs.number"].take(7)
        def buildNumber = "${buildId}-git~${gitShortHash}"

        println "buildNumber = '${buildNumber}'"

        buildInfo.properties = [
                'vcsBuildNumber': buildNumber,
                'vcsBranch': buildBranch
        ];
    } else {
        buildInfo.properties = [
                'vcsBuildNumber': 'Локальная сборка'
        ];
    }
}

configure(coreModule) {

    configurations {
        jdbc
        dbscripts
    }

    dependencies {
        compile(globalModule)
        compileOnly(servletApi)
        jdbc(postgres)
        testRuntime(postgres)
        compile group: 'net.coobird', name: 'thumbnailator', version: '0.4.13'
        compile(group: 'org.apache.poi', name: 'poi-ooxml', version: bom.getVersion('org.apache.poi', 'poi'))
        compile(group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: bom.getVersion('com.fasterxml.jackson.core', 'jackson-databind'))
    }

    task cleanConf(description: 'Cleans up conf directory', type: Delete) {
        delete "$cuba.appHome/${modulePrefix}-core/conf"
    }

    task deploy(dependsOn: [assemble, cleanConf], type: CubaDeployment) {
        appName = "${modulePrefix}-core"
        appJars(modulePrefix + '-global', modulePrefix + '-core')
    }

    task createTestDb(dependsOn: assembleDbScripts, description: 'Creates local test database', type: CubaDbCreation) {
        dbms = 'postgres'
        host = testDbHost
        ...
    }

    task createDb(dependsOn: assembleDbScripts, description: 'Creates local database', type: CubaDbCreation) {
        dbms = 'postgres'
        host = 'localhost'
        ...
    }

    task updateDb(dependsOn: assembleDbScripts, description: 'Updates local database', type: CubaDbUpdate) {
        dbms = 'postgres'
        host = 'localhost'
        ...
    }
}

configure(webModule) {
    configurations {
        webcontent
    }

    dependencies {
        compileOnly(servletApi)
        compile(globalModule)

    }
    
    task webArchive(type: Zip) {
        from file("$buildDir/web")
        from file('web')
        classifier = 'web'
    }

    artifacts {
        archives webArchive
    }

    task deployConf(type: Copy) {
        from file('src')
        include "com/haulmont/kacrm/**"
        into "$cuba.appHome/${modulePrefix}/conf"
    }

    task clearMessagesCache(type: CubaClearMessagesCache) {
        appName = "${modulePrefix}"
    }
    deployConf.dependsOn clearMessagesCache

    task cleanConf(description: 'Cleans up conf directory', type: Delete) {
        delete "$cuba.appHome/${modulePrefix}/conf"
    }

    task deploy(dependsOn: [assemble, cleanConf], type: CubaDeployment) {
        appName = "${modulePrefix}"
        appJars(modulePrefix + '-global', modulePrefix + '-web')
    }
    task buildScssThemes(type: CubaWebScssThemeCreation)
    task deployThemes(type: CubaDeployThemeTask, dependsOn: buildScssThemes)
    assemble.dependsOn buildScssThemes

    task themesJar(type: Jar) {
        from file('themes')
        classifier = 'themes'
    }

    artifacts {
        archives themesJar
    }
}


configure(angularClientModule) {
    apply(plugin: 'com.moowork.node')

    node {
        // @angular/cli requires Node.js 12.9+
        version = '12.9.1'
        download = true
    }

    task setCrmVersion(type: NpmTask) {
        args = ['run', 'setCrmVersion', '--', '--crmVersion=' + buildBranch]
    }

    // commons

    task lintCommons(type: NpmTask, dependsOn: [npmInstall] ) {
        args = ['run', 'commonsLint']
    }

    task testCommons(type: NpmTask, dependsOn: [npmInstall, ":${modulePrefix}-portal:generateTypeScript", setCrmVersion]) {
        args = ['run', 'commonsTestTeamcity']
    }

    // ka

    task assembleKa(type: NpmTask, dependsOn: [npmInstall, ":${modulePrefix}-portal:generateTypeScript", setCrmVersion]) {
        // Пример: gradlew assemble -PkaEnv=test
        def npmTask = kaEnv == 'dev' ? 'kaBuildDev' : 'kaBuildProd'
        args = ['run', npmTask, '--', '--configuration=' + kaEnv]
        inputs.property("kaEnv", kaEnv)
        inputs.property("buildBranch", buildBranch)
        inputs.dir "projects/ka"
        outputs.dir "dist/ka"
    }

    task lintKa(type: NpmTask, dependsOn: [npmInstall]) {
        args = ['run', 'kaLint']
    }

    task testKa(type: NpmTask, dependsOn: [npmInstall]) {
        args = ['run', 'kaTestTeamcity']
    }

    task deployKa(type: Copy, dependsOn: [assembleKa]) {
        from file('dist/ka')
        into "$cuba.tomcat.dir/webapps/${modulePrefix}-front"
    }

    // sa

    task assembleSa(type: NpmTask, dependsOn: [npmInstall, ":${modulePrefix}-portal:generateTypeScript", setCrmVersion]) {
        // Пример: gradlew assemble -PkaEnv=test
        def npmTask = kaEnv == 'dev' ? 'saBuildDev' : 'saBuildProd'
        args = ['run', npmTask, '--', '--configuration=' + kaEnv]
        inputs.property("kaEnv", kaEnv)
        inputs.property("buildBranch", buildBranch)
        inputs.dir "projects/sa"
        outputs.dir "dist/sa"
    }

    task lintSa(type: NpmTask, dependsOn: [npmInstall]) {
        args = ['run', 'saLint']
    }

    task testSa(type: NpmTask, dependsOn: [npmInstall]) {
        args = ['run', 'saTestTeamcity']
    }

    task deploySa(type: Copy, dependsOn: [assembleSa]) {
        from file('dist/sa')
        into "$cuba.tomcat.dir/webapps/sa-front"
    }

    // commons + ka + sa

    task assemble(dependsOn: [assembleKa, assembleSa]) {}

    task lintAngular(dependsOn: [lintCommons, lintKa, lintSa] ) {}

    task lint(dependsOn: [lintAngular]) {}

    task testAngular(dependsOn: [testCommons, testKa, testSa]) {}

    task test(dependsOn: [testAngular]) {}

    task deploy(dependsOn: [deployKa, deploySa]) {}

    task deployConf(dependsOn: [deploy]) {}

    task clean(type: Delete) {
        delete "node_modules"
    }
}

configure(portalModule) {
    dependencies {
        compileOnly(servletApi)
        compile(globalModule)

        compile "io.springfox:springfox-swagger2:$swaggerVersion"
        compile "io.springfox:springfox-swagger-ui:$swaggerVersion"
        compile "org.aspectj:aspectjweaver:1.7.4"
        compile(group: 'org.springframework', name: 'spring-websocket', version: bom.getVersion('org.springframework', 'spring-core'))
        compile(group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: bom.getVersion('com.fasterxml.jackson.core', 'jackson-databind'))
    }

    def webappName = "${modulePrefix}-portal"
    def resourcesDir = "$cuba.tomcat.dir/webapps/$webappName/resources"
    def ftlDir = "$cuba.tomcat.dir/webapps/$webappName/WEB-INF/templates"

    task deploy(dependsOn: assemble, type: CubaDeployment) {
        appName = webappName
        appJars(modulePrefix + '-global', modulePrefix + '-portal')
    }

    task deployStatic() {
        doLast {
            copy {
                from file('web/resources')
                include '**/*.css'
                include '**/*.js'
                include '**/*.png'
                include '**/*.gif'
                include '**/*.jpg'
                into resourcesDir
            }
            copy {
                from file('web/WEB-INF/templates')
                include '**/*.ftl'
                into ftlDir
            }
        }
    }

    task cleanStatic() {
        doLast {
            delete resourcesDir
            delete ftlDir
        }
    }

    task webArchive(type: Zip) {
        from file('web')
        from file("$buildDir/web")
        exclude '**/web.xml', '**/app.properties'
        classifier = 'web'
    }

    artifacts {
        archives webArchive
    }

    apply (plugin: "cz.habarta.typescript-generator")

    generateTypeScript {
        def outputFilePath = angularClientModule.projectDir.getAbsolutePath() + "/kacrm-types/kacrm-rest/index.d.ts"

        inputs.dir(globalModule.projectDir.getAbsolutePath() + "/src/com/haulmont/kacrm/dto")
        inputs.dir(portalModule.projectDir.getAbsolutePath() + "/src/com/haulmont/kacrm/portal/dto")
        outputs.file(outputFilePath)

        outputFile = outputFilePath
        classPatterns = [
                "com.haulmont.kacrm.dto.**",
                "com.haulmont.kacrm.portal.dto.**"
        ]
        excludeClassPatterns = [
                "com.haulmont.kacrm.dto.third_party.**"
        ]
        outputKind = "ambientModule"
        module = "kacrm-rest"
        jsonLibrary = "jackson2"
        mapEnum = "asEnum"
    }
}

task undeploy(type: Delete, dependsOn: ":${modulePrefix}-web:cleanConf" ) {
    delete("$cuba.tomcat.dir/shared")
    delete("$cuba.tomcat.dir/webapps/${modulePrefix}-core" )
    delete("$cuba.tomcat.dir/webapps/${modulePrefix}" )
    delete("$cuba.tomcat.dir/webapps/${modulePrefix}-portal" )
    delete("$cuba.tomcat.dir/webapps/${modulePrefix}-front" )
    delete("$cuba.tomcat.dir/webapps/sa-front" )
}

task restart(dependsOn: ['stop', ":${modulePrefix}-core:deploy" , ":${modulePrefix}-web:deploy" , ":${modulePrefix}-portal:deploy" ], description: 'Redeploys applications and restarts local Tomcat') {
    doLast {
        ant.waitfor(maxwait: 6, maxwaitunit: 'second', checkevery: 2, checkeveryunit: 'second') {
            not {
                socket(server: 'localhost', port: '8787')
            }
        }
    }
}
restart.finalizedBy start

