pipeline {
  agent none
  environment { 
    EMAIL_RECIPIENTS = 'samuele@steamware.net'
    enableIIS01       = 'Y'
    enableIIS02       = 'Y'
  }
  stages {
    stage('Checkout') {
			agent any
      steps {
				/* calcolo numero versione... diverso x branch MASTER/DEVELOP */
				script {
					withEnv(['NEXT_BUILD_NUMBER=262']) {
						// env.versionNumber = VersionNumber(versionNumberString : '1.8.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true)
						env.versionNumber = VersionNumber(versionNumberString : '1.8.${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"
						bat "e:\\nuget.exe restore ${WORKSPACE}\\XPS_app.sln"
						parallel (
							XPS: {
								sleep 0
								bat "\"${tool 'MSBuild-15.0'}\" XPS/XPS.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
							},
							XPST: {
								sleep 0
								bat "\"${tool 'MSBuild-15.0'}\" XPST/XPST.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 / master */
					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"
						bat "e:\\nuget.exe restore ${WORKSPACE}\\XPS_app.sln"
						parallel (
							XPS: {
                if(env.enableIIS01 == "Y")
                {
								  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=Release /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ XPS/XPS.csproj"
                }
                if(env.enableIIS02 == "Y")
                {
								  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=Release /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ XPS/XPS.csproj"
                }
							},
							XPST: {
                if(env.enableIIS01 == "Y")
                {
								  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=Release /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ XPST/XPST.csproj"
                }
                if(env.enableIIS02 == "Y")
                {
								  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=Release /p:username=jenkins /p:Password=viadante16 /p:AllowUntrustedCertificate=true /p:OutputPath=bin/ XPST/XPST.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"
						bat "e:\\nuget.exe restore ${WORKSPACE}\\XPS_app.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 (
              XPS_ZIP: {   
                sleep 0           
                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}/XPS.zip /p:DeployIisAppPath=\"Default Web Site/XPS\" /p:PackageAsSingleFile=True /p:OutputPath=bin/ XPS/XPS.csproj"
                // pubblico su server deploy!
                publishToDeployServer("XPS\\", "c:\\inetpub\\wwwroot\\SWS\\", "XPS")
              },
                XPST_ZIP: {  
                sleep 2            
                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}/XPST.zip /p:DeployIisAppPath=\"Default Web Site/XPST\" /p:PackageAsSingleFile=True /p:OutputPath=bin/ XPST/XPST.csproj"
                // pubblico su server deploy!
                publishToDeployServer("XPST\\", "c:\\inetpub\\wwwroot\\SWS\\", "XPST")
              },
            failFast: false)
          }
        }
      }
    }
  }
  post {
    success {
      sendEmail("Successful")
    }
    failure {
      sendEmail("Failed")
    }
    unstable {
      sendEmail("Unstable")
    }
  }
}

// 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 email
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")
}
