pipeline {
    agent any
    
    environment {
        SSH_CREDENTIALS_ID = 'ssh_credential_utdb'
    }
    
    stages {
        stage('SSH to Remote Server') {
            steps {
                script {
                    sshagent([SSH_CREDENTIALS_ID]) {
                        def remoteUser = 'hydrogen'
                        def remoteHost = '192.168.5.55'
                        def remotePort = '1724'
                        def remotePath = '/home/hydrogen/utdbtraveltstg'
                        
                        try {
                            // Syncing files with rsync
                            echo "Syncing files to ${remoteUser}@${remoteHost}:${remotePath}..."
                            sh """
                                rsync -avz -e 'ssh -p ${remotePort}' \
                                ${WORKSPACE}/ \
                                --exclude '.git' \
                                --exclude '.env' \
                                --exclude '*.zip' \
                                ${remoteUser}@${remoteHost}:${remotePath}
                            """
                            echo "Files synced successfully."
                            
                            // Running npm install and build
                            echo "Running npm commands on the remote server..."
                            sh """
                                ssh -p ${remotePort} ${remoteUser}@${remoteHost} \
                                'cd ${remotePath} && npm install && npm run build'
                            """
                            echo "NPM commands executed successfully."

                            // Copy build files to the web server directory
                            sh """
                                ssh -p ${remotePort} ${remoteUser}@${remoteHost} \
                                'cp -r ${remotePath}/build/* /var/www/html/ttstg'
                            """
                            echo "Build files copied successfully."
                        } catch (Exception e) {
                            echo "Error during SSH/rsync command execution: ${e.getMessage()}"
                            error("Pipeline failed: ${e.getMessage()}")
                        }
                    }
                }
            }
        }
    }
}
