pipeline {
  // Declarative Pipeline MODE con  Scripted Pipeline Syntax entro le chiamate script { }
  agent none
  stages {
    stage('Checkout') {
    agent any
      steps {
      /* calcolo numero versione... diverso x branch MASTER/DEVELOP */
      script {
        env.versionNumber = VersionNumber(versionNumberString : '5.1.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILD_DATE_FORMATTED, "dHH"}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
        env.versionNumberBeta = VersionNumber(versionNumberString : '5.1.${BUILD_DATE_FORMATTED, "yyMM"}-beta.${BUILD_DATE_FORMATTED, "dHH"}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
        env.APP_NAME = 'SteamWareLib'
      }				
      script {
        currentBuild.displayName = "${env.versionNumber}"
        currentBuild.description = "BUILD ${env.versionNumber}"
      }
      // CAMBIO numero versione + checkout NuGet in file sorgente!!!
      bat "e:\\fart.exe SteamWareLib\\SteamWare.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
      //bat "e:\\nuget.exe restore ${WORKSPACE}\\SteamWare.sln"
      fixNuget("${WORKSPACE}\\SteamWare.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 SteamWareLib\\SteamWare.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
          // bat "e:\\nuget.exe restore ${WORKSPACE}\\SteamWare.sln"
          fixNuget("${WORKSPACE}\\SteamWare.sln")
        }
        script {
          parallel (
            IO: {
              sleep 3;
                // Reports lib
                bat "\"${tool 'MSBuild-16.0'}\" SteamWare.IO\\SteamWare.IO.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /verbosity:minimal /m"
            },
            LOGGER: {
              sleep 5;
                // Reports lib
                bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Logger\\SteamWare.Logger.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /verbosity:minimal /m"
            },
            MAIN_LIB: {
                // MAIN lib
                bat "\"${tool 'MSBuild-16.0'}\" SteamWareLib\\SteamWare.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /verbosity:minimal /m"
            },
            REPORTS: {
                // Reports lib
                bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Reports\\SteamWare.Reports.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /verbosity:minimal /m"
            },
            SCHEDULER: {
                // Reports lib
                bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Scheduler\\SteamWare.Scheduler.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /verbosity:minimal /m"
            },
          failFast: false)
         }			
      }	
    }
    stage('Test') {
      steps {
        echo 'Testing.. 2 be done...'
      }
    }
    stage('Deploy') {
      agent any
      steps {
        // in primis compilo a seconda del branch... TUTTO tranne develop...
        script {
          // calcolo il config...
          if (env.BRANCH_NAME == "develop") {
            env.config = "Debug"
            env.packVers = env.versionNumberBeta
          }
          else if (env.BRANCH_NAME == "master") {
            env.config = "Release"
            env.packVers = env.versionNumber
          }
          // procedo solo se NON si tratta di commit in ramo UnitTesting...
          if (env.BRANCH_NAME != "UnitTesting") {
            // elimino vecchie build...
            bat "del /f /q *.nupkg"
            // CAMBIO numero versione + checkout NuGet in file sorgente!!!
            bat "e:\\fart.exe SteamWareLib\\SteamWare.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            bat "e:\\fart.exe SteamWareLib\\SteamWare.csproj 1.0.0.0 ${env.packVers} || EXIT /B 0"
            //bat "e:\\nuget.exe restore ${WORKSPACE}\\SteamWare.sln"
            fixNuget("${WORKSPACE}\\SteamWare.sln")
            parallel (
              IO: {
                  sleep 3;
                  // BUILD Logger lib!
                  bat "\"${tool 'MSBuild-16.0'}\" SteamWare.IO\\SteamWare.IO.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /verbosity:minimal /m"
                  // creo package NuGet... con version in modo da fare ANCHE le beta
                  bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWare.IO\\SteamWare.IO.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
              },
              LOGGER: {
                  sleep 5;
                  // BUILD Logger lib!
                  bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Logger\\SteamWare.Logger.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /verbosity:minimal /m"
                  // creo package NuGet... con version in modo da fare ANCHE le beta
                  bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWare.Logger\\SteamWare.Logger.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
              },
              MAIN_LIB: {
                // BUILD!
                bat "\"${tool 'MSBuild-16.0'}\" SteamWareLib\\SteamWare.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/Release /verbosity:minimal /m"
                //bat "\"${tool 'MSBuild-16.0'}\" SteamWareLib\\SteamWare.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /verbosity:minimal /m"
                // creo package NuGet... con version in modo da fare ANCHE le beta
                bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWareLib\\SteamWare.csproj -properties Configuration=Release -Version ${env.packVers}"
              },
              REPORTS: {
                  // BUILD Reports lib!
                  bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Reports\\SteamWare.Reports.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /verbosity:minimal /m"
                  // creo package NuGet... con version in modo da fare ANCHE le beta
                  bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWare.Reports\\SteamWare.Reports.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
              },
              SCHEDULER: {
                  // BUILD Reports lib!
                  bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Scheduler\\SteamWare.Scheduler.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /verbosity:minimal /m"
                  // creo package NuGet... con version in modo da fare ANCHE le beta
                  bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWare.Scheduler\\SteamWare.Scheduler.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
              },
            failFast: false)
          }
          else
          {
            echo 'Nessun Deploy x UnitTesting'
          }
        }
        // ora mi occupo delle operazioni di invio a NEXUS...
        script {
          // se richiesta pubblicazione nuget (x develop) oppure master..
          if ((env.BRANCH_NAME == "develop" && env.publNuget == true) || (env.BRANCH_NAME == "master")) {
            // 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 SteamWare.${env.versionNumberBeta}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push SteamWare.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push SteamWare.IO.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push SteamWare.Logger.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push SteamWare.Reports.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget.exe push SteamWare.Scheduler.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
          }
        }
      }
    }
  }
  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:  "#steamware-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\""
  }
  bat "e:\\nuget.exe restore ${solutionFile}"
}