pipeline {
    agent any

    options {
        ansiColor('xterm')
        timestamps()
        buildDiscarder logRotator(artifactDaysToKeepStr: '30',
          artifactNumToKeepStr: '100',
          daysToKeepStr: '365',
          numToKeepStr: '1000')
        timeout(time: 6, unit: 'HOURS')
    }

    parameters {
        choice(name: 'ENVIRONMENT', choices: ['qa', 'prod'], description: 'The environment to run against.')
        choice(name: 'FLOW', choices: [
            'SELECT_THE_WORKFLOW',
            'amazon_datapulse',
            'amazon_digital_services',
            'amazon_instant_video',
            'amazon_music',
            'amazon_prime_marketshare',
            'amazon_unlimited',
            'amazon_unlimited_marketshare',
            'apple_financial',
            'apple_id_mapping_sme',
            'apple_music_streams',
            'awa',
            'bandsintown',
            'beatport',
            'chartmetric_charts',
            'chartmetric_participants',
            'chartmetric_playlists_share',
            'chartmetric_socials',
            'chartmetric_socials_backfill',
            'deezer',
            'deezer_marketshare',
            'delphi_crm',
            'fandango_now',
            'feature_fm_facebook',
            'gfk',
            'gfk_physical',
            'gfk_streaming',
            'google_music',
            'google_play',
            'google_play_marketshare',
            'insta_reels',
            'itunes',
            'itunes_hides',
            'itunes_marketshare',
            'itunes_tickets',
            'kugou',
            'kuwo',
            'line',
            'meta_daily',
            'mrc',
            'music_analytics_reports',
            'neo4j_to_snowflake',
            'netease',
            'pandora',
            'peloton',
            'physical_reporting',
            'physical_warehouse_reports',
            'playstation_video',
            'proper_incoming',
            'qq',
            'ritmogestion',
            'seated',
            'setlive',
            'shazam_daily_events',
            'sme_latam',
            'soundcloud',
            'spotify',
            'spotify_artificial_streams',
            'spotify_backfill',
            'spotify_charts',
            'spotify_marketshare',
            'spotify_marquee',
            'spotify_strikes',
            'spotify_track_metrics',
            'ticketek',
            'tiktok',
            'tiktok_fraudulent_streams_report',
            'tiktok_openescrow',
            'tiktok_weekly',
            'vevo',
            'vudu',
            'wynk',
            'xbox',
            'youtube_asset',
            'youtube_asset_conflict',
            'youtube_bulk_reports',
            'youtube_bulk_reports_facts_asset',
            'youtube_bulk_reports_facts_video',
            'youtube_channel_names',
            'youtube_claim',
            'youtube_facts',
            'youtube_monthly',
            'youtube_neo4j',
            'youtube_red_marketshare',
            'youtube_video',
            'youtube_vod',
            'youtube_weekly',
        ])
        string(name: 'START_DATE', defaultValue: '',  description: 'YYYY-MM-DD. Required date to context_date.')
        string(name: 'END_DATE', defaultValue: '',  description: 'YYYY-MM-DD. End date. Optional')
        string(name: 'CONTEXT', defaultValue: '{"licensor": "", "report_name": ""}')
        booleanParam(name: 'RELOAD', defaultValue: false, description: 'when checked is sends to context "reload": "True"')
        booleanParam(name: 'WAIT_UNTIL_COMPLETE', defaultValue: false, description: 'Wait completion of SWF runs')
        booleanParam(name: 'CHECK_STATUS', defaultValue: true, description: 'Do not start already completed contexts')
        choice(name: 'EXPECTED_STATUS', choices: ['INGESTED', 'POPULATED_RAW_TABLE', 'DOWNLOADED'], description: 'Status value when flow considered as completed')
        string(name: 'MAX_CONCURRENT_FLOWS', defaultValue: '5', description: 'Max number of of active SWF flow executions.')
        choice(name: 'CONCURRENCY_STRATEGY', choices: ['WAIT', 'IGNORE', 'FAIL', 'SKIP'], description: 'IGNORE - execute all contexts regardless of limits. WAIT - hold off contexts until the slot is available (timeout 1h). FAIL - fail execution if limit is reached. SKIP - do not execute contexts which are above limit.')
        booleanParam(name: 'ONLY_UPDATE_JOB', defaultValue: false, description: 'When checked the Jenkins job only updates itself. No execution triggers')
    }

    environment {
        CREDENTIALS_ID = "${params.ENVIRONMENT == 'prod' ? 'prod-feed-ingestion-exec-creds' : 'qa-feed-ingestion-exec-creds'}"
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                script {
                    def buildUser = env.BUILD_USER_ID ?: "<unknown>"
                    currentBuild.displayName = "[${params.ENVIRONMENT}] ${params.FLOW} by ${buildUser}"
                }
                library "jenkins-global-libraries@master"
            }
        }
        stage('Run exec job') {
            when {
                expression {
                    params.ONLY_UPDATE_JOB == false
                }
            }
            steps {
                withEcr {
                    withCredentials([[
                    $class: 'AmazonWebServicesCredentialsBinding',
                    credentialsId: env.CREDENTIALS_ID,
                    accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                    secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
                    ]])
                    {
                        dockerRun(
                            imageTag: 'latest',
                            script: '/var/app/feed_ingestion/flows/_anyexec/exec.py',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: params.ENVIRONMENT,
                                FLOW: params.FLOW,
                                START_DATE: params.START_DATE,
                                END_DATE: params.END_DATE,
                                CONTEXT: params.CONTEXT,
                                RELOAD: params.RELOAD,
                                WAIT_UNTIL_COMPLETE: params.WAIT_UNTIL_COMPLETE,
                                CHECK_STATUS: params.CHECK_STATUS,
                                EXPECTED_STATUS: params.EXPECTED_STATUS,
                                MAX_CONCURRENT_FLOWS: params.MAX_CONCURRENT_FLOWS,
                                CONCURRENCY_STRATEGY: params.CONCURRENCY_STRATEGY,

                                AWS_ACCESS_KEY_ID: env.AWS_ACCESS_KEY_ID,
                                AWS_SECRET_ACCESS_KEY: env.AWS_SECRET_ACCESS_KEY,
                                AWS_DEFAULT_REGION: 'us-east-1',
                            ]
                        )
                    }
                }
            }
        }
    }
}
