def SETTINGS = "/var/jenkins_home/tools/apache-maven-3.6.0/settings.xml"
def ENCODE = "UTF-8"
def MODULO = "adm"
def TAG_SELECTOR = "UNINTIALIZED"

//======================================================================================================
def build(SETTINGS, ENCODE, jdk) {
   if (jdk == 'JDK8.202') {
      withEnv(["JAVA_HOME=/var/jenkins_home/tools/hudson.model.JDK/JDK8.202"]) {
         sh "mvn -B -f pom.xml -s ${SETTINGS} clean deploy -DskipTests -Dfile.encoding=${ENCODE} -Dproject.build.sourceEncoding=${ENCODE}"
      }
   } else {
      sh "mvn -B -f pom.xml -s ${SETTINGS} clean deploy -DskipTests -Dfile.encoding=${ENCODE} -Dproject.build.sourceEncoding=${ENCODE}"
   }
}

//======================================================================================================
def deployNexus(projeto, SETTINGS, ENCODE) {
   echo "Realizando deploy para o nexus: ${projeto}"
   sh "mvn -B  -s ${SETTINGS} deploy -DskipTests --file=pom.xml -Dfile.encoding=${ENCODE}"
}

//======================================================================================================
def geraVersao() {
   TAG_SELECTOR = readMavenPom file: 'pom.xml'
   VERSAO = TAG_SELECTOR.getVersion()
   VERSAO_TEXTO = "Versao: ${VERSAO}@${env.BUILD_TIMESTAMP_VERSAO}"

   currentBuild.displayName = "${VERSAO}"
   currentBuild.description = "<img src='/static/be103e6b/images/48x48/package.png' style='width: 48px; height: 48px; ' class='icon-package icon-xlg'>"+
   "<a href='http://52.5.53.15:8081/nexus/content/repositories/releases/br/com/rjconsultores/ventaboletosadm/${VERSAO}/ventaboletosadm-${VERSAO}.war'>"+
   "Download Link ventaboletosadm-${VERSAO}.war</a>"

   println(VERSAO_TEXTO)
   writeFile file: "src/java/versionADM.info", text: VERSAO_TEXTO
}

//======================================================================================================
def gitCheckout(branch_name, url_name) {
   if (branch_name == null || branch_name.isEmpty()) {
      branch_name = "master"
   }

   SCM = checkout([
           $class: 'GitSCM', 
	   branches: [[name: "${branch_name}"]],  
	   doGenerateSubmoduleConfigurations: false, 
	   extensions: [[$class: 'AuthorInChangelog']],
	   submoduleCfg: [], 
	   userRemoteConfigs: [[credentialsId: 'admin-gitea', url: url_name]]
	 ])
}

//======================================================================================================
@NonCPS
def verificaTicket(mensagem) {
   def M = mensagem =~ /#\D{2}-\d{4}/
   if(M){
      return M[0].substring(1)
   }
}

//======================================================================================================
@NonCPS
String getChangedFilesList() {
   if( tagName != 'master'){      
      return tagName
   }

   changedFiles = ""
   for (changeLogSet in currentBuild.changeSets) {
      for (entry in changeLogSet.getItems()) {
         for (file in entry.getAffectedFiles()) {
            changedFiles += "${file.editType.name} - ${file.path}\n"
         }
      }
   }
   return changedFiles
}

//======================================================================================================
@NonCPS
String getChangedLog() {
   changedLog = ""
   for (changeLogSet in currentBuild.changeSets) {
      for (entries in changeLogSet.getItems()) {
         for (entry in entries) {
            changedLog += "*Commit: ${entry.commitId}\n"
            changedLog += "Message: ${entry.msg}\n"
	    for (file in entry.getAffectedFiles()) {
	       changedLog += "${file.editType.name} - ${file.path}\n"
	    }
    	    changedLog += "Author: ${entry.author} \n"
         }
      }
   }
   return changedLog
}

//======================================================================================================
@NonCPS
boolean isPullRequest() {
   causas = ""
   def causes = currentBuild.rawBuild.getCauses()
   for (cause in causes) {
      causas += "${cause.getShortDescription()} "
   }

   echo "Conteúdo da solicitação:"
   echo "${causas}"

   return causas.contains('Pull Request merged from Gitea')
}

//======================================================================================================
def archiveFile(arquivo) {
   try {
      archiveArtifacts artifacts: arquivo
   } catch (err) {
      echo err.getMessage()
   }
}

