#!/bin/bash

bundle_path="registry.redhat.io/lvms4/lvms-operator-bundle"
#staging_bundle_path="quay.io/redhat-user-workloads/logical-volume-manag-tenant/lvm-operator-bundle"
staging_bundle_path="registry.stage.redhat.io/lvms4/lvms-operator-bundle"
lvms_all_tags="$(skopeo list-tags docker://${staging_bundle_path})"
lvms_released_tags="$(skopeo list-tags docker://${bundle_path})"
all_y_streams=($(echo "${lvms_all_tags}" | yq '[.Tags[] | select(test("^v[[:digit:]]+\.[[:digit:]]+$"))] | join(" ")'))
template="""
Schema: olm.semver
GenerateMajorChannels: false
GenerateMinorChannels: true
"""

staging_versions=$(echo "${lvms_all_tags}" | yq '{"staging": [.Tags[] | select(test("^v[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+$"))]}')
released_versions=$(echo "${lvms_released_tags}" | yq '{"released": [.Tags[] | select(test("^v[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+$"))]}')

# Filter out the already released versions
candidate_versions=$((yq ea '. as $item ireduce ({}; . * $item )' <(echo "${staging_versions}") <(echo "${released_versions}")) | yq '.staging - .released')

# Cache the digests so we don't need to double the quay calls
declare -A digests

for i in "${!all_y_streams[@]}"; do
    # Set the min and max version for each catalog
    maxVersion="${all_y_streams[${i}]}"
    minVersion=""

    if [ "${i}" -lt ${#all_y_streams[@]} ] && [ "${i}" -gt 0 ]; then
        minVersion="${all_y_streams[${i}-1]}"
    else
        minVersion="${all_y_streams[${i}]}"
    fi

    # Filter out unsupported versions
    if ! [[ " ${TARGET_VERSIONS[*]} " =~ " ${maxVersion} " ]]; then
        continue
    fi

    echo "Generating catalog template for LVM Operator ${maxVersion}"
    catalog_template="# WARNING THIS FILE IS AUTOGENERATED - DO NOT EDIT\n${template}"

    # Stable versions
    catalog_versions=($(echo "${released_versions}" | yq "[.released[] | select(contains(\"${maxVersion}\") or contains(\"${minVersion}\"))] | join(\" \")"))
    # Initialize the stable channel array if there are stable versions
    if (( ${#catalog_versions[@]} )); then
        catalog_template=$(echo "${catalog_template}" | yq '.Stable.Bundles = []')
    fi

    for ver in "${catalog_versions[@]}"; do
        if ! [[ -n "${digests["${ver}"]}" ]]; then
            digest=$(skopeo inspect "docker://${bundle_path}:${ver}" --format "{{.Digest}}")

            while ! [ $? -eq 0 ]; do
                echo "Trying again..."
                sleep 5s
                digest=$(skopeo inspect "docker://${bundle_path}:${ver}" --format "{{.Digest}}")
            done

            digests["${ver}"]=$digest
            echo "Pinning released ${ver} to ${digests["${ver}"]}"
        fi

        catalog_template=$(echo "${catalog_template}" | yq ".Stable.Bundles += ({\"Image\": \"${bundle_path}@${digests["${ver}"]}\"} | (.Image | key) line_comment=\"${ver}\")")
    done

    catalog_versions=($(echo "${candidate_versions}" | yq "[.[] | select(contains(\"${maxVersion}\"))] | join(\" \")"))

    # Check for and add any candidates if SKIP_CANDIDATES was not specified
    if (( ${#catalog_versions[@]} )) && [ -z "${SKIP_CANDIDATES+x}" ]; then
        for ver in "${catalog_versions[@]}"; do
            if ! [[ -n "${digests["${ver}"]}" ]]; then
                digests["${ver}"]=$(skopeo inspect "docker://${staging_bundle_path}:${ver}" --format "{{.Digest}}")
                echo "Pinning candidate ${ver} to ${digests["${ver}"]}"
            fi

            catalog_template=$(echo "${catalog_template}" | yq ".Stable.Bundles += ({\"Image\": \"${staging_bundle_path}@${digests["${ver}"]}\"} | (.Image | key) line_comment=\"Candidate ${ver}\")")
        done
    else
        echo "SKIP_CANDIDATES flag was set, skipping pre-release content"
    fi

    catalog_file_location="release/catalog/lvm-operator-catalog-template.yaml"
    echo -e "${catalog_template}" > $catalog_file_location
    echo "Catalog saved to ${catalog_file_location}"
done
