#!/usr/bin/bash

#shellcheck disable=1091
source /usr/lib/ujust/ujust.sh

IMAGE_INFO="/usr/share/ublue-os/image-info.json"
IMAGE_NAME=$(jq -r '."image-name"' < "$IMAGE_INFO")
IMAGE_TAG=$(jq -r '."image-tag"' < "$IMAGE_INFO")
IMAGE_VENDOR=$(jq -r '."image-vendor"' < "$IMAGE_INFO")
FEDORA_VERSION=$(jq -r '."fedora-version"' < "$IMAGE_INFO")
IMAGE_REGISTRY="ghcr.io/${IMAGE_VENDOR}"
ROOT_FS=$(findmnt -n -o FSTYPE /)

function list_tags() {
  local filter="$1"
  skopeo list-tags "docker://${IMAGE_REGISTRY}/${IMAGE_NAME}" \
    | jq -r '.Tags[]' \
    | grep -E --color=never "$filter" \
    | sort -rV | head -n 31
}

function rebase_helper() {
  echo "Current image: ${IMAGE_NAME}:${IMAGE_TAG} (Fedora ${FEDORA_VERSION})"
  echo "Root filesystem: ${ROOT_FS}"
  echo

  # Step 1: Choose image variant
  echo "Select your Aurora image:"
  IMAGE_OPTIONS=(aurora aurora-dx)

  # Add current image if it's not already in the list
  if [[ ! " ${IMAGE_OPTIONS[*]} " =~ \ ${IMAGE_NAME}\  ]]; then
    IMAGE_OPTIONS+=("${IMAGE_NAME}")
  fi

  IMAGE_OPTIONS+=(cancel)

  selected_image=$(Choose "${IMAGE_OPTIONS[@]}")
  [[ "$selected_image" == "cancel" ]] && exit 0

  IMAGE_NAME="$selected_image"
  base_image="${IMAGE_REGISTRY}/${IMAGE_NAME}"

  # Step 2: Channel Selection
  declare -a CHANNELS
  CHANNELS=(stable stable-daily latest)
    echo "The default selection is stable. Stable-daily (daily builds) are for enthusiasts, and latest is for testers"

  # Fetch Fedora version per channel and build display list
  declare -a CHANNELS_DISPLAY
  declare -a CHANNELS_RAW

  for channel in "${CHANNELS[@]}"; do
    version=$(skopeo inspect --no-tags docker://${base_image}:${channel} | jq -r '.Labels["org.opencontainers.image.version"]' | sed 's/.*-//' | cut -c 1-2)
    CHANNELS_DISPLAY+=("${channel} (F${version})")
    CHANNELS_RAW+=("${channel}")
  done

  channel_choice=$(Choose "${CHANNELS_DISPLAY[@]}" cancel)
  [[ "$channel_choice" == "cancel" ]] && exit 0
  channel_selected=${channel_choice%% *}

  rebase_target="${base_image}:${channel_selected}"

  # Step 3: Date selection (scoped to channel)
  echo "Would you like to pin to a specific build date?"
  echo "NOTICE! You won't receive any updates after pinning to a specific build date."
  date_choice=$(Choose "no" "yes" cancel)
  [[ "$date_choice" == "cancel" ]] && return 1

  if [[ "$date_choice" == "yes" ]]; then
    echo "Fetching available tags for channel: $channel_selected..."
    filter="${channel_selected}-[0-9]{8}"

    valid_tags=( $(list_tags "$filter") )
    [[ "${#valid_tags[@]}" -eq 0 ]] && { echo "No tags found for filter: $filter"; return 1; }

    selected_tag=$(Choose cancel "${valid_tags[@]}")
    [[ "$selected_tag" == "cancel" ]] && return 1

    rebase_target="${base_image}:${selected_tag}"
  fi

  echo "Rebase target: ${rebase_target}"
  echo "Confirm rebase?"
  [[ $(Confirm) -ne 0 ]] && return 1

  if grep -q "^LockLayering=true" /etc/rpm-ostreed.conf; then
    pkexec bootc switch --enforce-container-sigpolicy "${rebase_target}"
  else
    rpm-ostree rebase ostree-image-signed:docker://"${rebase_target}"
  fi
}

echo "Choose your action."
option=$(Choose rebase cancel)
if [[ "$option" == "rebase" ]]; then
    rebase_helper || /usr/bin/ublue-rollback-helper
else
    exit 0
fi
