pipeline {
  agent any

  environment {
    REMOTE_HOST = '192.168.1.102'
    REMOTE_DIR  = '/home/zouklambadabcn.com/public_html'
    PM2_APP     = 'ZLB'
    // Name of Jenkins Credentials (Username with private key) to SSH
    SSH_CREDS   = 'root_ssh' // <-- configure this in Jenkins Credentials
  }

  options {
    timestamps()
  }

  stages {
    stage('Deploy over SSH') {
      steps {
        script {
          // Validate Jenkins has the required credential
          withCredentials([sshUserPrivateKey(credentialsId: env.SSH_CREDS, keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')]) {
            // Build the remote command to run
            def remoteCmd = """
              set -e
              cd "${env.REMOTE_DIR}"
              git pull
              npm install
              npm run build
              pm2 restart ${env.PM2_APP}
            """.stripIndent()

            // SSH options for non-interactive, secure connection
            def sshOpts = '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes'

            // Execute remote command via ssh
            sh label: 'Run remote deployment', script: "ssh -i \"${SSH_KEY}\" ${sshOpts} \"${SSH_USER}@${REMOTE_HOST}\" 'bash -lc '\''" + remoteCmd.replace("'", "'\''") + "'\'' '"
          }
        }
      }
    }
  }

  post {
    success {
      echo 'Deployment completed successfully.'
    }
    failure {
      echo 'Deployment failed.'
    }
    always {
      cleanWs(deleteDirs: true, notFailBuild: true)
    }
  }
}
