#!/bin/bash

REPO_DIR="/usr/share/dnf-package-manager/repos"
DEST="/etc/repo.d/default.repo"
ICON="/usr/share/dnf-icons/dnf-package-manager.png"
OK="/usr/share/dnf-icons/ok.svg"
CANCEL="/usr/share/dnf-icons/cancel.svg"
INFO="/usr/share/dnf-icons/info.svg"
ERROR="/usr/share/dnf-icons/error.svg"

shopt -s nullglob

# Collect repo files
FILES=("$REPO_DIR"/*.repo)

# Exit if none found
if [[ ${#FILES[@]} -eq 0 ]]; then
    yad --info \
        --title="No Repos Found" \
        --text="\nNo repo files found in:\n$REPO_DIR" \
        --width=400 --height=100 --center --fixed \
        --window-icon="$INFO" --image="$INFO" \
        --button="Cancel"!$CANCEL:1
    exit 0
fi

# Grab current default repo baseurl
if [[ -f "$DEST" ]]; then
    CUR_BASE=$(grep -m1 '^baseurl=' "$DEST" | cut -d= -f2)
    if [[ -n "$CUR_BASE" ]]; then
        # Extract only the domain (ftp.nluug.nl)
        CUR_BASE=$(echo "$CUR_BASE" | awk -F/ '{print $3}')
    fi
fi

# Build radiolist from repo files
for file in "${FILES[@]}"; do
    fname=$(basename "$file")
    LIST+=(FALSE "$fname")
done

# Show selection dialog
SELECTED=$(yad --list \
    --title="Current Repo: $CUR_BASE" \
    --radiolist \
    --column="Select:FBTN" \
    --column="Repo File:T" \
    "${LIST[@]}" \
    --height=300 --width=500 --center \
    --button=Cancel!$CANCEL:1 \
    --button="Set Default"!$OK:0 \
    --window-icon="$ICON")

# Exit if cancelled
[[ $? -ne 0 || -z "$SELECTED" ]] && exit 0

SELECTED_FILE=$(echo "$SELECTED" | cut -d'|' -f2)

# Handle pseudo "Current:" entry
if [[ "$SELECTED_FILE" == Current:* ]]; then
    yad --info \
        --title="Information" \
        --text="\nDefault repository is already set to:\n$SELECTED_FILE" \
        --width=400 --height=100 --center --fixed \
        --window-icon="$INFO" --image="$INFO"
    exit 0
fi

SRC="$REPO_DIR/$SELECTED_FILE"

# Confirm copy
yad --question \
    --title="Confirm Default Repo" \
    --text="\nSet this as default repo?\n\n$SRC\n\n→ $DEST" \
    --button="Cancel"!$CANCEL:1 \
    --button="Apply"!$OK:0 \
    --width=420 --height=100 --center --fixed \
    --window-icon="$ICON" --image="$ICON"

[[ $? -ne 0 ]] && exit 0

# Copy file
if cp "$SRC" "$DEST"; then
    yad --info \
        --title="Success" \
        --text="\nDefault repository set successfully!" \
        --width=320 --height=120 --center --fixed \
        --window-icon="$INFO" --image="$INFO" \
        --button="Cancel"!$OK:0
        else
    yad --error \
        --title="Error" \
        --text="\nFailed to set default repository." \
        --width=320 --height=100 --center --fixed \
        --window-icon="$ERROR" --image="$ERROR" \
        --button="Cancel"!$CANCEL:0
fi
