pipeline {
    agent any

    environment {
        IMAGE = "ghcr.io/kukkacc1/high-orbit-hu"
    }

    stages {
        stage('Build') {
            steps {
                sh "docker build -t ${IMAGE}:${env.BUILD_NUMBER} ."
            }
        }

        stage('Push') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'GHCR_TOKEN', usernameVariable: 'GHCR_USER', passwordVariable: 'GHCR_PASS')]) {
                    sh """
                        echo \$GHCR_PASS | docker login ghcr.io -u \$GHCR_USER --password-stdin
                        docker tag ${IMAGE}:${env.BUILD_NUMBER} ${IMAGE}:latest
                        docker push ${IMAGE}:${env.BUILD_NUMBER}
                        docker push ${IMAGE}:latest
                    """
                }
            }
        }

        stage('Deploy') {
            when { branch 'master' }
            steps {
                withCredentials([usernamePassword(credentialsId: 'GHCR_TOKEN', usernameVariable: 'GHCR_USER', passwordVariable: 'GHCR_PASS')]) {
                    sh """
                        ssh -i /root/.ssh/id_jenkins_deploy -o StrictHostKeyChecking=no root@204.168.193.92 \
                            "echo \$GHCR_PASS | docker login ghcr.io -u \$GHCR_USER --password-stdin && cd /opt/high-orbit-hu && docker compose pull && docker compose up -d"
                    """
                }
            }
        }
    }

    post {
        always {
            sh 'docker logout ghcr.io || true'
        }
    }
}
