pipeline {
  // Declarative Pipeline MODE con  Scripted Pipeline Syntax entro le chiamate script { }
  agent none
  environment { 
    enableIIS01       = 'Y'
    enableIIS02       = 'Y'
  }
  stages {
    stage('Checkout') {
      agent any
      steps {
      /* calcolo numero versione... diverso x branch MASTER/DEVELOP */
      script {
        withEnv(['NEXT_BUILD_NUMBER=325']) {
          // env.versionNumber = VersionNumber(versionNumberString : '1.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2019-07-01', skipFailedBuilds: true)
          env.versionNumber = VersionNumber(versionNumberString : '1.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2019-07-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
          env.versionNumberBeta = VersionNumber(versionNumberString : '1.1.${BUILD_DATE_FORMATTED, "yyMM"}-beta.${BUILDS_ALL_TIME}', projectStartDate : '2019-07-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
          env.APP_NAME = 'NKC'
        }
      }				
      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 VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
      fixNuget("${WORKSPACE}\\NKC_WF.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 VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
          fixNuget("${WORKSPACE}\\NKC_WF.sln")
        }
        script {
          /* compilo installers in base al BRANCH del cliente... */
          if (env.BRANCH_NAME == "develop") {
            parallel (
              NKC_SITE: {
                sleep 0
                bat "\"${tool 'MSBuild-16.0'}\" NKC_WF/NKC_WF.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
              },
              failFast: false)
            }
          else {
            echo 'Niente x Build (limitata a develop)...'
          }	
        }			
      }	
    }
    stage('Deploy') {
      agent any
      steps {
        script {
          // CAMBIO numero versione + checkout NuGet in file sorgente!!!
          bat "e:\\fart.exe VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
          fixNuget("${WORKSPACE}\\NKC_WF.sln")
        }
        script {
          /* DEPLOY condizionale: master (Ufficio Seriate) / demo_ovh (Demo Online) */
          if (env.BRANCH_NAME == "master") {
            parallel (
              SITE_IIS02: {
                if(env.enableIIS02 == "Y")
                {
                  sleep 1
                  // SITE
                  bat "\"${tool 'MSBuild-16.0'}\" \"/p:AspnetMergePath=C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.2 Tools\" /p:DeployOnBuild=true /p:Targets=Publish /p:PublishProfile=IIS02.pubxml /p:VisualStudioVersion=16.0 /p:RunCodeAnalysis=false /p:Configuration=Release /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ NKC_WF/NKC_WF.csproj"
                  sleep 3
                }
              },
             failFast: false)
          }
          else if (env.BRANCH_NAME == "develop") {
            parallel (
              SITE_IIS01: {
                if(env.enableIIS01 == "Y")
                {
                  sleep 3
                  // SITE
                  bat "\"${tool 'MSBuild-16.0'}\" \"/p:AspnetMergePath=C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.2 Tools\" /p:DeployOnBuild=true /p:Targets=Publish /p:PublishProfile=IIS01.pubxml /p:VisualStudioVersion=16.0 /p:RunCodeAnalysis=false /p:Configuration=Release /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ NKC_WF/NKC_WF.csproj"
                  sleep 1
                }
              },
             failFast: false)
          }
          else
          {
            echo 'Questo BRANCH non necessita di deploy...'
          }
        }
      }
    }
    stage('Installers') {
      // da rivedere: creare branch = versioni LEGACY, STABLE (LTS), INSIDER (ULTIMATE), e NON pubblicare DOCS (ex branch Giancarlo)... impostare filtro?
      agent any
      steps {
        // in primis cambio versione e NuGet
        script {
          // CAMBIO numero versione + checkout NuGet in file sorgente!!!
          bat "e:\\fart.exe VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
          fixNuget("${WORKSPACE}\\NKC_WF.sln")
        }
        // ora mi occupo delle operazioni di compressione e copia...
        script {
          /* compilo installers SOLO stable / beta */
          if (env.BRANCH_NAME == "stable" || env.BRANCH_NAME.contains("beta") ) { 
            // calcolo il config...
            if (env.BRANCH_NAME == "beta") {
              env.config = "Debug"
              env.classifier = "unstable"
            }
            else if (env.BRANCH_NAME == "stable") {
              env.config = "Release"
              env.classifier = ""
            }

            parallel (
            SITE_NKC: {					
              sleep 0
              // SITE
              bat "\"${tool 'MSBuild-16.0'}\" \"/p:AspnetMergePath=C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.2 Tools\" /T:Package /P:Configuration=Prod /p:PublishProfile=${env.BRANCH_NAME}.pubxml /p:VisualStudioVersion=16.0 /p:RunCodeAnalysis=false /p:AutoParameterizationWebConfigConnectionStrings=False /p:PackageLocation=Releases/${env.BRANCH_NAME}/NKC.zip /p:DeployIisAppPath=\"Default Web Site/NKC\" /p:PackageAsSingleFile=True /p:OutputPath=bin/ NKC_WF/NKC_WF.csproj"
              // pubblico su server deploy!
              publishToDeployServer("NKC_WF\\", "c:\\inetpub\\wwwroot\\SWS\\", "NKC")
              nexusArtifactUploader (
              artifacts: [                
                [
                  artifactId: 'NKC',
                  classifier: "${env.classifier}",
                  file: "NKC_WF\\Releases\\${env.BRANCH_NAME}\\NKC.zip",
                  type: 'zip'
                ]
              ],
              credentialsId: 'bc9d8e92-4302-3266-817f-7b58501d12d5',
              //groupId: 'MP', 
              nexusUrl: 'nexus.steamware.net', 
              nexusVersion: 'nexus3', 
              protocol: 'http', 
              repository: 'SWS', 
              version: "${env.versionNumber}"
            )
            },
            failFast: false)
          }
          /* preparo nuget pkg dell'SDK ma solo x branch SDK / beta */
          else if (env.BRANCH_NAME == "SDK" || env.BRANCH_NAME.contains("beta") ) { 
            // calcolo il config...
            if (env.BRANCH_NAME == "beta") {
              env.config = "Debug"
              env.packVers = env.versionNumberBeta
            }
            else if (env.BRANCH_NAME == "SDK") {
              env.config = "Release"
              env.packVers = env.versionNumber
            }
            // elimino vecchie build...
            bat "del /f /q *.nupkg"
            // BUILD!
            bat "\"${tool 'MSBuild-16.0'}\" NKC_SDK\\NKC_SDK.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /m"
            // creo package NuGet... con version in modo da fare ANCHE le beta
            bat "e:\\nuget.exe pack ${WORKSPACE}\\NKC_SDK\\NKC_SDK.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
            
            // lancio upload con nuget!
            echo 'Start upload with nuget push'
            bat "e:\\nuget setapikey fe387daa-d07c-3207-877e-96c8be1be91b -source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push NKC_SDK.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
          }
          else
          {
            echo 'Questo BRANCH non necessita di installer...'
          }
        }
      }
    }
  }
  post {
    success {
      sendSlack("Successful", "good")
      updateGitlabCommitStatus(name: 'jenkins-build', state: 'success')
    }
    failure {
      sendSlack("Failed", "danger")
      updateGitlabCommitStatus(name: 'jenkins-build', state: 'failed')
    }
    unstable {
      sendSlack("Unstable", "warning")
      updateGitlabCommitStatus(name: 'jenkins-build', state: 'failed')
    }
  }
}

// Funzione x pubblicazione su server IIS di deploy
def publishToDeployServer(prjPath, iisPath, packName) {
      echo "Richiesto esecuzione publishToDeployServer con parametri: " + prjPath + " | " + iisPath + " | " + packName
      // inizio copiando files di base da area VersGen...
       bat "xcopy /y VersGen\\ChangeLog.html " + prjPath + "Resources\\ChangeLog.html "
       bat "xcopy /y VersGen\\logoSteamware.png " + prjPath + "Resources\\logoSteamware.png "
       bat "xcopy /y VersGen\\manifest.xml " + prjPath + "Resources\\manifest.xml "
      // manifest.xml: aggiorno versNumber ed URL del branch di update...
      bat "e:\\fart.exe " + prjPath + "Resources\\manifest.xml 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
      bat "e:\\fart.exe " + prjPath + "Resources\\manifest.xml {{BRANCHNAME}} ${env.BRANCH_NAME} || EXIT /B 0"
      bat "e:\\fart.exe " + prjPath + "Resources\\manifest.xml {{PACKNAME}} " + packName + " || EXIT /B 0"
      bat "e:\\fart.exe " + prjPath + "Resources\\ChangeLog.html {{CURRENT-REL}} ${env.versionNumber} || EXIT /B 0" 
      writeFile file: prjPath + 'changeLog.log', text: "${getChangeString()}"
      powershell '(Get-Content ' + prjPath + 'Resources\\ChangeLog.html) | ForEach-Object { $_ -replace \"{{LAST-CHANGES}}\", \"${getChangeString()}\" } | Set-Content ' + prjPath + 'Resources\\ChangeLog.html'
      // copio ed esporto in IIS02 i vari files .xml, .html, .zip
      bat "xcopy /y " + prjPath + "Resources\\manifest.xml " + iisPath + packName + "\\${env.BRANCH_NAME}\\ "
      bat "xcopy /y " + prjPath + "Resources\\ChangeLog.html " + iisPath + packName + "\\${env.BRANCH_NAME}\\ "
      bat "xcopy /y " + prjPath + "Resources\\logoSteamware.png " + iisPath + packName + "\\${env.BRANCH_NAME}\\ "
      // salvo copia della versione...
      bat "xcopy /y " + prjPath + "\\Releases\\${env.BRANCH_NAME}\\* E:\\Staging\\byProd\\MP\\${env.BRANCH_NAME}\\" + packName + "\\${env.versionNumber}\\ "  
      // copio x AutoUpdate deploy
      bat "xcopy /y " + prjPath + "\\Releases\\${env.BRANCH_NAME}\\" + packName + ".zip " + iisPath + packName + "\\${env.BRANCH_NAME}\\ "
}
@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:  "#sauder-nkc-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 invio slack
// def sendGitlab(status) {
//   gitlabCommitStatus(
//       builds: status,
//       [[connection: gitLabConnection('Gitlab'),
//       projectId: '1',
//       revisionHash: '']]
//       ){
//       // some block
//   }
// }

// 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\""
  }
  bat "e:\\nuget.exe restore ${solutionFile}"
}