//======================================================================================================
pipeline {
   agent any
   tools {
      maven 'mvn_3.6.0'
      jdk 'JDK8.202'
   }
   stages {
      stage('Info') {
         steps {
            sh '''
            echo "PATH = ${PATH}"
            echo "M2_HOME = ${M2_HOME}"
            '''
            echo "VERSÃO: @${env.BUILD_TIMESTAMP_VERSAO}#${env.BUILD_NUMBER}"
            echo "parametro ${tagName} "
         }
      }

      stage('Checkout Git') {
         steps {
            script {
               try {
                  gitCheckout(tagName, 'http://18.235.188.113:3000/rjconsultores/ventaBoletosAdm.git')
               } catch (err) {
                  echo err.getMessage()
               }
            }
         }
      }

      stage('Deps') {
         steps {
            script {

	       Auditador = build(job: "Adm/Lib-Auditador-Build", parameters: [
               	 [$class: 'StringParameterValue', name: 'GIT', value: "master"]], propagate: true)


	       Integracao = build(job: "Adm/Lib-IntegracaoReceitaDespesa-Build", parameters: [
               	 [$class: 'StringParameterValue', name: 'GIT', value: "master"]], propagate: true)


	       BoletoCnab = build(job: "Adm/Lib-GeneradorBoletosCNAB-Build", parameters: [
               	 [$class: 'StringParameterValue', name: 'GIT', value: "master"]], propagate: true)

               
	       ModelWeb = build(job: "Adm/Lib-ModelWeb-Build", parameters: [
               	 [$class: 'StringParameterValue', name: 'GIT', value: "master"]], propagate: true)

               
	       Flyway = build(job: "Adm/Lib-Flyway-Build", parameters: [
               	 [$class: 'StringParameterValue', name: 'GIT', value: "master"]], propagate: true)

            }
         }
      }

      stage('Build') {
         steps {	    
            script {
               geraVersao()
               build(SETTINGS, ENCODE, 'JDK8.202')
            }
         }
      }
      stage('Test') {
         steps {
            echo "Em construção"
         }
      }
   }

   post {
      success {
         script {
            if( getChangedFilesList()) {
               //gravando e publicando as mudanças
               def publisher = LastChanges.getLastChangesPublisher "PREVIOUS_REVISION", "LINE", "LINE", true, true, "", "", "", "", ""
               publisher.publishLastChanges()
               def changes = publisher.getLastChanges()

               def textoJira = "Build SUCCESS: Versao ${VERSAO_TEXTO}\n" +
	           "(acesse  http://18.235.188.113:1313/job/Adm/job/Adm-Project-Build/${env.BUILD_NUMBER}/)\n\n" +
                   "Download de versão ${VERSAO}\n" +
		   "(http://52.5.53.15:8081/nexus/content/repositories/releases/br/com/rjconsultores/ventaboletosadm/${VERSAO}/ventaboletosadm-${VERSAO}.war)\n\n" +
		   "Alterações do projeto VentaBoletosAdm\n" +
		   "${getChangedFilesList()}\n\n" 

	       def textoTag = "TAG: **${VERSAO_TEXTO}** \n"

               def changedLog = getChangedLog()
               def TICKET = verificaTicket(changedLog)

               for (commit in changes.getCommits()) {
                  def commitInfo = commit.getCommitInfo()
		  textoJira += "${commitInfo}\n\n"

                  textoTag += "- Commit: ${commitInfo.commitId} \n"+
		              "- Autor: ${commitInfo.committerEmail} \n"+
		              "- Data: ${commitInfo.commitDate} \n"+
		              "- Message: ${commitInfo.commitMessage} \n\n"
	       }


               //geração automatica de versão
	       try {
                 def giteaversion = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: '''{
		         "body": "'''+textoTag+'''",
			 "draft": false,
			 "name": "'''+VERSAO+'''",
			 "prerelease": false,
			 "tag_name": "'''+VERSAO+'''",
			 "target_commitish": "master"
		       }''', responseHandle: 'NONE', url: 'http://18.235.188.113:3000/api/v1/repos/adm/VentaBoletosAdm/releases?access_token=6231bd083b69e47f5ad34329891ed6b3128a154e', wrapAsMultipart: false
               } catch (err) {
                  echo err.getMessage()
               }


               if( TICKET ){
                  //integrando ao jira
	          jiraComment body: textoJira, issueKey: TICKET
		                    
		  //resolvendo o card
                  if( textoJira.contains('fix') || textoJira.contains('feat') || textoJira.contains('BREAKING CHANGE') ){
                     step([$class: 'JiraIssueUpdateBuilder', comment: '', jqlSearch: "issue = ${TICKET}", workflowActionName: 'RESOLVIDO'])
		     step([$class: 'JiraIssueUpdateBuilder', comment: '', jqlSearch: "issue = ${TICKET}", workflowActionName: 'TESTAR/PUBLICADO'])
                  }
	       } else {
	          echo 'Ticket não encontrado' 
               }

	       archiveFile("target/ventaboletosadm.war")
	       cleanWs( 
                  cleanWhenAborted:true,
                  cleanWhenFailure: false,
                  cleanWhenNotBuilt: false,
                  cleanWhenSuccess: true,
                  cleanWhenUnstable: true,
                  deleteDirs: true,
                  notFailBuild: true,
                  disableDeferredWipeout: true,
                  patterns: [[ pattern: '.war' , type: 'EXCLUDE' ]]
	       )
            }
         }
      }
   }
}