pipeline {
    environment {
        WORKDIR = 'dockerfiles/services/gitea'
        DOCKER_HOST = 'dkhost:2376'
    }

    agent { label 'docker' }
    options {
        buildDiscarder(logRotator(numToKeepStr: '2'))
    }
    triggers {
        cron('@weekly')
    }

    stages {
        stage('prepare') {
            steps {
                checkout scm
                sh 'ls'
            }
        }

        stage('build') {
            steps {
                dir(WORKDIR) {
                    sh "DOCKER_HOST=${DOCKER_HOST} docker-compose -f docker-compose.yml pull"
                }
            }
        }

        stage('deploy') {
            steps {
                dir(WORKDIR) {
                    sh """
                        export DOCKER_HOST=${DOCKER_HOST}
                        docker stack deploy --with-registry-auth --prune -c docker-compose.yml gitea
                        (cd ../ && chmod +x ./scaleout.sh && ./scaleout.sh gitea_app 180)
                    """
                }
            }
        }

        stage('smoke tests') {
            steps {
                dir(WORKDIR) {
                    sleep 60
                    sh "curl -If http://dkhost:10080"
                }
            }
            post {
                failure {
                    dir(WORKDIR) {
                        sh """
                            export DOCKER_HOST=${DOCKER_HOST}
                            docker service rollback gitea_app
                        """
                    }
                }
            }
        }

    }
}
