pipeline {
    agent any

    options {
        timeout(time: 15, unit: 'MINUTES')
    }

    environment {
        QA_HOST = "172.31.80.14" // awstaging
        PROD_HOST = "172.31.0.10" // rpsweb01
        REPO_PATH = "/var/app/shared/rs-sample-files"
        REMOTE_NAME = "origin_ssh"
        QA_SSH_CREDENTIAL = 'royaltyshare_awstaging'
        PROD_SSH_CREDENTIAL = 'royaltyshare_prod_ssh'
    }

    stages {
        stage('Update QA host') {
            when {
                branch 'master'
            }
            steps {
                script {
                    updateRemoteRepository(env.QA_HOST, env.QA_SSH_CREDENTIAL)
                }
            }
        }

        stage('Update Prod host') {
            when {
                branch 'master'
            }
            steps {
                script {
                    updateRemoteRepository(env.PROD_HOST, env.PROD_SSH_CREDENTIAL)
                }
            }
        }
    }
}

def updateRemoteRepository(String remoteHost, String sshCredential) {
    sshagent(credentials: [sshCredential]) {
        sh """
            ssh -o StrictHostKeyChecking=no jenkins@${remoteHost} '
                set -euo pipefail

                if [ ! -d "${env.REPO_PATH}" ]; then
                    echo "Error: missing ${env.REPO_PATH}."
                    exit 1
                fi

                git -C "${env.REPO_PATH}" config --add safe.directory "${env.REPO_PATH}"
                git -C "${env.REPO_PATH}" config core.sshCommand "ssh -i ~/.ssh/sample-files-deploy-key -o StrictHostKeyChecking=no"
                git -C "${env.REPO_PATH}" pull "${env.REMOTE_NAME}" "${env.GIT_BRANCH}"

                echo "Updated: ${env.GIT_PREVIOUS_COMMIT} -> ${env.GIT_COMMIT}"
            '
        """
    }
}
