/*
 * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

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

version stripBallerinaExtensionVersion("${project.version}")

description = 'Ballerina - EDI tools package'

def packageName = "editoolspackage"
def packageOrg = "ballerina"
def tomlVersion = stripBallerinaExtensionVersion("${project.version}")
def ballerinaTomlFilePlaceHolder = new File("${project.rootDir}/build-config/resources/package/Ballerina.toml")
def balToolTomlFilePlaceHolder = new File("${project.rootDir}/build-config/resources/package/BalTool.toml")
def ballerinaTomlFile = new File("$project.projectDir/Ballerina.toml")
def balToolTomlFile = new File("$project.projectDir/BalTool.toml")
def balerinaCentralDir = System.getProperty("user.home") + "/.ballerina/repositories/central.ballerina.io/bala/ballerina"
def ballerinaLocalDir = System.getProperty("user.home") + "/.ballerina/repositories/local/bala/ballerina"
def ediPackageDir = project.file("$project.projectDir")
def balCentralCacheDir = project.file(System.getProperty("user.home") + "/.ballerina/repositories/central.ballerina.io")
def ballerinaToolConfigToml = System.getProperty("user.home") + "/.ballerina/.config/bal-tools.toml"
task updateTomlFiles {
    // Update the Ballerina.toml and Dependencies.toml files
    doLast {
        def newConfig = ballerinaTomlFilePlaceHolder.text.replace("@project.version@", project.version)
        newConfig = newConfig.replace("@toml.version@", tomlVersion)
        ballerinaTomlFile.text = newConfig

        def newToolConfig = balToolTomlFilePlaceHolder.text.replace("@project.version@", project.version)
        newToolConfig = newToolConfig.replace("@toml.version@", tomlVersion)
        balToolTomlFile.text = newToolConfig
    }
}

task commitTomlFiles {
    // Commit the Ballerina.toml and Dependencies.toml files
    doLast {
        project.exec {
            ignoreExitValue true
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', '/c', "git commit -m \"[Automated] Update the native jar versions\" Ballerina.toml Dependencies.toml"
            } else {
                commandLine 'sh', '-c', "git commit -m '[Automated] Update the native jar versions' Ballerina.toml Dependencies.toml"
            }
        }
    }
}

task deleteOldEdiCliJars(type: Delete) {
    // Delete the old EDI Tools CLI jar from the resources directory
    delete fileTree(dir: 'resources').matching {
        include 'edi-tools-cli-*.jar'
    }
}

task copyEdiCliJar {
    doLast {
        // Copy the EDI Tools CLI jar to the resources directory
        if (!file("resources").exists()) {
            file("resources").mkdir()
        }
        copy {
            from "../edi-tools-cli/build/libs/edi-tools-cli-${version}.jar"
            into "resources"
            include "*.jar"
        }
    }
}

task createBallerinaToolConfigFile {
    // Create the bal-tools.toml file in the .ballerina/.config directory
    def configFileContent = """
        [[tool]]
        id = "edi"
        org = "ballerina"
        name = "editoolspackage"
        version = "$version"
        active = true
    """.stripIndent()

    outputs.upToDateWhen { false }
    doLast {
        if (!file(ballerinaToolConfigToml).exists()) {
            file(ballerinaToolConfigDir).mkdirs()
            file(ballerinaToolConfigToml).createNewFile()
        }

        // Retrieve existing content of toml file
        def tomlFile = file(ballerinaToolConfigToml)
        def tomlFileContent = tomlFile.text

        // Append tool to toml file if it does not exist
        if (!tomlFileContent.contains(configFileContent)) {
            tomlFile << "\n" + configFileContent
            println("Successfully created the bal-tools.toml file in the .ballerina/.config directory")
        } else {
            println("bal edi tool already exists!")
        }
    }
}

task buildEDIPackage {
    doLast {
        // Pack and push the EDI Tools package to the local repository
        exec {
            workingDir ediPackageDir
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', "/c", "bal pack && bal push --repository=local"
            } else {
                commandLine 'sh', "-c", "bal pack && bal push --repository=local"
            }
        }
        println("Successfully build and pushed the EDI Tools package to the local repository")

        // Remove the cache directories in the central repository
        delete {
            fileTree(balCentralCacheDir).matching {
                include 'cache-*'
            }
        }
        println("Successfully cleaned the .ballerina/cache* directories")

        // Update the central repository
        def balDestinationDir = "$balerinaCentralDir/$packageName"
        def balSourceDir = "$ballerinaLocalDir/$packageName"
        if (file(balDestinationDir).exists()) {
            file(balDestinationDir).deleteDir()
        }
        copy {
            from balSourceDir
            into balDestinationDir
        }
        println("Successfully copied package from local/bala the central.ballerina.io/bala directory")
    }
}
task publishEDIPackage {
    doLast {
        // Push the EDI Tools package to the central repository
        exec {
            workingDir ediPackageDir
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine 'cmd', "/c", "bal pack && bal push"
            } else {
                commandLine 'sh', "-c", "bal pack && bal push"
            }
        }
        println("Successfully pushed the EDI Tools package to the central.")
    }
}
task build {
    dependsOn ":edi-tools-cli:build"
    dependsOn deleteOldEdiCliJars
    dependsOn createBallerinaToolConfigFile
    dependsOn copyEdiCliJar
    dependsOn updateTomlFiles
    dependsOn commitTomlFiles
    dependsOn buildEDIPackage
}

task release {
    dependsOn publishEDIPackage
}

deleteOldEdiCliJars.dependsOn ":edi-tools-cli:build"
copyEdiCliJar.dependsOn deleteOldEdiCliJars
commitTomlFiles.dependsOn updateTomlFiles
buildEDIPackage.dependsOn createBallerinaToolConfigFile
buildEDIPackage.dependsOn copyEdiCliJar
buildEDIPackage.dependsOn commitTomlFiles

release.dependsOn build
