// Manages standalone pipeline jobs that do not fit within the Organization Folder structure.
import jenkins.model.Jenkins
import hudson.model.Item
import hudson.model.Items

def pipelineJobs = [
    [
        name: 'terraform-state-provider-not-present-fix',
        description: '''
Fixes the "Provider configuration not present" errors encountered when upgrading modules which previously had providers defined inside in the modules.<br>
<br>
Examples:<br>
terraform-lambda from <=2.4.0 to >=2.4.1<br>
terraform-datadog from <=3.4.0 to >=4.0.0''',
        repo: 'theorchard/terraform-utils',
        scriptPath: 'state-file-fixer/Jenkinsfile'
    ],
    [
        name: 'publishing-csv-ingestion',
        description: 'Reads a CSV and ingests publishing metadata.',
        repo: 'theorchard/graphql-publishing',
        scriptPath: 'scripts/ingestion-client/Jenkinsfile'
    ],
    [
        name: 'publishing-delivery-updater',
        description: 'Reads a CSV and updates deliveryDate and delivered status to true on compositions',
        repo: 'theorchard/graphql-publishing',
        scriptPath: 'scripts/delivery-updater/Jenkinsfile'
    ],
    [
        name: 'publishing-qa-s3-bucket-cleanup',
        description: 'Job to cleanup QA publishing resources in S3',
        repo: 'theorchard/lambda-publishing-changelog',
        scriptPath: 'scripts/qa-s3-bucket-cleanup/Jenkinsfile',
    ],
    [
        name: 'nr-performance-trigger-versioning',
        description: 'Triggers the graphql-nr `trigger-versioning` script for updating performance contributions. See https://www.notion.so/nr-trigger-versionning-00b1724e7234419b9832a65402592dfe',
        repo: 'theorchard/graphql-neighbouring-rights',
        scriptPath: 'scripts/trigger-versioning/Jenkinsfile',
    ],
    [
        name: 'neo4j-aura-refresh-pipeline',
        description: 'Pipeline to refresh Neo4j Aura instances.',
        repo: 'theorchard/python-neo4j-utils',
        scriptPath: 'refresh_aura/Jenkinsfile'
    ],
    [
        name: 'insights-playlist-freshness-tests',
        description: 'Automated tests verifying Insights playlist freshness, completeness, metrics and NMF data against source-of-truth providers.',
        repo: 'theorchard/insights-cross-app-data-tests',
        scriptPath: 'Jenkinsfile.playlist-freshness'
    ],
    [
        name: 'insights-go-tests',
        description: 'Automated tests checking Insights GO (mobile) data.',
        repo: 'theorchard/insights-cross-app-data-tests',
        scriptPath: 'Jenkinsfile.insights-go'
    ],
    [
        name: 'nr-s3-cleanup-utils',
        description: 'Job to cleanup some QA neighbouring rights resources in S3',
        repo: 'theorchard/nr-s3-cleanup-utils',
        scriptPath: 'Jenkinsfile',
    ],
    [
        name: 'db-deploy-push-ecr',
        description: 'Pipeline to upload a new dockers image for database',
        repo: 'theorchard/database',
        scriptPath: 'Jenkinsfile'
    ],
    [
        name: 'publishing-changelog-non-utf8-encoding-fix',
        description: 'Fixes non-UTF-8 encoding in publishing changelog table.',
        repo: 'theorchard/lambda-publishing-changelog',
        scriptPath: 'scripts/changelog-non-utf8-fixer/Jenkinsfile',
    ],
    [
        name: 'abacus-accounting-run-e2e-tests',
        description: 'Pipeline to run E2E test(s) for Abacus Accounting Run',
        repo: 'theorchard/scheduled-test-pipelines',
        scriptPath: 'playwright/qa/Jenkinsfile.abacus-accounting-run',
        branch: 'master'
    ],
    [
        name: 'songwhip-cookie-banner-e2e-tests',
        description: 'Pipeline to run E2E tests for Songwhip Cookie Banner',
        repo: 'theorchard/scheduled-test-pipelines',
        scriptPath: 'playwright/qa/Jenkinsfile.songwhip-cookie-banner',
        branch: 'master'
    ],
    [
        name: 'insights-regression-qa-tests',
        description: 'Pipeline to run QA regression E2E tests for Insights',
        repo: 'theorchard/scheduled-test-pipelines',
        scriptPath: 'playwright/qa/Jenkinsfile.insights-regression',
        branch: 'master'
    ],
    [
        name: 'airflow-redeploy',
        description: 'Rollback an airflow environment to a previously deployed Git revision.',
        repo: 'theorchard/python-deployment-utils',
        scriptPath: 'airflow/Jenkinsfile.rollback',
    ],
    [
        name: 'k6Tests',
        description: 'Run Performance tests using k6 hybrid framework',
        repo: 'theorchard/k6-hybrid-performance-tests',
        scriptPath: 'Jenkinsfile',
    ],
    [
        name: 'insights-lighthouse-e2e-prod-tests-pipeline',
        description: 'Pipeline to run Prod Lighthouse tests for Insights app',
        repo: 'theorchard/cucumber-cypress-tests',
        scriptPath: 'scripts/Jenkinsfile/prod/Jenkinsfile.insights_lighthouse',
        branch: 'master'
    ],
    [
        name: 'content-sound-recording-redelivery',
        description: 'Pipeline to run the <a href="https://github.com/theorchard/lambda-sound-recordings/blob/fa1769b286001730e63cdba78d47fcc6ca95fe36/scripts/osr-redelivery/redelivery.py">sr-delivery script</a> for manually redelivering OSRs.',
        repo: 'theorchard/lambda-sound-recordings',
        scriptPath: 'scripts/osr-redelivery/Jenkinsfile',
        branch: 'master'
    ],
    [
        name: 'streamlit-call-delete-smeanalyticsdummy-product',
        description: 'Pipeline to deploy streamlit app.',
        repo: 'theorchard/streamlit-call-delete-smeanalyticsdummy-product',
        scriptPath: 'Jenkinsfile',
        branch: 'master'
    ],
    [
        name: 'audit-feature-flags-splitio',
        description: 'Pipeline to audit all feature flags in Split.io, optionally filtered by team and exported as Excel, JSON, or table.',
        repo: 'theorchard/security-scripts',
        scriptPath: 'splitio_ff_manager/Jenkinsfile.splitio_audit',
        branch: 'master'
    ],
    [
        name: 'create-feature-flag-splitio',
        description: 'pipeline to create a feature flag in Split.io using user input.',
        repo: 'theorchard/security-scripts',
        scriptPath: 'splitio_ff_manager/Jenkinsfile',
        branch: 'master'
    ],
    [
        name: 'trigger-backup-cloudsearch',
        description: 'pipeline to start backup of a cloudsearch domain to kafka instance using ECS task.',
        repo: 'theorchard/backup-cloudsearch',
        scriptPath: 'Jenkinsfile.trigger',
        branch: 'master'
    ],
    [
        name: 'terraform-state-replace-snowflake-provider',
        description: 'Replaces terraform snowflake provider in order to use new organization snowflakedb instead of Snowflake-Labs',
        repo: 'theorchard/terraform-utils',
        scriptPath: 'replace-snowflake-provider/Jenkinsfile'
    ],
    [
        name: 'datadog-software-catalog-refresh-executor',
        description: 'DO NOT TRIGGER MANUALLY. Refreshes software catalog entry for a given entity.',
        repo: 'theorchard/python-datadog-utils',
        scriptPath: 'refreshExec.groovy'
    ],
    [
        name: 'datadog-software-catalog-refresh',
        description: 'Triggers a refresh for datadog software catalog entities',
        repo: 'theorchard/python-datadog-utils',
        scriptPath: 'refreshJob.groovy'
    ],
    [
        name: 'gdb-infrastructure-datadog-software-catalog',
        description: 'Job for uploading software catalog definitions for devops owned GDB services',
        repo: 'theorchard/infrastructure',
        scriptPath: 'software-catalog.groovy'
    ],
    [
        name: 'deezer-timed-release-link-scraper-e2e',
        description: 'Pipeline to run Deezer timed release link scraper E2E test',
        repo: 'theorchard/scheduled-test-pipelines',
        scriptPath: 'playwright/qa/Jenkinsfile.deezer-release-link-scraper',
        branch: 'master'
    ],
]

