pipeline {
  // Declarative Pipeline MODE con  Scripted Pipeline Syntax entro le chiamate script { }
  agent none
  environment { 
    EMAIL_RECIPIENTS  = 'samuele@steamware.net'
    enableIIS01       = 'Y'
    enableIIS02       = 'Y'
  }
  stages {
    stage('Checkout') {
    agent any
      steps {
      /* build delle SteamWare libs! */
      /*build 'SteamWare/SteamWareLib'*/ 
      /* copio le libs...*/
      // mirroring directory x SteamWare Libs
      //bat "robocopy /MIR ..\\..\\SteamWare\\SteamWareLib ..\\SteamWare\\SteamWareLib  || EXIT /B 0"

      // step([$class: 'CopyArtifact', fingerprintArtifacts: true, projectName: 'Steamware/SteamWareLib', selector: [$class: 'WorkspaceSelector'], target: '../Steamware/SteamWareLib'])

      /* calcolo numero versione... diverso x branch MASTER/DEVELOP */
      script {
        withEnv(['NEXT_BUILD_NUMBER=377']) {
          // env.versionNumber = VersionNumber(versionNumberString : '1.3.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true)
          env.versionNumber = VersionNumber(versionNumberString : '1.3.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
            env.APP_NAME = 'B2BCONDOMINI'
        }
      }				
      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 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
      bat "e:\\nuget.exe restore ${WORKSPACE}\\B2BCONDOMINI.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 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
          bat "e:\\nuget.exe restore ${WORKSPACE}\\B2BCONDOMINI.sln"
        }
        script {
          /* compilo installers in base al BRANCH del cliente... */
          if (env.BRANCH_NAME == "develop") {
            parallel (
              ADM: {
                sleep 5
                bat "\"${tool 'MSBuild-15.0'}\" ADM/ADM.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
              },
              PUB: {
                sleep 0
                bat "\"${tool 'MSBuild-15.0'}\" PUB/PUB.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 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
          bat "e:\\nuget.exe restore ${WORKSPACE}\\B2BCONDOMINI.sln"
        }
        script {
          /* DEPLOY condizionale: develop / master / demo_ovh */
          if (env.BRANCH_NAME == "master") {
            parallel (
              PUB_IIS01: {
                if(env.enableIIS01 == "Y")
                {
                  sleep 0
                  bat "\"${tool 'MSBuild-15.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=15.0 /p:RunCodeAnalysis=false /p:Configuration=IIS01 /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ PUB/PUB.csproj"
                }
              },
              PUB_IIS02: {
                if(env.enableIIS02 == "Y")
                {
                  sleep 0
                  bat "\"${tool 'MSBuild-15.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=15.0 /p:RunCodeAnalysis=false /p:Configuration=IIS02 /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ PUB/PUB.csproj"
                }
              },
              failFast: false)
          }
          if (env.BRANCH_NAME == "OVH") { 
            parallel (
              PUB_PROD: {
                  sleep 0
                  bat "\"${tool 'MSBuild-15.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=OVH-prod.pubxml /p:VisualStudioVersion=15.0 /p:RunCodeAnalysis=false /p:Configuration=OVH /p:username=WPROD01\\Steamware /p:Password=viaD@nte16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ PUB/PUB.csproj"
              },
              failFast: false)
          }
          else {
            echo 'Nothing to deploy...'
          }
        }
      }
    }
  }
  post {
    success {
      //sendEmail("Successful")
      sendSlack("Successful", "good")
    }
    failure {
      //sendEmail("Failed")
      sendSlack("Failed", "danger")
    }
    unstable {
      //sendEmail("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 email
def sendEmail(status) {
  mail (
    to: "$EMAIL_RECIPIENTS", 
    subject: "${env.versionNumber} " + status +": Build $BUILD_NUMBER ($JOB_NAME)", 
    body: "Modifiche:\n " + getChangeString() + "\n\n Verifica console output: $BUILD_URL/console" + "\n"
  )
}

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