pipeline {
    agent any
    triggers {
        githubPush() // This will trigger the pipeline when a new commit is pushed to the 'main' branch.
    } 
    environment {
        // Define Docker variables with same values in your kubernetes.yaml file
        DOCKERHUBUSERNAME='semiharsan'
        DOCKERIMAGE_NAME='pythonapp'
        DOCKERIMAGE_TAG_VERSION='v10'
        DOCKERIMAGE_ID = ''
        // Write here your kubernetes cluster namespace for your deployment
        NAMESPACE="default"
        DEPLOYMENTREPLICA="2"
    }
    
    stages {
        
        stage('Checkout New Code and Download Repository') {
            agent { label 'K8S_Master' }
            steps {
                script {
                    // Checkout the code from GitHub Repository
                    checkout scmGit(branches: [[name: '*/main']], extensions: [], userRemoteConfigs: [[credentialsId: 'b66dea26-cddc-4ad5-bc33-15595ceebe9f', url: 'https://github.com/semiharsan/pythondemoapp.git']])
                }
            }
        }
       
       stage('Docker Build And Push to Docker Hub') {
            agent { label 'K8S_Master' }
            steps {
                withDockerRegistry(credentialsId: '720f2e1b-5a65-464a-9fcd-409ad902d3cf', url: 'https://index.docker.io/v1/'){}
                                
                sh ''' 
                ls -lsa
                pwd
                DOCKERIMAGE_ID=$(docker images -q "$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION")
                if [ -z "$DOCKERIMAGE_ID" ]; then
                    echo "Docker image '$DOCKERIMAGE_NAME' not found. Let us create it"
                else
                    echo "There is a cocker image with id $DOCKERIMAGE_ID, let us remove it first"
                    docker rmi -f $DOCKERIMAGE_ID
                fi
                docker build -t $DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION .
                DOCKERIMAGE_ID=$(docker images -q "$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION")
                docker tag $DOCKERIMAGE_ID $DOCKERHUBUSERNAME/$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION
                docker push $DOCKERHUBUSERNAME/$DOCKERIMAGE_NAME:$DOCKERIMAGE_TAG_VERSION
                DEPLOYMENT_NAME=$(awk '/metadata:/ {f=1} f && /name:/ {print $2; exit}' onpremisekubernetes.yaml | tr -d '\r' 2>/dev/null)
                PODS=$(kubectl get pods -n $NAMESPACE -l app=$DEPLOYMENT_NAME -o custom-columns=NAME:.metadata.name --no-headers)
                if [ -z "$PODS" ]; then
                    echo "There is no $DEPLOYMENT_NAME deployment. Let us create it"
                    kubectl apply -f onpremisekubernetes.yaml
                    kubectl get pods
                else
                    echo "There is already pods with name $PODS let us update deployment"
                    NEW_REPLICA=$((DEPLOYMENTREPLICA + 1))
                    kubectl scale deployment/$DEPLOYMENT_NAME --replicas=$NEW_REPLICA
                    kubectl get pods
                    kubectl wait deployment/$DEPLOYMENT_NAME --for=condition=Available --timeout=120s
                    echo Deleting pods: $PODS
                    kubectl delete pod $PODS -n $NAMESPACE
                    kubectl scale deployment/$DEPLOYMENT_NAME --replicas=$DEPLOYMENTREPLICA
                    kubectl get pods
                fi
                '''
             }
        } 
    }
}