def playwrightProdFeatures = [
    'collaborators',
    'content',
    'ddex',
    'distribution',
    'documents',
    'fansifter',
    'insights',
    'moneyhub',
    'publishing',
    'royalties',
    'settings',
    'songwhip',
    'workstation',
    'songwhip-cookie-banner',
]

playwrightProdFeatures.each { feature ->
    pipelineJobs << [
        name: "${feature}-e2e-prod-tests-pipeline",
        description: "Pipeline to run Prod E2E tests for ${feature.capitalize()}",
        repo: 'theorchard/scheduled-test-pipelines',
        scriptPath: "playwright/prod/Jenkinsfile.${feature}",
        branch: 'master'
    ]
}

pipelineJobs.each { job ->
    def jobProperties
    Item existingJob = Jenkins.instance.getItemByFullName(job.name)
    if (existingJob) {
        jobProperties = existingJob.@properties
    }

    pipelineJob(job.name) {
        definition {
            cpsScm {
                lightweight(true)
                scm {
                    gitSCM {
                        browser {}
                        branches {
                            branchSpec {
                                name(job.branch ?: 'master')
                            }
                        }
                        gitTool(null)
                        userRemoteConfigs {
                            userRemoteConfig {
                                name('')
                                credentialsId('577cbc72-7d9e-4eba-924c-ecbbe6de9805')
                                refspec('')
                                url("git@github.com:${job.repo}.git")
                            }
                        }
                    }
                }
                scriptPath(job.scriptPath)
            }
        }
        description("${job.description}<br><br>NOTE: The configuration for this job is managed by <a href=\"${GIT_URL}\" target=\"_blank\">${GIT_URL}</a>")

        // Grim workaround for preserving properties configured in the Jenkinsfile.
        // See https://issues.jenkins.io/browse/JENKINS-43758?focusedId=408718&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-408718
        if (jobProperties) {
            configure { root ->
                def properties = root / 'properties'
                jobProperties.each { property ->
                    String xml = Items.XSTREAM2.toXML(property)
                    def jobPropertiesPropertyNode = new XmlParser().parseText(xml)
                    properties << jobPropertiesPropertyNode
                }
            }
        }
    }
}
