pipeline {
  // Declarative Pipeline MODE con  Scripted Pipeline Syntax entro le chiamate script { }
  agent none
  environment { 
    EMAIL_RECIPIENTS  = 'samuele@steamware.net'
  }
  stages {
    stage('Checkout') {
    agent any
      steps {

      /* calcolo numero versione... diverso x branch MASTER/DEVELOP */
      script {
        env.versionNumber = VersionNumber(versionNumberString : '2.2.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILD_DATE_FORMATTED, "ddHH"}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
        env.APP_NAME = 'SCMA'
      }				
      script {
        currentBuild.displayName = "${env.versionNumber}"
        if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME.contains("DEMO")) { 
          currentBuild.description = "TEST ${env.versionNumber}"
        }
        else {
          currentBuild.description = "BUILD ${env.versionNumber}"
        }
      }
      // CAMBIO numero versione + checkout NuGet in file sorgente!!!
      bat "e:\\fart.exe ${WORKSPACE}\\MTC_Adapter\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
      //fixNuget("${WORKSPACE}\\MTC_Adapter\\SCMA.sln")
      }
    }
    stage('Build') {
      agent any
      steps {
        script {
          properties([buildDiscarder(logRotator(artifactDaysToKeepStr: '180', artifactNumToKeepStr: '30', daysToKeepStr: '360', numToKeepStr: '30')), pipelineTriggers([])])
          // CAMBIO numero versione + checkout NuGet in file sorgente!!!
          bat "e:\\fart.exe ${WORKSPACE}\\MTC_Adapter\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
          fixNuget("${WORKSPACE}\\MTC_Adapter\\SCMA.sln")
        }
        script {
          /* compilo installers in base al BRANCH del cliente... */
          if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME == "master") {
            parallel (
              DB: {
                sleep 1
                bat "\"${tool 'MSBuild-16.0'}\" MTC_Adapter/MTC-ADB/MTC-ADB.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
              },
              MAIN: {
                sleep 0
                bat "\"${tool 'MSBuild-16.0'}\" MTC_Adapter/SCMA/SCMA.csproj -target:Build /p:DefineConstants=\"FS30D=1,SIEMENS=1\" /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /p:verbosity=minimal /m"
              },
              failFast: false)
            }
          else {
            echo 'Niente x Build (limitata a develop/master)...'
          }	
        }			
      }	
    }
    stage('Deploy') {
          agent any
          steps {
            // in primis fix versione e recupero pacchetti...
            script {
              // CAMBIO numero versione + checkout NuGet in file sorgente!!!
              bat "e:\\fart.exe ${WORKSPACE}\\MTC_Adapter\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
              fixNuget("${WORKSPACE}\\MTC_Adapter\\SCMA.sln")
            }
            // poi compilo
            script {
              // procedo solo se NON si tratta di commit in ramo DOCUMentazione...
              if (env.BRANCH_NAME == "master" || env.BRANCH_NAME.contains("develop") || env.BRANCH_NAME.contains("MTC_Only")) { 
                echo 'Questo BRANCH non necessita di installer...'
              }
              else
              {
                if (env.BRANCH_NAME == "MySql") {
                  // pulizia directory BIN
                  bat "RD /S /Q \"${WORKSPACE}\\MTC_Adapter\\MTC-ADB\\bin\" || EXIT /B 0"
                  // BUILD adapter MySql!
                  bat "\"${tool 'MSBuild-16.0'}\" MTC_Adapter/MTC-ADB/MTC-ADB.csproj -target:Build /p:Configuration=${env.BRANCH_NAME} /p:VisualStudioVersion=15.0 /p:RunCodeAnalysis=false /p:Platform=\"Any CPU\" /p:DebugSymbols=false /p:DebugType=None /p:OutputPath=bin/${env.versionNumber} /p:verbosity=minimal /m"
                }
                else {
                  // pulizia directory BIN
                  //bat "RD /S /Q \"${WORKSPACE}\\MTC_Adapter\\SCMA\\bin\" || EXIT /B 0"
                  if (env.BRANCH_NAME == "FANUC") {
                    env.currConfig='CMS-FANUC'
                  }
                  else if (env.BRANCH_NAME == "KVARA") {
                    env.currConfig='CMS-ESA'
                  }
                  else if (env.BRANCH_NAME == "OSAI") {
                    env.currConfig='CMS-OSAI'
                  }
                  else if (env.BRANCH_NAME == "SIEMENS") {
                    env.currConfig='CMS-SIEMENS'
                  }
                  else {
                    env.currConfig='Release'
                  }
                  // Build adapters MTC/OPC-UA-RED
                  bat "\"${tool 'MSBuild-16.0'}\" MTC_Adapter/SCMA/SCMA.csproj -target:Build /p:DefineConstants=\"FS30D=1,SIEMENS=1\" /p:Configuration=${env.currConfig} /p:DebugSymbols=false /p:DebugType=None /p:OutputPath=bin/${env.versionNumber} /p:verbosity=minimal /m"
                }
              }
            }
            // ora mi occupo delle operazioni di compressione e copia...
            script {
              // procedo ove necessario...
               if (env.BRANCH_NAME == "master" || env.BRANCH_NAME.contains("develop") || env.BRANCH_NAME.contains("MTC_Only")) { 
                echo 'Nessuna compressione + copia post deploy x documentazione'
              }
              else {
                // manifest.xml: aggiorno versNumber ed URL del branch di update...
                bat "e:\\fart.exe MTC_Adapter\\SCMA\\Resources\\manifest.xml 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
                bat "e:\\fart.exe MTC_Adapter\\SCMA\\Resources\\manifest.xml {{BRANCHNAME}} ${env.BRANCH_NAME} || EXIT /B 0"
                bat "e:\\fart.exe MTC_Adapter\\SCMA\\Resources\\ChangeLog.html {{CURRENT-REL}} ${env.versionNumber} || EXIT /B 0" 
                writeFile file: 'changeLog.log', text: "${getChangeString()}"
                // copio ed esporto in IIS02 i vari files .xml, .html, .zip
                powershell '(Get-Content MTC_Adapter\\SCMA\\Resources\\ChangeLog.html) | ForEach-Object { $_ -replace \"{{LAST-CHANGES}}\", \"${getChangeString()}\" } | Set-Content MTC_Adapter\\SCMA\\Resources\\ChangeLog.html'

                bat "xcopy /y MTC_Adapter\\SCMA\\Resources\\manifest.xml c:\\inetpub\\wwwroot\\SWS\\SCMA\\${env.BRANCH_NAME}\\ "
                bat "xcopy /y MTC_Adapter\\SCMA\\Resources\\ChangeLog.html c:\\inetpub\\wwwroot\\SWS\\SCMA\\${env.BRANCH_NAME}\\ "
                bat "xcopy /y MTC_Adapter\\SCMA\\Resources\\logoSteamware.png c:\\inetpub\\wwwroot\\SWS\\SCMA\\${env.BRANCH_NAME}\\ "


                // // elimino files inutili di resources e pubblico
                // bat "RD /S /Q MTC_Adapter\\SCMA\\Resources"
                // elimino vecchio zip...
                bat "RD /S /Q Releases\\${env.BRANCH_NAME}\\ || EXIT /B 0"
                if (env.BRANCH_NAME == "MySql") {
                  // Compressione in .zip dell'installer x MySql...
                  bat "e:\\7za.exe a -tzip ${WORKSPACE}\\Releases\\${env.BRANCH_NAME}\\SCMA.zip ${WORKSPACE}\\MTC_Adapter\\MTC-ADB\\bin\\${env.versionNumber}\\*"
                }
                else {
                  // Compressione in .zip dell'installer x adapter MTC/OPC-UA-RED...
                  bat "e:\\7za.exe a -tzip ${WORKSPACE}\\Releases\\${env.BRANCH_NAME}\\SCMA.zip ${WORKSPACE}\\MTC_Adapter\\SCMA\\bin\\${env.versionNumber}\\*"
                }

                // salvo copia della versione in staging...
                bat "xcopy /y Releases\\${env.BRANCH_NAME}\\SCMA.zip E:\\Staging\\byProd\\SCMA\\${env.BRANCH_NAME}\\${env.versionNumber}\\ "  
                // copio in area WebDeploy
                bat "xcopy /y Releases\\${env.BRANCH_NAME}\\SCMA.zip c:\\inetpub\\wwwroot\\SWS\\SCMA\\${env.BRANCH_NAME}\\ "
              }
            }
          }
        }
  }
  post {
    success {
      sendSlack("Successful", "good")
    }
    failure {
      sendSlack("Failed", "danger")
    }
    unstable {
      sendSlack("Unstable", "warning")
    }
  }
}

