pipeline {
  agent none
  environment { 
    EMAIL_RECIPIENTS = 'samuele@steamware.net'
  }
  stages {
    stage('Checkout') {
    agent any
    steps {

      /* calcolo numero versione... diverso x branch MASTER/DEVELOP */
      script {
        withEnv(['NEXT_BUILD_NUMBER=225']) {
          // env.versionNumber = VersionNumber(versionNumberString : '2.0.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true)
          env.versionNumber = VersionNumber(versionNumberString : '2.0.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
          env.versionNumberBeta = VersionNumber(versionNumberString : '2.0.${BUILD_DATE_FORMATTED, "yyMM"}-beta.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
          env.APP_NAME = 'MConnectSDK'
        }
      }				
      script {
        currentBuild.displayName = "${env.versionNumber}"
        if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME.contains("DEMO") || env.BRANCH_NAME.contains("UnitTesting")) { 
          currentBuild.description = "TEST ${env.versionNumber}"
        }
        else {
          currentBuild.description = "BUILD ${env.versionNumber}"
        }
      }
      
      /* CAMBIO numero versione in file sorgente!!! */
      bat "e:\\fart.exe SharedAssemblyInfo.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
      }
    }
    stage('Build') {
      agent any
      steps {
        script {
          // calcolo il config...
          if (env.BRANCH_NAME == "develop") {
            env.config = "Debug"
          }
          else if (env.BRANCH_NAME == "master") {
            env.config = "Release"
          }

          // compilo installers in base al BRANCH...
          if (env.BRANCH_NAME == "develop" || env.BRANCH_NAME == "master") {
            // CAMBIO numero versione in file sorgente!!!
            bat "e:\\fart.exe SharedAssemblyInfo.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            // restore nuget packages
            bat "e:\\nuget.exe restore ${WORKSPACE}\\MConnect.sln"
            // BUILD Develop (della sola libreria)!
            bat "\"${tool 'MSBuild-16.0'}\" MConnectSDK/MConnectSDK.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"x86\" /p:OutputPath=bin/${env.config}/ /m"
          }
          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 {
        // 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
            env.classifier = ""
          }
          else if (env.BRANCH_NAME == "master") {
            env.config = "Release"
            env.packVers = env.versionNumber
            env.classifier = ""
          }
          // procedo solo se NON si tratta di commit in ramo UnitTesting...
          if (env.BRANCH_NAME != "UnitTesting") {
            // CAMBIO numero versione in file sorgente!!!
            bat "e:\\fart.exe SharedAssemblyInfo.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            // restore nuget packages
            bat "e:\\nuget.exe restore ${WORKSPACE}\\MConnect.sln"
            // BUILD!
            bat "\"${tool 'MSBuild-16.0'}\" MConnectSDK/MConnectSDK.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"x86\" /p:OutputPath=bin/${env.config} /m"
            // creo package NuGet...
            bat "e:\\nuget.exe pack ${WORKSPACE}\\MConnectSDK\\MConnectSDK.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
          }
          else
          {
            echo 'Nessun Deploy x UnitTesting'
          }
        }
        // ora mi occupo delle operazioni di invio a NEXUS...
        script {
          if (env.BRANCH_NAME == "develop") {
            // 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 MConnectSDK.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
            // bat "e:\\nuget.exe  push MConnectSDK.${env.versionNumber}.nupkg fe387daa-d07c-3207-877e-96c8be1be91ba -Source http://nexus.steamware.net/repository/nuget-hosted"
            bat "e:\\nuget setapikey 065e6ea1-db11-3ded-a77e-be1a689c8d1a -source https://repository.scmgroup.com/repository/mconnect-nuget"
            bat "e:\\nuget.exe  push MConnectSDK.${env.packVers}.nupkg -Source https://repository.scmgroup.com/repository/mconnect-nuget"
          }
          else if (env.BRANCH_NAME == "master") {
            // lancio upload con nuget!
            echo 'Start upload with nuget push'
            bat "e:\\nuget setapikey 065e6ea1-db11-3ded-a77e-be1a689c8d1a -source https://repository.scmgroup.com/repository/mconnect-nuget"
            bat "e:\\nuget.exe  push MConnectSDK.${env.packVers}.nupkg -Source https://repository.scmgroup.com/repository/mconnect-nuget"
            // bat "e:\\nuget.exe  push MConnectSDK.${env.versionNumber}.nupkg 065e6ea1-db11-3ded-a77e-be1a689c8d1a -Source https://repository.scmgroup.com/repository/mconnect-nuget"
          }
        }
      }
    }
  }
  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 sendEmail(status) {
 mail (
 to: "$EMAIL_RECIPIENTS", 
 subject: "Build $BUILD_NUMBER - " + status + " ($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:  "#MConnectSDK-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"
  )
}
