// Import necessary classes
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*
import hudson.util.Secret
import org.jenkinsci.plugins.plaincredentials.impl.*

// Define the IDs and description
def existingCredentialID = 'existing-credential-id'  // Replace with your existing credential ID
def newCredentialID = 'new-credential-id'            // Set the new credential ID
def newDescription = 'New Credential Description'    // Set the new credential description

// Get Jenkins instance and the credentials store
def jenkins = Jenkins.instance
def domain = Domain.global()
def store = jenkins.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()

// Find the existing credential
def existingCredential = store.getCredentials(domain).find { it.id == existingCredentialID }

if (existingCredential == null) {
    println("Credential with ID '${existingCredentialID}' not found.")
} else if (existingCredential instanceof FileCredentialsImpl) {
    // Get the content of the existing credential
    def secretBytes = existingCredential.getSecretBytes()
    def fileName = existingCredential.getFileName()

    // Create a new credential with the same content but a different ID and description
    def newCredential = new FileCredentialsImpl(
            CredentialsScope.GLOBAL,
            newCredentialID,
            newDescription,
            fileName,
            secretBytes
    )

    // Add the new credential to the store
    store.addCredentials(domain, newCredential)
    println("New credential '${newCredentialID}' created successfully.")
} else {
    println("The credential with ID '${existingCredentialID}' is not a file credential.")
}
