// Jenkinsfile template for deploying to a dotnews-paas server from the
// existing LAN Jenkins. Copy into a pipeline job (or the repo) and adjust
// the environment block. Requirements on Jenkins:
//   - Node 22 available on the agent (or use a nodejs tool installation)
//   - SSH credential 'paas-deploy-key' = private key of the 'deploy' user
pipeline {
    agent any

    environment {
        PAAS_APP  = 'myapp'
        PAAS_HOST = 'deploy@192.168.12.80'      // the paas VM
        BRANCH    = 'main'
        REPO_URL  = 'git@gitlab.com:dotnews/example.git'
        OUTPUT    = '.output'                   // Nuxt/Nitro build output
    }

    // Trigger however this Jenkins already does it: SCM polling or webhooks.
    triggers { pollSCM('H/2 * * * *') }

    stages {
        stage('Checkout') {
            steps { git branch: env.BRANCH, url: env.REPO_URL }
        }
        stage('Build') {
            steps {
                sh 'npm ci'
                sh 'NITRO_PRESET=node-server npm run build'
            }
        }
        stage('Deploy') {
            steps {
                sshagent(credentials: ['paas-deploy-key']) {
                    sh '''
                        rsync -az --delete "$OUTPUT"/ "$PAAS_HOST:/srv/paas/builds/jenkins-$PAAS_APP/"
                        ssh -o StrictHostKeyChecking=accept-new "$PAAS_HOST" \
                          "PAAS_SOURCE=jenkins PAAS_COMMIT=$(git rev-parse HEAD) paas deploy $PAAS_APP /srv/paas/builds/jenkins-$PAAS_APP"
                    '''
                }
            }
        }
    }
}
