pipeline {

	environment {

		NGINX_DIR = '/home/nginx'
		NGINX_CONTENT_DIR = "${NGINX_DIR}/cv.kamil.zuk.00x097.com"

		NGINX_USER_ID = 1001
		NGINX_GROUP_ID = 1001

		JENKINS_REPO_CV_DIR = "${JENKINS_AGENT_WORKDIR}/curriculum.vitae"

		JENKINS_USER_ID = 1000
		JENKINS_GROUP_ID = 1000

		NPM_LOGS_DIR = "/root/.npm/_logs"

	}

	triggers {

		GenericTrigger(

			genericVariables: [
                [
					key: 'DATA_SOURCE_BRANCH',
					value: '$.DATA_SOURCE_BRANCH'
				],
			],
			token: 'dbeds56e-183f-4g43-b90a-637130d4d8e4'
		)
	}

	agent {
		kubernetes {
		    yaml """
apiVersion: v1
kind: Pod
metadata:
  name: jenkins-agent
  namespace: default
spec:
  containers:
  - name: jenkins-agent-nodejs
    image: node:14.15.4
    command: ["/bin/bash", "-c"]
    args: ["sleep 999d"]
    tty: true
    volumeMounts:
    - mountPath: /home/nginx
      name: content
  volumes:
  - name: content
    persistentVolumeClaim:
      claimName: pvc-nginx
            """
		}
	}

	stages {

		stage('Setup Parameters') {

			steps {

				script {

					properties([
				        parameters([
							string(
						        defaultValue: 'master',
								description: 'Select <b>CV</b> data source branch for the build & deploy',
								name: 'DATA_SOURCE_BRANCH'
						    )
						])
				    ])
				}
			}
		}

		stage('Setup Container Environment') {

			steps {

				container('jenkins-agent-nodejs') {

					echo """
						Setup Container Environment
					"""

					sh """
						getent group
					"""

					sh """
						getent passwd
					"""

					sh """
						if [ \$(getent group | grep ${JENKINS_GROUP_ID}) ]; then
							groupdel -f \$(getent passwd | grep ${JENKINS_USER_ID} | cut -d: -f1);
							groupadd -g ${JENKINS_GROUP_ID} jenkins;
						else
							groupadd -g ${JENKINS_GROUP_ID} jenkins;
						fi
					"""

					sh """
						if [ \$(getent passwd | grep ${JENKINS_USER_ID}) ]; then
							userdel \$(getent passwd | grep ${JENKINS_USER_ID} | cut -d: -f1);
							useradd -u ${JENKINS_USER_ID} -g ${JENKINS_GROUP_ID} jenkins;
						else
							useradd -u ${JENKINS_USER_ID} -g ${JENKINS_GROUP_ID} jenkins;
						fi
					"""

					sh """
						if [ ! -d ${JENKINS_REPO_CV_DIR} ]; then
							mkdir -p ${JENKINS_REPO_CV_DIR};
						fi
					"""

					sh """
						chown jenkins:jenkins -R ${JENKINS_AGENT_WORKDIR};
					"""

				}
			}
		}

		stage('Fetch App') {

			steps {

				container('jenkins-agent-nodejs') {

					echo """
						Fetch App
					"""

					sh """
						git config --global --add safe.directory '*';
					"""

					dir("${JENKINS_REPO_CV_DIR}") {

						git	credentialsId: 'git-gitea-tbs093a',
							branch: "${DATA_SOURCE_BRANCH}",
							url: "https://git.00x097.com/tbs093a/curriculum.vitae.git"

						sh """
							ls -la
						"""
					}
				}
			}
		}

		stage('Build App') {

			steps {

				container('jenkins-agent-nodejs') {

					echo """
						Build App
					"""

                    catchError(
						buildResult: 'FAILURE',
						stageResult: 'FAILURE'
					) {

						dir("${JENKINS_REPO_CV_DIR}") {	

							sh """
								npm install;
								npm run build;
							"""

							sh """
								ls -la
							"""
						}
					}
				}
			}
		}

		stage('Load Build Logs') {

			steps {

				container('jenkins-agent-nodejs') {

					echo """
						Load Build Logs
					"""

					catchError(
						buildResult: 'SUCCESS',
						stageResult: 'UNSTABLE'
					) {

						dir("${JENKINS_REPO_CV_DIR}") {

							sh """
								if [ -d ${NPM_LOGS_DIR} ]; then
									if [ "\$(ls -1 ${NPM_LOGS_DIR} | wc -l)" != "0" ]; then
										cat "${NPM_LOGS_DIR}/\$(ls -rt ${NPM_LOGS_DIR} | tail -n1)"
									else
										echo "No NPM logs found";
										exit 1;
									fi
								fi
							"""
						}
					}
				}
			}
		}

		stage('Move Static Files To Nginx Persistent Volume') {

			steps {

				container('jenkins-agent-nodejs') {

					echo """
						Deploy App
					"""

					catchError(
						buildResult: 'FAILURE',
						stageResult: 'FAILURE'
					) {

						dir("${JENKINS_REPO_CV_DIR}") {

							sh """
								if [ -d ./public ]; then
									echo "Static files found in ./public";
									if [ -d ${NGINX_CONTENT_DIR} ]; then
										rm -r ${NGINX_CONTENT_DIR};
									fi
									mkdir -p ${NGINX_CONTENT_DIR};
									chown ${NGINX_USER_ID}:${NGINX_GROUP_ID} -R ${NGINX_DIR};
									mv ./public/* ${NGINX_CONTENT_DIR}/;
									exit 0;
								else
									echo "No static files found in ./public";
									exit 1;
								fi
							"""
						}
					}
				}
			}
		}
	}
}

