pipeline {
    agent any

    environment {
        DOCKER_IMAGE = 'jassimsm/documentation'
        DOCKER_TAG = 'latest'
        REGISTRY_CREDENTIALS = 'docker-credentials'
        SSH_CREDENTIALS = 'documentation'
    }

    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://git.tech4biz.wiki/jassim/cicid.git'
            }
        }

        stage('Install Dependencies') {
            steps {
                sh 'yarn install'
            }
        }

        stage('Build Documentation') {
            steps {
                sh 'yarn build'
            }
        }

        stage('Build Docker Image') {   
            steps {
                script {
                    docker.build("${DOCKER_IMAGE}:${DOCKER_TAG}")
                }
            }
        }

        stage('Push Docker Image') {
            steps {
                script {
                    docker.withRegistry('https://index.docker.io/v1/', REGISTRY_CREDENTIALS) {
                        docker.image("${DOCKER_IMAGE}:${DOCKER_TAG}").push()
                    }
                }
            }
        }

        stage('Deploy') {
            steps {
                script {
                    sshagent(credentials: [SSH_CREDENTIALS]) {
                        sh '''
                        ssh user@160.187.166.47 << EOF
                        docker pull ${DOCKER_IMAGE}:${DOCKER_TAG}
                        docker documentation-container || true
                        docker rm documentation-container || true
                        docker run -d -p 3000:3000 --name documentation-container ${DOCKER_IMAGE}:${DOCKER_TAG}
                        EOF
                        '''
                    }
                }
            }
        }

        stage('Update Nginx Configuration') {
            steps {
                script {
                    sshagent(credentials: [SSH_CREDENTIALS]) {
                        sh '''
                        ssh user@160.187.166.47 << EOF
                        sudo nginx -t
                        sudo systemctl reload nginx
                        EOF
                        '''
                    }
                }
            }   
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}
