#!/usr/bin/env groovy

pipeline {
    agent any
    environment {
        PROJECT_NAME = 'hedera-web'
        STACK_NAME   = "${env.PROJECT_NAME}-${env.BRANCH_NAME}"
    }
    stages {
        stage('Checkout') {
            steps {
                script {
                    def packageJson = readJSON file: 'package.json'
                    env.VERSION = packageJson.version

                    switch (env.BRANCH_NAME) {
                        case 'master':
                            env.NODE_ENV = 'production'
                            env.MAIN_REPLICAS = 3
                            env.CRON_REPLICAS = 1
                            break
                        case 'test':
                            env.NODE_ENV = 'test'
                            env.MAIN_REPLICAS = 1
                            env.CRON_REPLICAS = 0
                            break
                    }
                }
                setEnv()
            }
        }
        stage('Debuild') {
            when {
                anyOf {
                    branch 'master'
                    branch 'test'
                }
            }
            agent {
                docker {
                    image 'registry.verdnatura.es/debuild:2.23.4-vn1'
                    registryUrl 'https://registry.verdnatura.es/'
                    registryCredentialsId 'docker-registry'
                    args '-v /mnt/appdata/reprepro:/reprepro'
                }
            }
            steps {
                sh 'debuild -us -uc -b'
                sh 'vn-includedeb bookworm'
            }
        }
        stage('Container') {
            when {
                anyOf {
                    branch 'master'
                    branch 'test'
                }
            }
            environment {
                CREDS = credentials('docker-registry')
            }
            steps {
                sh 'docker login --username $CREDS_USR --password $CREDS_PSW $REGISTRY'
                sh 'docker-compose build --build-arg BUILD_ID=$BUILD_ID --parallel'
                sh 'docker-compose push'
            }
        }
        stage('Deploy') {
            when {
                anyOf {
                    branch 'master'
                    branch 'test'
                }
            }
            environment {
                DOCKER_HOST = "${env.SWARM_HOST}"
            }
            steps {
                sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}"
            }
        }
    }
    post {
        unsuccessful {
            sendEmail()
        }
    }
}
