#!/usr/bin/env groovy
pipeline {
    agent any
    options {
        disableConcurrentBuilds()
    }
    environment {
        PROJECT_NAME = 'lilium'
        STACK_NAME   = "${env.PROJECT_NAME}-${env.BRANCH_NAME}"
    }
    stages {
        stage('Checkout') {
            steps {
                script {
                    switch (env.BRANCH_NAME) {
                        case 'master':
                            env.NODE_ENV = 'production'
                            env.FRONT_REPLICAS = 2
                            break
                        case 'test':
                            env.NODE_ENV = 'test'
                            env.FRONT_REPLICAS = 1
                            break
                    }
                }
                setEnv()
            }
        }
        stage('Install') {
            environment {
                NODE_ENV = ""
            }
            steps {
                nodejs('node-v18') {
                    sh 'npm install --no-audit --prefer-offline'
                }
            }
        }
        stage('Test') {
            when { not { anyOf {
                branch 'test'
                branch 'master'
            }}}
            environment {
                NODE_ENV = ""
            }
            parallel {
                stage('Frontend') {
                    steps {
                        nodejs('node-v18') {
                            sh 'npm run test:unit:ci'
                        }
                    }
                }
            }
        }
        stage('Build') {
            when { anyOf {
                branch 'test'
                branch 'master'
            }}
            environment {
                CREDENTIALS = credentials('docker-registry')
            }
            steps {
                nodejs('node-v18') {
                    sh 'quasar build'
                }
                dockerBuild()
            }
        }
        stage('Deploy') {
            when { anyOf {
                branch 'test'
                branch 'master'
            }}
            environment {
                DOCKER_HOST = "${env.SWARM_HOST}"
            }
            steps {
                sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
            }
        }
    }
    post {
        always {
            script {
                if (!['master', 'test'].contains(env.BRANCH_NAME)) {
                    try {
                        junit 'junitresults.xml'
                        junit 'junit.xml'
                    } catch (e) {
                        echo e.toString()
                    }
                }
            }
        }
    }
}