pipeline {
    agent any
    environment {
        staging_server = "${env.UTDB_DEV_SERVER_IP}"
        port = "${env.UTDB_DEV_SERVER_PORT}"
    }
    stages {

        stage('Deploy to Remote') {
            steps {
                sshCopy('./*', '/var/www/html/utdbttstg', 'Deploying files to remote server')
                echo 'Deployment Stage completed'
            }
        }

        stage('Execute a command') {
            steps {
                // sshExecute('/home/hydrogen/utdbstg-traveltrade-deploy.sh', 'Checking backup on remote server')
                sshExecute('/home/hydrogen/utdbttstg-traveltrade-deploy.sh', 'Checking backup on remote server')
                echo 'After deploy complete'
            }
        }
    }
    post {
        always {
            echo 'Pipeline completed'
        }
    }
}

def sshExecute(scriptPath, description) {
    withCredentials([usernamePassword(credentialsId: 'scp-credentials', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        withEnv(["SSHPASS=$PASSWORD"]) {
            sh """
                echo "${description}"
                sshpass -e ssh -o StrictHostKeyChecking=no -p $port $USERNAME@$staging_server '${scriptPath}'
            """
        }
    }
}

def sshCopy(sourcePath, destinationPath, description) {
    withCredentials([usernamePassword(credentialsId: 'scp-credentials', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        withEnv(["SSHPASS=$PASSWORD"]) {
            sh """
                echo "${description}"
                sshpass -e scp -P $port -o StrictHostKeyChecking=no -r ${sourcePath} $USERNAME@$staging_server:${destinationPath}
            """
        }
    }
}
