#!/usr/bin/env bash

# Description:
# Check if there are cached state disks available for subsequent jobs to use.
#
# This lookup uses the state version from constants.rs.
# It accepts disks generated by any branch, including draft and unmerged PRs.
#
# If the disk exists, sets the corresponding output to "true":
# - lwd_tip_disk
# - zebra_tip_disk
# - zebra_checkpoint_disk

set -euxo pipefail


LOCAL_STATE_VERSION=$(grep -oE "DATABASE_FORMAT_VERSION: .* [0-9]+" "${GITHUB_WORKSPACE}/zebra-state/src/constants.rs" | grep -oE "[0-9]+" | tail -n1)
echo "STATE_VERSION: ${LOCAL_STATE_VERSION}"

# Function to find a disk image and output its name
find_disk_image() {
local base_name="${1}"
local disk_type="${2}"
local disk_pattern="${base_name}-cache"
local output_var="${base_name}_${disk_type}_disk"
local disk_image

disk_image=$(gcloud compute images list --filter="status=READY AND name~${disk_pattern}-.+-[0-9a-f]+-v${LOCAL_STATE_VERSION}-${NETWORK}-${disk_type}" --format="value(NAME)" --sort-by=~creationTimestamp --limit=1)

if [[ -z "${disk_image}" ]]; then
    echo "No ${disk_type^^} disk found for ${base_name^^} on network: ${NETWORK}"
    echo "${output_var}=false" >> "${GITHUB_OUTPUT}"
else
    echo "Disk: ${disk_image}"
    echo "${output_var}=true" >> "${GITHUB_OUTPUT}"
fi
}

# Find and output LWD and Zebra disks
find_disk_image "lwd" "tip"
find_disk_image "zebrad" "tip"
find_disk_image "zebrad" "checkpoint"
