@Library('jenkins-lib')

import dev.romanjaros.jenkins.utils.ReleaseUtils

def SKIP = "skip"

properties([parameters([
        choice(
                name: 'RELEASE',
                choices: ['patch', 'minor', 'major'],
                description: 'Release new version'
        ),
        choice(
                name: 'GAME',
                choices: [SKIP, 'classic_era', 'retail', 'all'],
                description: 'Create build with manual tag',
        )
])])

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

def readToCVersion = { String tocFile ->
    return sh(
            script: "grep '## Version:' $tocFile | 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 createZipFile = { String game ->
    def tocFile = tocFiles[game]

    // prepare output folder
    sh "mkdir -p $outputFolder"

    // copy toc file
    sh "cp $tocFile $outputFolder"

    // copy files
    sh "find . -name '*.lua' -exec rsync -av {} $outputFolder \\;"
    sh "find . -name '*.tga' -exec rsync -av {} $outputFolder \\;"
    sh "find . -name '*.ttf' -exec rsync -av {} $outputFolder \\;"

    // get version
    def currentVersion = readToCVersion(tocFile)
    def newVersion = ReleaseUtils.increaseVersion(currentVersion, params.RELEASE)

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

    // remove build folder
    sh "rm -r $outputFolder"

    // save version
    writeToCVersion(tocFile, currentVersion, newVersion)
}

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

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

    checkout scm

    stageWhen('build') {
        def game = params.GAME
        if (game == "all") {
            createZipFile("classic_era")
            createZipFile("retail")
        } else {
            createZipFile(game)
        }
        forgejoGit()
        pushToGit(game)
    }

    stageWhen('release') {
        def game = params.GAME
        def tocFile = tocFiles[game]
        def version = readToCVersion(tocFile)
        ForgejoRelease('czech-quests', 'addon', version)
    }
}