pipeline {
	agent any
	options {
		disableConcurrentBuilds()
		skipDefaultCheckout(true)
	}
	environment {
		DEPLOY_NAMESPACE = "staging"
		PIPELINE_BOT_EMAIL = "pharos.bot@gmail.com"
		PIPELINE_BOT_NAME = "Pipeline Bot"
		PIPELINE_NAME = "Innopharm - White Panther Staging"

		PROJECT_NAME = "${params.PROJECT_NAME}"
		PROJECT_VERSION = "${params.PROJECT_VERSION}"
		PROJECT_URL = "${params.PROJECT_URL}"

		CHART_ORG = "innopharm"
		
		DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/1394949302438068264/Czf1hreOZwtqhOq6oDFFH1xsq5_I2Fop8Gwn-hAjZoly9HEYWPjDWwRins1kr2Op5Td4"
	}
	stages {
		stage('Checkout SCM') {
			steps {
				checkout scm 
			}
		}
		stage('Update Chart') {
			steps {
				script {
					try {
						if (env.PROJECT_NAME != null && env.PROJECT_VERSION != null) {
							sh "chart-dependency-updater --p ${env.PROJECT_NAME} --v ${env.PROJECT_VERSION} --r http://chartmuseum:8080/${env.CHART_ORG} --c env/Chart.yaml"
							withCredentials([gitUsernamePassword(credentialsId: 'gitlab-pipeline-bot', gitToolName: 'git-tool')]) {
								sh "git config user.email '${env.PIPELINE_BOT_EMAIL}'"
								sh "git config user.name '${env.PIPELINE_BOT_NAME}'"
								sh "git add env/Chart.yaml"
								sh "git commit -m 'Bump ${env.PROJECT_NAME} version to ${env.PROJECT_VERSION}'"
								sh "git push origin HEAD:master"
							}
						} 
					} catch (Exception e) {
						echo '> Exception occured: ' + e.toString()
					} 
				}
			}
		}
		stage('Setup Discord Notifications') {
			steps {
				script {
					env.DISCORD_DESC = sh (
						script: "discord-desc-setup",
						returnStdout: true
					).trim()
				}
			}
		}
		stage('Validate Environment') {
			steps {
				sh 'make pull'
			}
		}
		stage('Apply Environment Configurations') {
			steps {
				sh 'make install-independent'
			}
		}
	}
	post {
		success {
			discordSend link: env.BUILD_URL, 
            result: currentBuild.currentResult, 
            title: "${env.PIPELINE_NAME} #${env.BUILD_NUMBER}", 
            webhookURL: env.DISCORD_WEBHOOK_URL,
            description: env.DISCORD_DESC,
            footer: "Tags: v${env.PROJECT_VERSION}"
			sh "exit 0"
		}
		regression {
			discordSend link: env.BUILD_URL, 
            result: currentBuild.currentResult, 
            title: "${env.PIPELINE_NAME} #${env.BUILD_NUMBER}", 
            webhookURL: env.DISCORD_WEBHOOK_URL,
            description: env.DISCORD_DESC,
            footer: "Tags: v${env.PROJECT_VERSION}",
			notes: "Error nih boss <@&712203287096459326>"
			sh "exit 1"
		}
	}
}
