#!/bin/bash
# SA7AUX package repository setup.
#
#   curl -fsSL https://debrepo.sa7aux.se/setup.sh | sudo bash
#
# Detects Debian (apt) or RHEL/el9 (dnf) and wires in the sa7aux repo + GPG key,
# then refreshes the package index. After it runs you can install directly:
#   apt install  chan-svx chan-svx-sat chan-pbx-sat pbxsat-freepbx   (Debian)
#   dnf install  chan-pbx-sat pbxsat-freepbx                          (el9)
set -euo pipefail

BASE="https://debrepo.sa7aux.se"

if [ "$(id -u)" -ne 0 ]; then echo "run as root (sudo)"; exit 1; fi

if command -v apt-get >/dev/null 2>&1 && [ -f /etc/debian_version ]; then
    # ---- Debian (apt) ----
    . /etc/os-release
    SUITE="${VERSION_CODENAME:-}"
    case "$SUITE" in
        bookworm|trixie) ;;
        *) echo "!! sa7aux has no apt section for '${SUITE:-unknown}' (need Debian bookworm or trixie)"; exit 1 ;;
    esac
    apt-get update -qq >/dev/null 2>&1 || true
    apt-get install -y --no-install-recommends curl ca-certificates gnupg >/dev/null
    install -d -m 0755 /etc/apt/keyrings
    curl -fsSL "$BASE/sa7aux.gpg" -o /etc/apt/keyrings/sa7aux.gpg
    cat > /etc/apt/sources.list.d/sa7aux.sources <<EOF
Types: deb
URIs: $BASE/sa7aux-$SUITE
Suites: ./
Components:
Signed-By: /etc/apt/keyrings/sa7aux.gpg
EOF
    apt-get update
    echo ">> sa7aux apt repo klart ($SUITE). Installera t.ex.:"
    echo "     apt install chan-svx chan-svx-sat        # asl3/AllStar"
    echo "     apt install chan-pbx-sat pbxsat-freepbx   # FreePBX (bookworm)"

elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then
    # ---- RHEL / el9 (dnf) ----
    PM="$(command -v dnf || command -v yum)"
    curl -fsSL "$BASE/sa7aux-el9.repo" -o /etc/yum.repos.d/sa7aux-el9.repo
    rpm --import "$BASE/sa7aux-rpm-key.asc" 2>/dev/null || true
    "$PM" makecache >/dev/null 2>&1 || true
    echo ">> sa7aux dnf repo klart (el9). Installera t.ex.:"
    echo "     dnf install chan-pbx-sat pbxsat-freepbx"

else
    echo "!! okänt OS — hittade varken apt eller dnf"; exit 1
fi
