@Library('jenkins-lib')

import dev.romanjaros.jenkins.utils.ReleaseUtils

def SKIP = "skip"

properties([parameters([
        choice(
                name: 'RELEASE',
                choices: [SKIP, 'patch', 'minor', 'major'],
                description: 'Next new version'
        ),
])])

def output = "Output"
def addon = "CzechQuests"

def tocFiles = [
        "classic_era": "CzechQuests_Vanilla.toc",
        "retail"     : "CzechQuests_Mainline.toc"
]

def readToCVersion = { ->
    return sh(
            script: "grep '## Version:' ${tocFiles['classic_era']} | cut -d ' ' -f 3",
            returnStdout: true
    ).trim()
}

def writeToCVersion = { String tocFile, String current, String next ->
    def content = readFile(file: tocFile)
    content = content.replace("## Version: $current", "## Version: $next")
    writeFile(file: tocFile, text: content)
}

def increaseVersion = { ->
    def currentVersion = readToCVersion()
    def newVersion = ReleaseUtils.increaseVersion(currentVersion, params.RELEASE)
    writeToCVersion(tocFiles['classic_era'], currentVersion, newVersion)
    writeToCVersion(tocFiles['retail'], currentVersion, newVersion)
}

def createZipFile = { String game ->
    def tocFile = tocFiles[game]
    def version = readToCVersion()

    // prepare output folder
    sh "mkdir -p $output/$addon/Addon/Data"

    // copy toc file
    sh "cp $tocFile $output/$addon"

    // copy lue files
    sh "rsync -av './CzechQuests.lua' ./$output/$addon"
    sh "rsync -av './Addon/Data/other.lua' ./$output/$addon/Addon/Data"
    sh "find ./Addon/Data/$game/ -name '*.lua' -exec rsync -av {} ./$output/$addon/Addon/Data/ \\;"
    sh "find ./Addon/Code/ -name '*.lua' -exec rsync -av {} ./$output/$addon/Addon/Code/ \\;"

    // copy assets
    sh "find . -name '*.tga' -exec rsync -avR {} $output/$addon \\;"
    sh "find . -name '*.ttf' -exec rsync -avR {} $output/$addon \\;"

    // create zip
    def zipFileName = "czech-quests-$game-v${version}.zip"
    zip zipFile: zipFileName, archive: false, dir: output

    // remove build folder
    sh "rm -r $output"
}

def pushToGit = { ->
    def version = readToCVersion()
    sh "git checkout ${BRANCH_NAME}"
    sh "git add *.toc"
    sh "git commit -m 'Release $version'"
    sh "git push"
    sh "git tag $version"
    sh "git push origin $version"
}

def uploadToForgejo = { ->
    def version = readToCVersion()
    ForgejoRelease('czech-quests', 'addon', version)
}

MasterJob [:], { ->
    def version = params.RELEASE
    if (version == SKIP) {
        currentBuild.result = 'SUCCESS'
        return
    }

    checkout scm

    stageWhen("version") {
        increaseVersion()
    }

    stageWhen('build') {
        createZipFile("classic_era")
        createZipFile("retail")
        forgejoGit()
        pushToGit()
    }

    stageWhen('release') {
        uploadToForgejo()
    }
}