plugins {
    id 'nu.studer.credentials' version('1.0.4')
    id 'idea'
    id 'eclipse'
    id 'application'
    id 'java-library'
    id 'war'
    id 'gradle-ncore' version("$pluginVersion")
    id 'maven-publish'
}

targetCompatibility = 1.8

ncore {
    coreVersion = project.properties.'biz.redsoft.ncore.version'
    sourceEncoding = 'UTF-8'
}

group = 'biz.redsoft.sample'

repositories {
    maven {
        def repo = getProperty("biz.redsoft.private.repo")
        url  repo
        if (repo.contains("http:/"))
            allowInsecureProtocol = true
        if (project.credentials.user != null && project.credentials.password != null) {
            credentials {
                username project.credentials.user
                password project.credentials.password
            }
        }
    }
}

dependencies {
    implementation 'javax.servlet:javax.servlet-api:3.1.0'
    testCompileClasspath 'org.junit.jupiter:junit-jupiter:5.8.2'
    testImplementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.76'
    testImplementation 'org.apache.tomcat.embed:tomcat-embed-jasper:9.0.76'
    runtimeClasspath files(ncoreGenerateControlDataJar)
    runtimeClasspath files(genJar)
}


// writing build process to a log file
// --------------------- BUILD LOG SETTINGS ----------------------
def tstamp = new Date().format('yyyy-MM-dd_HH-mm-ss')
def buildLogDir = "${rootDir}/logs"
mkdir("${buildLogDir}")
def buildLog = new File("${buildLogDir}/${tstamp}_buildLog.log")


import org.gradle.internal.logging.LoggingOutputInternal

import java.util.regex.Matcher

System.setProperty('org.gradle.color.error', 'RED')

gradle.services.get(LoggingOutputInternal).addStandardOutputListener(new StandardOutputListener() {
    void onOutput(CharSequence output) {
        buildLog << output
    }
})

gradle.services.get(LoggingOutputInternal).addStandardErrorListener(new StandardOutputListener() {
    void onOutput(CharSequence output) {
        buildLog << output
    }
})
// --------------------- BUILD LOG SETTINGS ----------------------

run.args = ['client',
            '-config', 'ncore-properties.xml',
            '-config', 'ncore-properties-local.xml']

task copyDist(type: Copy) {
    from distZip
    from distTar
    from war
    def releaseDir
    if (project.hasProperty('biz.redsoft.release.dir') && project.getProperty('biz.redsoft.release.dir'))
        releaseDir = "${project.getProperty('biz.redsoft.release.dir')}"
    else
        releaseDir = "$projectDir/../releases"
    into "$releaseDir/$project.name/$version"
}

def versionPropertiesFilePath = sourceSets.main.resources.srcDirs[0].toString() + File.separator + "META-INF/ncore-product/${project.group}/version.properties"

release {
    def newVersion = project.getVersion().toString().replace("-SNAPSHOT", "")
    commitNewVersion.enabled(true)
    failOnCommitNeeded = false
    failOnPublishNeeded = true
    failOnSnapshotDependencies = true
    failOnUnversionedFiles = false
    failOnUpdateNeeded = false
    revertOnFail = true
    preCommitText = ''
    preTagCommitMessage = '[Gradle Release Plugin] - pre tag commit: '
    tagCommitMessage = '[Gradle Release Plugin] - creating tag: '
    newVersionCommitMessage = '[Gradle Release Plugin] - new version commit: '
    tagTemplate = "${project.name}/v${newVersion}"
    versionPropertyFile = versionPropertiesFilePath
    versionProperties = []
    snapshotSuffix = '-SNAPSHOT'
    buildTasks = ['ncoreTestDbConnection', 'clean', 'unSnapshotVersion', 'writeVersion', 'commitNewVersion', 'nbackup', 'build', 'copyDist', 'publish', 'dockerFile', 'commitNewVersion']
    ignoredSnapshotDependencies = []
    versionPatterns = [
            /(\d+)(\.)(\d+)(\.)(\d+)([^\d]*\u0024)/: { Matcher m, Project p ->
                project.getVersion().newVersion().toString()
            }
    ]
    git.requireBranch.set('master')
    pushReleaseVersionBranch = 'master'
}

//Добавить флаг -Pbiz.redsoft.release=true к таске release для того чтобы публиковалось в releases и false если в snapshots.
//./gradlew release -Pbiz.redsoft.release=true 
publishing {
    repositories {
        maven {
            def isRepoCredetionals = project.hasProperty('biz.redsoft.repo.user') && project.hasProperty('biz.redsoft.repo.password')
            def isCredentialsInsideBuildScript = project.credentials.user != null && project.credentials.password != null
            println(isRepoCredetionals ? "Using repoCredentials for publish..." :
                    isCredentialsInsideBuildScript ? "Using buildScript credentials for publish..." : "Credentials are not presented!!!")
            if (isRepoCredetionals) {
                credentials {
                    username project.'biz.redsoft.repo.user'
                    password project.'biz.redsoft.repo.password'
                }
            } else if (isCredentialsInsideBuildScript) {
                credentials {
                    username project.credentials.user
                    password project.credentials.password
                }
            }
            def suffix = project.findProperty('biz.redsoft.release') ? 'releases' : 'snapshots'
            url "https://ncore-repo.red-soft.ru/repository/${suffix}"
        }
    }
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}


jar{
    manifest{
        attributes(
                'Main-Class': 'biz.redsoft.ncore.client.MainForm',
                'Class-Path': configurations.runtimeClasspath.collect { it.name }.join(' ')
        )
    }
}

startScripts {
    project.startScripts.defaultJvmOpts = ['-Dlogback.configurationFile=./config/logback.xml']
}

distTar {
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
distZip {
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}