pipeline {
  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 : '3.5.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILD_DATE_FORMATTED, "ddHH"}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
        env.APP_NAME = 'MAPO-IOB-WIN'
      }
      script {
        currentBuild.displayName = "${env.versionNumber}"
        if (env.BRANCH_NAME == "master") { 
          currentBuild.description = "BUILD ${env.versionNumber}"
        }
        else {
          currentBuild.description = "TEST ${env.versionNumber}"
        }
      }
      /* CAMBIO numero versione in file sorgente!!! */
      bat "e:\\fart.exe VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
      }
    }
    stage('Build') {
      agent any
      steps {
        // fix vers numb + pacchetti nuget
        script {
          // CAMBIO numero versione in file sorgente!!!
          bat "e:\\fart.exe VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
          // checkout NuGet in file sorgente!!!
          fixNuget("${WORKSPACE}\\IOB-MAN.sln")
          fixNuget("${WORKSPACE}\\IOB-WIN-NEXT.sln")
        }
        script {
          if (env.BRANCH_NAME == "develop") {
            parallel (
              IOB_WIN: {
                // BUILD!
                bat "\"${tool 'MSBuild-16.0'}\" IOB-MAN/IOB-MAN.csproj -target:Build /p:Configuration=Release /p:Platform=\"x86\" /p:OutputPath=bin/ /verbosity:minimal /m"
                bat "\"${tool 'MSBuild-16.0'}\" IOB-WIN-NEXT/IOB-WIN-NEXT.csproj -target:Build /p:Configuration=Release /p:Platform=\"x86\" /p:OutputPath=bin/ /verbosity:minimal /m"
              },
              // IOB_MAN: {
              //   // BUILD!
              //   bat "\"${tool 'MSBuild-16.0'}\" IOB-MAN/IOB-MAN.csproj -target:Build /p:Configuration=Release /p:Platform=\"x86\" /p:OutputPath=bin/ /verbosity:minimal /m" 
              // },
              failFast: false
            )
          }
          else {
            echo 'NON faccio test di Build se non per BRANCH develop'
          }	
        }			
      }
    }
    stage('Test') {
      steps {
        echo 'Testing.. 2 be done...'
      }
    }
    stage('Deploy') {
      agent any
      steps {
        // fix vers numb + pacchetti nuget
        script {
          // CAMBIO numero versione in file sorgente!!!
          bat "e:\\fart.exe VersGen\\VersGen.cs 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
          // checkout NuGet in file sorgente!!!
          fixNuget("${WORKSPACE}\\IOB-MAN.sln")
          fixNuget("${WORKSPACE}\\IOB-WIN-NEXT.sln")
        }
        // a seconda del branch decido cosa e come compilare e caricare...
        script {
          if(env.BRANCH_NAME == "IobMan") {   
            // BUILD!
            bat "\"${tool 'MSBuild-16.0'}\" IOB-MAN/IOB-MAN.csproj -target:Build /p:Configuration=Release /p:Platform=\"x86\" /p:OutputPath=bin/ /verbosity:minimal /m"
          }
          // procedo solo se NON si tratta di commit in ramo DOCUMentazione...
          else if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME.contains("master") ) {
            // BUILD!
            bat "\"${tool 'MSBuild-16.0'}\" IOB-MAN/IOB-MAN.csproj -target:Build /p:Configuration=Release /p:Platform=\"x86\" /p:OutputPath=bin/ /verbosity:minimal /m"
            bat "\"${tool 'MSBuild-16.0'}\" IOB-WIN-NEXT/IOB-WIN-NEXT.csproj -target:Build /p:Configuration=Release /p:Platform=\"x86\" /p:OutputPath=bin/ /verbosity:minimal /m"
          }
          else
          {
            echo 'Nessun Deploy necessario'
          }
        }
        // ora mi occupo delle operazioni di compressione e copia...
        script {
          // // se è ramo IobMan compilo SOLO IOB-MAN...
          // if(env.BRANCH_NAME == "IobMan") {      
          //   env.classifier = ""   
          //   // rimuovo vecchio zip...
          //   bat "del /f ${WORKSPACE}\\Releases\\${env.BRANCH_NAME}\\*.zip || EXIT /B 0"   
          //   // Compressione in .zip dell'installer...
          //   bat "e:\\7za.exe a -tzip ${WORKSPACE}\\Releases\\${env.BRANCH_NAME}\\MAPO-IOB-MAN.zip ${WORKSPACE}\\IOB-MAN\\bin\\*"
          //   // ora mi occupo delle operazioni di invio a NEXUS...
          //   nexusArtifactUploader(
          //     nexusVersion: 'nexus3',
          //     protocol: 'https',
          //     nexusUrl: 'nexus.steamware.net',
          //     groupId: 'MAPO',
          //     //version: "${env.versionNumber}",
          //     version: "stable",
          //     repository: 'utility',
          //     credentialsId: 'bc9d8e92-4302-3266-817f-7b58501d12d5',
          //     artifacts: [
          //         [artifactId: 'IOB-MAN',
          //         classifier: "${env.classifier}",
          //         file: "Releases\\${env.BRANCH_NAME}\\MAPO-IOB-MAN.zip",
          //         type: 'zip']
          //     ]
          //   )
          // }
          // ...
          // else if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME.contains("master") || env.BRANCH_NAME.contains("feature") ) {
          if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME.contains("master") ) {
            fixResources("IOB-MAN")
            fixResources("IOB-WIN-NEXT")

            // elimino vecchio zip...
            bat "RD /S /Q Releases\\${env.BRANCH_NAME}\\ || EXIT /B 0"

            compressZip("IOB-MAN")
            compressZip("IOB-WIN-NEXT")

            // fix classificazione x develop/master...
            if (env.BRANCH_NAME == "develop")
            {
              // env.classifier = "unstable"   
              env.version = "unstable"
            }
            else
            {
              // env.classifier = ""  
              env.version = "stable" 
            }
            // ora mi occupo delle operazioni di invio a NEXUS...
            nexusArtifactUploader(
              nexusVersion: 'nexus3',
              protocol: 'https',
              nexusUrl: 'nexus.steamware.net',
              groupId: 'MAPO',
              //version: "${env.versionNumber}",
              version: "${env.version}",
              repository: 'utility',
              credentialsId: 'bc9d8e92-4302-3266-817f-7b58501d12d5',
              artifacts: [
                  // [artifactId: 'IOB-WIN',
                  // classifier: "",
                  // // classifier: "${env.classifier}",
                  // file: "Releases\\${env.BRANCH_NAME}\\MAPO-IOB-WIN.zip",
                  // type: 'zip'],
                   [artifactId: 'IOB-MAN',
                  classifier: "${env.classifier}",
                  file: "Releases\\${env.BRANCH_NAME}\\MAPO-IOB-MAN.zip",
                  type: 'zip'],
                  [artifactId: 'IOB-WIN-NEXT',
                  classifier: "",
                  // classifier: "${env.classifier}",
                  file: "Releases\\${env.BRANCH_NAME}\\MAPO-IOB-WIN-NEXT.zip",
                  type: 'zip']
              ]
            )
          }
          else
          {
            echo 'Nessuna compressione+copia post deploy'
          }
        }
      }
    }
  }
  post {
    success {
      sendSlack("Successful", "good")
    }
    failure {
      sendSlack("Failed", "danger")
    }
    unstable {
      sendSlack("Unstable", "warning")
    }
  }
}

