#!/usr/bin/env bash
set -euo pipefail

KEYRING_URL='https://repo.beryllium.gr/repo/Beryllium/aarch64/beryllium-keyring-20260322-1-any.pkg.tar.zst'
MIRRORLIST_URL='https://repo.beryllium.gr/repo/Beryllium/aarch64/beryllium-mirrorlist-20260429-2-any.pkg.tar.zst'

require_root() {
    if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
        echo "This script must be run as root." >&2
        exit 1
    fi
}

download_file() {
    local url="$1"
    local out="$2"

    if command -v curl >/dev/null 2>&1; then
        curl -fL --retry 3 --connect-timeout 10 -o "$out" "$url"
        return 0
    fi

    if command -v wget >/dev/null 2>&1; then
        wget -qO "$out" "$url"
        return 0
    fi

    if command -v python3 >/dev/null 2>&1; then
        python3 - "$url" "$out" <<'PY'
import sys
from urllib.request import urlopen, Request

url, out = sys.argv[1], sys.argv[2]
req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urlopen(req) as r, open(out, "wb") as f:
    f.write(r.read())
PY
        return 0
    fi

    echo "No downloader found. Need curl, wget, or python3." >&2
    return 1
}

install_mirrorlist_if_staged() {
    if [[ -f /etc/pacman.d/beryllium-mirrorlist-new ]]; then
        install -m 0644 -T /etc/pacman.d/beryllium-mirrorlist-new /etc/pacman.d/beryllium-mirrorlist
        rm -f /etc/pacman.d/beryllium-mirrorlist-new
    fi
}

main() {
    require_root

    local tmpdir keyring_pkg mirrorlist_pkg

    tmpdir="$(mktemp -d)" || exit 1
    trap "rm -rf '$tmpdir'" EXIT

    keyring_pkg="$tmpdir/beryllium-keyring-20260322-1-any.pkg.tar.zst"
    mirrorlist_pkg="$tmpdir/beryllium-mirrorlist-20260401-1-any.pkg.tar.zst"

    echo "Downloading beryllium keyring..."
    download_file "$KEYRING_URL" "$keyring_pkg"

    echo "Downloading beryllium mirrorlist..."
    download_file "$MIRRORLIST_URL" "$mirrorlist_pkg"

    echo "Installing packages with pacman..."
    pacman -U --noconfirm "$keyring_pkg" "$mirrorlist_pkg"

    install_mirrorlist_if_staged
}

main "$@"
