pipeline {
	agent {
		docker {
			image 'node:14'
		}
	}

	environment {
		GITEA_URL = 'https://code.relms.dev/NeonJS/library'
		GITEA_TOKEN = credentials('GITEA_TOKEN')
		NPM_TOKEN = credentials('NPM_TOKEN')
		DISCORD_WEBHOOK = credentials('DISCORD_WEBHOOK')
		GIT_AUTHOR_NAME = 'JenkinsCI'
		GIT_AUTHOR_EMAIL = 'jenkins@relms.dev'
		GIT_COMMITTER_NAME = 'JenkinsCI'
		GIT_COMMITTER_EMAIL = 'jenkins@relms.dev'
	}

	stages {
		stage('Checkout') {
			steps {
				script {
					echo '==========Checking out=========='
					if (sh (script: "git log -1 | grep '.*\\[ci skip\\].*'", returnStatus: true)) {
						error "'[ci skip]' found in git commit message. Aborting."
						currentBuild.result = 'NOT_BUILT'
					}
				}
			}
		}

		stage('Dependencies') {
			steps {
				echo '==========Installing Dependencies=========='
				sh 'yarn install'
			}
		}

		stage('Build') {
			steps {
				echo '==========Bundling Application=========='
				sh 'yarn build'
			}
		}

		stage('Publish') {
			steps {
				script {
					echo '==========Publishing to NPM=========='
					if (env.BRANCH_NAME == 'master') {
						echo '==========Publishing as Development Version=========='
						sh 'echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc'
						sh 'yarn version $(node -pe \'require("./package.json").version\')-$(git rev-parse HEAD).$(date +%s)'
						sh 'npm publish --tag dev --access public'
					} else if (env.BRANCH_NAME == 'stable') {
						echo '==========Publishing as Stable Version=========='
						sh 'semantic-release'
					}
				}
			}
		}
	}
	post {
		always {
			deleteDir()
			cleanWs()
		}
		success {
			sh 'tar -cf - dist/ | xz -9 -c - > neonjs-library.tar.xz'
			archiveArtifacts artifacts: 'neonjs-library.tar.xz', fingerprint: true

			discordSend	description: 'CI build was a Success',
				link: env.BUILD_URL,
				result: 'SUCCESS',
				title: env.JOB_NAME,
				webhookURL: env.DISCORD_WEBHOOK
		}
		unstable {
			sh 'tar -cf - dist/ | xz -9 -c - > neonjs-library.tar.xz'
			archiveArtifacts artifacts: 'neonjs-library.tar.xz', fingerprint: true

			discordSend description: 'CI build was Unstable.',
				link: env.BUILD_URL,
				result: 'UNSTABLE',
				title: env.JOB_NAME,
				webhookURL: env.DISCORD_WEBHOOK
		}
		failure {
			discordSend description: 'CI build has Failed.',
				link: env.BUILD_URL,
				result: 'FAILURE',
				title: env.JOB_NAME,
				webhookURL: env.DISCORD_WEBHOOK
		}
		aborted {
			discordSend description: 'CI build was Aborted',
				link: env.BUILD_URL,
				result: 'ABORTED',
				title: env.JOB_NAME,
				webhookURL: env.DISCORD_WEBHOOK
		}
	}
}