#!/usr/bin/env bash
set -eux


CHANNELS_URL="https://update.rke2.io/v1-release/channels"
IMAGE_LIST_URL="https://github.com/rancher/rke2/releases/download/"
RKE2_IMAGES="$(pwd)/$(dirname $0)/images-sources-rke2-standalone.txt"
NUM_VERSIONS=4


concat_images() {
    local image_file="$1"
    local channel="$2"

    # Concatenate the individual images files from the RKE2's version file
    # into the bigger version file.  Then we remove the 'docker.io' domain, but
    # keep 'registry.suse.com' and other domains, to be inline with the
    # Rancher's image file. Finally, we add the 'rke2-k3s' and
    # 'release/rke2/<channel>' labels that will be used by
    # image-scanning when creating the GH issues. Note that there is a space
    # before the labels and they are separated by a comma.  Everything is
    # concatenated into one big file that will be parsed by image-scanning.
    cat "$image_file" | \
        sed "s/^docker.io\///" | \
        sed "s/$/ rke2-k3s,release\/rke2\/$channel/" >> "$RKE2_IMAGES"
}

download_image_lists() {
    local version="$1"
    local channel="$2"
    local images_file="${IMAGE_LIST_URL}${version}/rke2-images.linux-amd64.txt"
    local image_filename=
    local dir=$(pwd)
    local tmpdir=$(mktemp -d)

    cd "$tmpdir"

    echo "=> Downloading RKE2's image file for version $version"
    if ! (curl --fail -sLO "$images_file"); then
        echo "=> Unable to find an image file for RKE2's $version version"
        exit 1
    fi

    concat_images $(basename $images_file) "$channel"

    cd "$dir" && rm -rf "$tmpdir"
}

main() {
    rm -rf "$RKE2_IMAGES"
    CHANNEL_DATA=$(curl -s "${CHANNELS_URL}" | jq '.data[] | select(.id != "latest" and .id != "testing" and .id != "stable")')
    for channel in $(echo "${CHANNEL_DATA}" | jq '.id' | tr -d '"' | sort -Vr | head -n "${NUM_VERSIONS}"); do
        version=$(jq --arg channel "$channel" 'select(.id == $channel) | .latest' <<< "$CHANNEL_DATA")
        version=$(echo "${version}" | tr -d '"')
        download_image_lists "${version}" "${channel}"
    done
}

main