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 {
        env.versionNumber = VersionNumber(versionNumberString : '2.0.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILD_DATE_FORMATTED, "ddHH"}', projectStartDate : '2019-07-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
        env.versionNumberdevelop = VersionNumber(versionNumberString : '2.0.${BUILD_DATE_FORMATTED, "yyMM"}-develop.${BUILD_DATE_FORMATTED, "ddHH"}', 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") || env.BRANCH_NAME.contains("report")) { 
          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/ /p:verbosity=minimal /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=IIS02 /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ /p:verbosity=minimal 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/ /p:verbosity=minimal 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 master / develop */
          if (env.BRANCH_NAME == "master" || env.BRANCH_NAME.contains("develop") ) { 
            
            parallel (
            NKC_UPLOAD: {					
              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/ /p:verbosity=minimal NKC_WF/NKC_WF.csproj"
              setManifestFile("NKC_WF\\", "NKC")
              
              // ---------- Upload versione 0 ----------
              nexusArtifactUploader (
              artifacts: [
                [
                  artifactId: 'LAST',
                  classifier: '',
                  file: "NKC_WF\\Resources\\manifest.xml",
                  type: 'xml'
                ],
                [
                  artifactId: 'LAST',
                  classifier: '',
                  file: "NKC_WF\\Resources\\ChangeLog.html",
                  type: 'html'
                ]
              ]
              ,credentialsId: 'bc9d8e92-4302-3266-817f-7b58501d12d5'
              ,nexusUrl: 'nexus.steamware.net'
              ,nexusVersion: 'nexus3'
              ,protocol: 'http'
              ,repository: 'SWS' 
              ,groupId: "NKC.${env.BRANCH_NAME}"
              ,version: ""
              )

              // ---------- Upload versione effettiva ----------
              publishToDeployServer("NKC_WF\\", "c:\\inetpub\\wwwroot\\SWS\\", "NKC")
              nexusArtifactUploader (
              artifacts: [                
                [
                  artifactId: 'NKC',
                  classifier: '',
                  file: "NKC_WF\\Releases\\${env.BRANCH_NAME}\\NKC.zip",
                  type: 'zip'
                ]
              ]
              ,credentialsId: 'bc9d8e92-4302-3266-817f-7b58501d12d5'
              ,nexusUrl: 'nexus.steamware.net'
              ,nexusVersion: 'nexus3'
              ,protocol: 'http'
              ,repository: 'SWS' 
              ,groupId: "NKC.${env.BRANCH_NAME}.ARCHIVE"
              ,version: "${env.versionNumber}"
            )
            },
            failFast: false)
          }
          /* preparo nuget pkg dell'SDK ma solo x branch SDK / develop */
          else if (env.BRANCH_NAME == "SDK" || env.BRANCH_NAME.contains("develop") ) { 
            // calcolo il config...
            if (env.BRANCH_NAME == "develop") {
              env.config = "Debug"
              env.packVers = env.versionNumberdevelop
            }
            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 develop(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 https://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push NKC_SDK.${env.packVers}.nupkg -Source https://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 sistemazione file PRIMA del deploy nexus/IIS
def setManifestFile(prjPath, packName) {
      echo "Richiesto esecuzione setManifestFile con parametri: " + prjPath + " | " + 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 {{VERS}} ${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'
      // salvo copia della versione...
      bat "xcopy /y " + prjPath + "\\Releases\\${env.BRANCH_NAME}\\* E:\\Staging\\byProd\\MP\\${env.BRANCH_NAME}\\" + packName + "\\${env.versionNumber}\\ "  
}

// Funzione x pubblicazione su server IIS di deploy
def publishToDeployServer(prjPath, iisPath, packName) {
      echo "Richiesto esecuzione publishToDeployServer con parametri: " + prjPath + " | " + iisPath + " | " + packName     
      // 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}\\ "      
      // 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 fix pacchetti nuget da NOSTRO repo Nexus con proxy
def fixNuget(solutionFile) {
  // bat "e:\\nuget setapikey fe387daa-d07c-3207-877e-96c8be1be91b -source https://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 https://nexus.steamware.net/repository/nuget-group -username \"nugetUser\" -password \"viaDante16\""
  }
  else
  {
    bat "e:\\nuget sources Update -Name \"Steamware Nexus\" -Source https://nexus.steamware.net/repository/nuget-group -username \"nugetUser\" -password \"viaDante16\""
  }
  bat "e:\\nuget.exe restore ${solutionFile}"
}