@NonCPS
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
}

def fixResources(basePath){
  echo "Start fixResources for ${basePath}"
  def now = new Date()
  def anno = now.format("yyyy", TimeZone.getTimeZone('UTC'))

  // elimino files conf personalizzata per ogni install...
  bat "RD /S /Q ${basePath}\\bin\\DATA || EXIT /B 0"
  // manifest.xml: aggiorno versNumber ed URL del branch di update...
  bat "e:\\fart.exe ${basePath}\\Resources\\manifest.xml 0.0.0.0 ${env.versionNumber} || EXIT /B 0"
  bat "e:\\fart.exe ${basePath}\\Resources\\manifest.xml {{BRANCHNAME}} ${env.BRANCH_NAME} || EXIT /B 0"
  bat "e:\\fart.exe ${basePath}\\Resources\\ChangeLog.html {{CURRENT-REL}} ${env.versionNumber} || EXIT /B 0" 
  bat "e:\\fart.exe ${basePath}\\Resources\\ChangeLog.html {{CURR-YEAR}} ${anno} || EXIT /B 0" 
  
  // // copio ed esporto in IIS02 i vari files .xml, .html, .zip
  // powershell "(Get-Content ${basePath}\\Resources\\ChangeLog.html) | ForEach-Object { $_ -replace \"{{LAST-CHANGES}}\", \"${getChangeString()}\" } | Set-Content ${basePath}\\Resources\\ChangeLog.html"

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

  // elimino files inutili di resources e pubblico
  bat "RD /S /Q ${basePath}\\Resources || EXIT /B 0"
}

def compressZip(basePath){
  // Compressione in .zip dell'installer...
  bat "e:\\7za.exe a -tzip ${WORKSPACE}\\Releases\\${env.BRANCH_NAME}\\MAPO-${basePath}.zip ${WORKSPACE}\\${basePath}\\bin\\*"
  // salvo copia della versione in staging...
  bat "xcopy /y Releases\\${env.BRANCH_NAME}\\MAPO-${basePath}.zip E:\\Staging\\byProd\\MP\\${env.BRANCH_NAME}\\${basePath}\\${env.versionNumber}\\ " 
  // copio in area WebDeploy
  bat "xcopy /y Releases\\${env.BRANCH_NAME}\\MAPO-${basePath}.zip c:\\inetpub\\wwwroot\\SWS\\MAPO\\${basePath}\\${env.BRANCH_NAME}\\ "
}

// Funzione x invio slack
def sendSlack(status, colorCode) {
  slackSend (
    color:    colorCode, 
    channel:  "#mapo-dev",
    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}"
}