pipeline{
    agent any
    environment{
        SONARQUBE_PATH=''
        AWS_REGION='ap-south-1'
        ECR_BASE_URL='053996352509.dkr.ecr.ap-south-1.amazonaws.com'
        EKS_CLUSTER_NAME='Infinitheism-PreProd'
        ECR_REPO_NAME='infinitheism-preprod'
    }
    stages{
        // stage('SonarScan') {
        //     steps {
        //         script {
        //             nodejs('Infinitheism') {
        //                 withSonarQubeEnv('Sonar') {
        //                     sh "${env.SONARQUBE_PATH}"
        //                 }
        //             }
        //         }
        //     }
        // }
        // stage('Quality Gate') {
        //     steps {
        //         script {
        //             def qg = waitForQualityGate()
        //             if (qg.status != 'OK') {
        //                 error "Pipeline aborted due to quality gate failure: ${qg.status}"
        //             }
        //         }
        //     }
        // }
        stage('Authentication') {
            steps {
                sh "aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_BASE_URL}"
                sh "aws eks update-kubeconfig --region ${AWS_REGION} --name ${EKS_CLUSTER_NAME}"
            }
        }
        stage('Building Dockerfile') {
            steps {
                sh "docker build -t ${ECR_BASE_URL}/${ECR_REPO_NAME}:latest -f devops/Dockerfile ."
            }
        }
        stage('Push the Image into ECR') {
            steps {
                sh "docker push ${ECR_BASE_URL}/${ECR_REPO_NAME}:latest"
            }
        }
        stage('Restart the deployment') {
             steps {
                sh "kubectl rollout restart deployments/infinitheism-preprod"
                sh "kubectl set image deployments/infinitheism-preprod infinitheism-preprod=${ECR_BASE_URL}/${ECR_REPO_NAME}:latest"
                sh "docker rmi ${ECR_BASE_URL}/${ECR_REPO_NAME}:latest"
             }
         }
         stage('Cleaning the cache') {
             steps {
                 sh 'docker system prune -f'
             }
         }
    }
    post{
        always{
            cleanWs()
        }
    }
}
