package com.freeleaps.devops

class SemanticReleasingExecutor {
  def steps
  def workspace
  def config
  def plugins = [
    'semantic-release',
    '@semantic-release/git',
    '@semantic-release/changelog',
    '@semantic-release/exec',
    'conventional-changelog-conventionalcommits'
  ]

  SemanticReleasingExecutor(steps, workspace) {
    this.steps = steps
    this.workspace = workspace
    // TODO: This should be a parameter, not hardcoded
    this.config = 'com/freeleaps/devops/builtins/semantic-release/releaserc.json'
  }

  def release(credentialsId, branch) {
    steps.log.warn("SemanticReleasingExecutor", "Configuration file customization is not supported yet, using builtin release rules as fallback")
    steps.log.info("SemanticReleasingExecutor", "Releasing with config: ${config}")

    steps.dir(steps.env.workroot) {
      steps.withCredentials([steps.usernamePassword(credentialsId: credentialsId, passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
        steps.env.GIT_CREDENTIALS = "${steps.env.GIT_USERNAME}:${steps.env.GIT_PASSWORD}"
        steps.writeFile file: '.releaserc.json', text: steps.libraryResource(config)
        steps.sh "git config --global --add safe.directory ${steps.env.workroot}"
        steps.env.GIT_LOCAL_BRANCH = "${branch}"

        // Store the version before semantic release
        def previousVersion = ""
        def versionFileExistsBefore = steps.sh(script: 'test -f "VERSION"', returnStatus: true) == 0
        if (versionFileExistsBefore) {
          previousVersion = steps.readFile('VERSION').trim()
          steps.log.info("SemanticReleasingExecutor", "Previous version: ${previousVersion}")
        }

        steps.sh """
          #!/bin/bash
          semantic-release
        """
        steps.log.info("SemanticReleasingExecutor", "Semantic release completed, read latest version from VERSION file")

        // check if VERSION file exists
        def versionFileExists = steps.sh(script: 'test -f "VERSION"', returnStatus: true) == 0
        def released = false

        if (versionFileExists) {
          def currentVersion = steps.readFile('VERSION').trim()
          released = !versionFileExistsBefore || (currentVersion != previousVersion)
          if (released) {
            steps.env.LATEST_VERSION = steps.readFile('VERSION').trim()
            steps.env.SEMANTIC_RELEASED = true
            steps.log.info("SemanticReleasingExecutor", "Semantic release completed, version: ${steps.env.LATEST_VERSION}")
          } else {
            steps.log.warn("SemanticReleasingExecutor", "No new version released, current version remains: ${currentVersion}")
          }
        } else {
          steps.log.warn("SemanticReleasingExecutor", "VERSION file not found, semantic release may have failed ?")
        }
      }
    }
  }
}