#!/usr/bin/bash

VERSION=${1:-4.19.3}

if [[ "$1" == "-h" || "$1" == "--help" ]]; then
  echo "Usage: $0 [VERSION]"
  echo "  VERSION: OpenShift Virtualization version to process"
  echo "  Example: $0 4.19.3"
  exit 0
fi

echo "Processing OpenShift Virtualization version: ${VERSION}"

RH_OPERATORS_CATALOG=registry.redhat.io/redhat/redhat-operator-index
MINOR_VERSION=${VERSION%.*}
BUNDLE_NAME=kubevirt-hyperconverged-operator.v${VERSION}
CSV_NAME=kubevirt-hyperconverged-operator.clusterserviceversion.yaml

oc image extract ${RH_OPERATORS_CATALOG}:v${MINOR_VERSION} --path /configs/kubevirt-hyperconverged/catalog.json:. --confirm
BUNDLE_IMAGE=$(jq -r --arg bundle_name "$BUNDLE_NAME" 'select(.schema == "olm.bundle" and .name == $bundle_name).image' catalog.json)
oc image extract "${BUNDLE_IMAGE}" --path /manifests/${CSV_NAME}:. --confirm
echo "Images included in ${VERSION}:"
yq .spec.relatedImages[].name "${CSV_NAME}"

CSV_OUTPUT="ocp-virt-${VERSION}-source-references.csv"

echo "requestType,requestSubType,compVendorName,compVendorUrl,compName,compVersion,repoCommitId,compDownloadUrl" > "${CSV_OUTPUT}"

TOTAL_IMAGES=$(yq .spec.relatedImages[].name "${CSV_NAME}" | wc -l)
CURRENT_COUNT=0

echo "Processing ${TOTAL_IMAGES} images..."

yq .spec.relatedImages[].name "${CSV_NAME}" | while IFS= read -r image; do
  CURRENT_COUNT=$((CURRENT_COUNT + 1))
  
  IMAGE_NAME_PART=$(echo "$image" | sed 's|.*/||')  # Remove registry and path
  echo "Processing ${CURRENT_COUNT} out of ${TOTAL_IMAGES}: ${IMAGE_NAME_PART}" >&2
  
  # Get image info once and reuse for all label extractions
  IMAGE_INFO=$(oc image info $image --filter-by-os linux/amd64 -o json)
  
  if [[ "$image" == *"openshift4/ose"* ]]; then
    COMMIT_SHA=$(echo "$IMAGE_INFO" | jq -r '.config.config.Labels["vcs-ref"]')
    
    if [[ "$IMAGE_NAME_PART" == *"ose-"*"-rhel9"* ]]; then
      REPO_NAME=$(echo "$IMAGE_NAME_PART" | sed 's/.*ose-\(.*\)-rhel9.*/\1/')
      UPSTREAM_REPO="https://github.com/openshift/${REPO_NAME}"
    else
      UPSTREAM_REPO=$(echo "$IMAGE_INFO" | jq -r '.config.config.Labels["upstream-vcs-url"]')
    fi
  elif [[ "$IMAGE_NAME_PART" == *"kubevirt-dpdk-checkup-rhel9"* ]]; then
    # Special handling for kubevirt-dpdk-checkup-rhel9
    # the upstream-vcs-url label will be available in future
    COMMIT_SHA=$(echo "$IMAGE_INFO" | jq -r '.config.config.Labels["upstream-vcs-ref"]')
    UPSTREAM_REPO="https://github.com/kiagnose/kubevirt-dpdk-checkup"
  elif [[ "$IMAGE_NAME_PART" == *"kubevirt-realtime-checkup-rhel9"* ]]; then
    # Special handling for kubevirt-realtime-checkup-rhel9
    # the upstream-vcs-url label will be available in future
    COMMIT_SHA=$(echo "$IMAGE_INFO" | jq -r '.config.config.Labels["upstream-vcs-ref"]')
    UPSTREAM_REPO="https://github.com/kiagnose/kubevirt-realtime-checkup"
  else
    # For non-OpenShift images, use the original labels
    COMMIT_SHA=$(echo "$IMAGE_INFO" | jq -r '.config.config.Labels["upstream-vcs-ref"]')
    UPSTREAM_REPO=$(echo "$IMAGE_INFO" | jq -r '.config.config.Labels["upstream-vcs-url"]')
  fi
  
  # Remove .git suffix from repository URL if present
  UPSTREAM_REPO=${UPSTREAM_REPO%.git}
  
  if [ "${COMMIT_SHA}" != "null" ] && [ "${UPSTREAM_REPO}" != "null" ]; then
    if [[ "$IMAGE_NAME_PART" == *":"* ]]; then
      COMP_NAME=$(echo "$IMAGE_NAME_PART" | sed 's/:.*$//')
      COMP_VERSION=$(echo "$IMAGE_NAME_PART" | sed 's/.*://')
    elif [[ "$IMAGE_NAME_PART" == *"@"* ]]; then
      COMP_NAME=$(echo "$IMAGE_NAME_PART" | sed 's/@.*$//')
      COMP_VERSION=$(echo "$IMAGE_NAME_PART" | sed 's/.*@//')
    else
      COMP_NAME="$IMAGE_NAME_PART"
      COMP_VERSION="latest"
    fi
    
    COMP_DOWNLOAD_URL="${UPSTREAM_REPO}/archive/${COMMIT_SHA}.tar.gz"
    
    echo "FOSS,NEW_COMPONENT,Red Hat,${UPSTREAM_REPO},${COMP_NAME},${COMP_VERSION},${COMMIT_SHA},${COMP_DOWNLOAD_URL}" >> "${CSV_OUTPUT}"
  else
    echo "Warning: Missing upstream info for $image" >&2
  fi
done

echo "CSV output written to: ${CSV_OUTPUT}"