@NonCPS
// Funzione x recupero changeLog
def getChangeString() {
  MAX_MSG_LEN = 100
  def changeString = ""

  echo "Gathering SCM changes"
  def changeLogSets = currentBuild.changeSets
  for (int i = 0; i < changeLogSets.size(); i++) {
    def entries = changeLogSets[i].items
    for (int j = 0; j < entries.length; j++) {
      def entry = entries[j]
      truncated_msg = entry.msg.take(MAX_MSG_LEN)
      changeString += " - ${truncated_msg} [${entry.author}]\n"
    }
  }

  if (!changeString) {
    changeString = " - Nessuna Modifica"
  }
  return changeString
}
// Funzione x invio slack
def sendSlack(status, colorCode) {
  slackSend (
    color:    colorCode, 
    channel:  "#scma-dev",
    failOnError: false,
    message:  "${env.JOB_NAME} ${env.versionNumber}  | " + status + ": Build ${env.BUILD_NUMBER}\n\n" +
              "Modifiche:\n " + getChangeString() + "\n\n Verifica build: <${env.BUILD_URL}|Apri>" + "\n"
  )
}
// funzione x fix pacchetti nuget da NOSTRO repo Nexus con proxy
def fixNuget(solutionFile) {
  // bat "e:\\nuget setapikey fe387daa-d07c-3207-877e-96c8be1be91b -source http://nexus.steamware.net/repository/nuget-group"
  // solo la prima volta va aggiunta...
  hasSource = bat "e:\\nuget sources list | find \"Steamware\" /C"
  if (hasSource == "0")
  {
    bat "e:\\nuget sources Add -Name \"Steamware Nexus\" -Source http://nexus.steamware.net/repository/nuget-group -username \"nugetUser\" -password \"viaDante16\""
  }
  else
  {
    bat "e:\\nuget sources Update -Name \"Steamware Nexus\" -Source http://nexus.steamware.net/repository/nuget-group -username \"nugetUser\" -password \"viaDante16\""
  }
  // preliminarmente svuoto...
  bat "rmdir /Q /S ${WORKSPACE}\\MTC_Adapter\\packages"
  // restore pacchetti
  bat "e:\\nuget.exe restore ${solutionFile}"
}