pipeline {
  agent none
  environment { 
    EMAIL_RECIPIENTS = 'samuele@steamware.net'
  }
  stages {
    stage('Checkout') {
			agent any
      steps {
				/* build delle SteamWare libs! */
				/*build 'SteamWare/SteamWareLib'*/ 
				/* copio le libs...*/
				// 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=4273']) {
						// env.versionNumber = VersionNumber(versionNumberString : '3.3.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true)
						env.versionNumber = VersionNumber(versionNumberString : '3.3.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
    					env.APP_NAME = 'CMS-SC'
					}
				}				
				script {
					currentBuild.displayName = "${env.versionNumber}"
					if (env.BRANCH_NAME == "develop") { 
						currentBuild.description = "TEST ${env.versionNumber}"
					}
					else {
						currentBuild.description = "BUILD ${env.versionNumber}"
					}
				}				
				/* CAMBIO numero versione in file sorgente!!! */
				bat "e:\\fart.exe ${WORKSPACE}\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
      }
    }
		stage('Build') {
			agent any
			steps {
				script {
					/* compilo tutti i progetti compresi... */
					if (env.BRANCH_NAME == "develop") {
						/* CAMBIO numero versione in file sorgente!!! */
						bat "e:\\fart.exe ${WORKSPACE}\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            // checkout NuGet in file sorgente!!!
            fixNuget("${WORKSPACE}\\CMS-SC.sln")
						parallel (
							REL: {
								sleep 0
								bat "\"${tool 'MSBuild-15.0'}\" CMS_SC/CMS_SC.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
							},
							failFast: false)
						}
					else {
						echo 'Nothing to Build...'
					}	
				}			
			}	
    }
		stage('Test') {
			steps {
                echo 'Testing.. 2 be done...'
			}
		}
		stage('Deploy') {
			agent any
			steps {
				script {
					/* DEPLOY condizionale: develop --> IIS01 / master --> IIS02 */
					if (env.BRANCH_NAME == "develop") { 
						/* CAMBIO numero versione in file sorgente!!! */
						bat "e:\\fart.exe ${WORKSPACE}\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            // checkout NuGet in file sorgente!!!
            fixNuget("${WORKSPACE}\\CMS-SC.sln")
						parallel (
							IIS01: {
								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=14.0 /p:RunCodeAnalysis=false /p:Configuration=IIS01 /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ CMS_SC/CMS_SC.csproj"
							},
							failFast: false)
					}
          else if (env.BRANCH_NAME == "master") { 
						/* CAMBIO numero versione in file sorgente!!! */
						bat "e:\\fart.exe ${WORKSPACE}\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            // checkout NuGet in file sorgente!!!
            fixNuget("${WORKSPACE}\\CMS-SC.sln")
						parallel (
							IIS02: {
								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=14.0 /p:RunCodeAnalysis=false /p:Configuration=IIS02 /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ CMS_SC/CMS_SC.csproj"
							},
							failFast: false)
					}
					else {
						echo 'Nothing to deploy...'
					}
				}
			}
		}
    stage('Installers') {
      agent any
      steps {
        // in primis cambio versione e NuGet
        script {
          // CAMBIO numero versione + checkout NuGet in file sorgente!!!
						bat "e:\\fart.exe ${WORKSPACE}\\VersGen\\VersGen.cs 1.0.0.0 ${env.versionNumber} || EXIT /B 0"
            // checkout NuGet in file sorgente!!!
            fixNuget("${WORKSPACE}\\CMS-SC.sln")
        }
        // ora mi occupo delle operazioni di compressione e copia...
        script {
            /* compilo installers in base al BRANCH del cliente... */
          if (env.BRANCH_NAME == "master" || env.BRANCH_NAME.contains("develop")) { 
            echo 'Questo BRANCH non necessita di installer...'
          }
          else
          {
            parallel (
            CMS_SC_ZIP: {              
              bat "\"${tool 'MSBuild-15.0'}\" \"/p:AspnetMergePath=C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.2 Tools\" /T:Package /P:Configuration=${env.BRANCH_NAME} /p:PublishProfile=${env.BRANCH_NAME}.pubxml /p:VisualStudioVersion=14.0 /p:RunCodeAnalysis=false /p:PackageLocation=ReleaseClienti/${env.BRANCH_NAME}/CMS_SC.zip /p:DeployIisAppPath=\"Default Web Site/CMS-SC\" /p:PackageAsSingleFile=True /p:OutputPath=bin/ CMS_SC/CMS_SC.csproj"

              // // SOLO se è tra i branch "cliente" pubblico in dropbox...
              // if (env.BRANCH_NAME == "Donati") {
              //   bat "E:\\Jenkins\\exportDropbox.bat \"${WORKSPACE}\\MP\\ReleaseClienti\\Donati\" \"E:\\Staging\\byProd\\MP\\Donati\\MP-LAND\" "
              //   // dropbox configName: 'Donati', remoteDirectory: 'installers/MP-LAND', removePrefix: 'ReleaseClienti/Donati', sourceFiles: 'ReleaseClienti/Donati/**'
              // }

              // pubblico su server deploy!
              publishToDeployServer("CMS_SC\\", "c:\\inetpub\\wwwroot\\SWS\\", "CMS_SC")
            },
            failFast: false)
          }
        }
      }
    }
  }
  post {
    success {
      sendSlack("Successful", "good")
    }
    failure {
      sendSlack("Failed", "danger")
    }
    unstable {
      sendSlack("Unstable", "warning")
    }
  }
}

// Funzione x pubblicazione su server IIS di deploy
def publishToDeployServer(prjPath, iisPath, packName) {
      echo "Richiesto esecuzione publishToDeployServer con parametri: " + prjPath + " | " + iisPath + " | " + 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 1.0.0.0 ${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'
      // 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}\\ "
      // salvo copia della versione...
      bat "xcopy /y " + prjPath + "\\ReleaseClienti\\${env.BRANCH_NAME}\\* E:\\Staging\\byProd\\" + prjPath + "${env.BRANCH_NAME}\\" + packName + "\\${env.versionNumber}\\ "  
      // copio x AutoUpdate deploy
      bat "xcopy /y " + prjPath + "\\ReleaseClienti\\${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:  "#ctrack-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}"
}