#!/bin/bash
PIS_SBIN="${PIS_SBIN:-/sbin}"
if [ -z "${PIS_LIBDIR:-}" ]; then
    case "$(uname -m)" in x86_64) PIS_LIBDIR=/usr/lib64/pis ;; *) PIS_LIBDIR=/usr/lib/pis ;; esac
fi
. "$PIS_LIBDIR/pis_lib" 2>/dev/null || . "$(dirname "$0")/pis_lib" || exit 1
pis_init || exit 1
mirrors="$(pis_path /etc/slackpkg/mirrors)"
[ -r "$mirrors" ] || { pis_error "$mirrors was not found."; exit 1; }
tree="$(pis_slackpkg_tree)" || { pis_error "Unable to determine the Slackware mirror tree."; exit 1; }
items=()
while IFS= read -r url; do items+=("$url" "$tree"); done < <(
    sed -E 's/^[[:space:]]*#[[:space:]]*//' "$mirrors" | grep -E "^https?://.*/${tree}/?$" | sort -u
)
[ "${#items[@]}" -gt 0 ] || { pis_error "No HTTP(S) mirrors for $tree were found."; exit 1; }
choice=$(dialog --stdout --backtitle "$PIS_BACKTITLE" --title "Slackpkg Mirror" \
    --menu "Select one mirror. Current: $(pis_state_read slackpkg_mirror)" 0 0 14 "${items[@]}") || exit 0
if pis_apply_slackpkg_mirror "$choice"; then
    pis_info "Slackpkg Mirror" "The mirror was set to:\n$choice"
else
    pis_error "The slackpkg mirror could not be changed."
    exit 1
fi
