#!/usr/bin/env bash
set -euo pipefail
main() {
    local channel=stable fingerprint family
    while (( $# )); do
        case "$1" in
            --channel) [[ $# -ge 2 ]] || return 2; channel=$2; shift 2 ;;
            --help) echo 'Usage: install.sh [--channel stable|beta|alpha]'; return ;;
            *) echo "Unknown argument: $1" >&2; return 2 ;;
        esac
    done
    [[ $channel == stable || $channel == beta || $channel == alpha ]] || { echo 'Invalid channel' >&2; return 2; }
    [[ $(uname -m) == x86_64 ]] || { echo 'Only x86_64 is supported.' >&2; return 1; }
    # shellcheck source=/dev/null
    . /etc/os-release
    case " ${ID:-} ${ID_LIKE:-} " in
        *' arch '*) family=arch ;;
        *' debian '*|*' ubuntu '*) family=apt ;;
        *) echo 'Supported systems: Arch derivatives, Debian and Ubuntu derivatives.' >&2; return 1 ;;
    esac
    local -a elevate=()
    if (( EUID != 0 )); then elevate=(sudo); fi
    command -v curl >/dev/null
    command -v gpg >/dev/null || { echo 'Install gnupg first, then rerun this installer.' >&2; return 1; }
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    curl --proto '=https' -fsSL https://pkgs.signalrgb.com/signalrgb-archive-keyring.asc -o "$tmp/key.asc"
    gpg --batch --show-keys --with-colons "$tmp/key.asc" > "$tmp/key-info"
    [[ $(grep -c '^pub:' "$tmp/key-info") == 1 ]] || { echo 'Expected exactly one vendor key.' >&2; return 1; }
    fingerprint=$(awk -F: '$1 == "pub" {n++} $1 == "fpr" && n == 1 && !seen++ {print $10}' "$tmp/key-info")
    [[ $fingerprint == 9732D971D1DFC80AF59B30107A22FD695C82F229 ]] || { echo 'Signing key fingerprint mismatch.' >&2; return 1; }
    if [[ $family == apt ]]; then
        "${elevate[@]}" install -Dm644 "$tmp/key.asc" /etc/apt/keyrings/signalrgb.asc
        cat > "$tmp/signalrgb.sources" <<SOURCES
Types: deb
URIs: https://pkgs.signalrgb.com/apt
Suites: $channel
Components: main
Architectures: amd64
Signed-By: /etc/apt/keyrings/signalrgb.asc
SOURCES
        "${elevate[@]}" install -m644 "$tmp/signalrgb.sources" /etc/apt/sources.list.d/signalrgb.sources
        "${elevate[@]}" apt-get update
        "${elevate[@]}" apt-get install signalrgb </dev/tty
    else
        "${elevate[@]}" pacman-key --add "$tmp/key.asc"
        "${elevate[@]}" pacman-key --lsign-key "$fingerprint"
        printf '[signalrgb]\nSigLevel = Required DatabaseOptional\nServer = https://pkgs.signalrgb.com/arch/%s/$arch\n' "$channel" > "$tmp/signalrgb.conf"
        "${elevate[@]}" install -Dm644 "$tmp/signalrgb.conf" /etc/pacman.d/signalrgb.conf
        if ! grep -Eq '^Include[[:space:]]*=[[:space:]]*/etc/pacman.d/signalrgb.conf[[:space:]]*$' /etc/pacman.conf; then
            printf '\nInclude = /etc/pacman.d/signalrgb.conf\n' | "${elevate[@]}" tee -a /etc/pacman.conf >/dev/null
        fi
        # Sync only our new repository. Refreshing the distribution databases
        # without upgrading the system would introduce a partial-upgrade risk.
        # Install against the user's existing distribution databases instead;
        # system updates (including Omarchy migrations) remain their decision.
        printf '[options]\nArchitecture = auto\n' > "$tmp/pacman-sync.conf"
        cat "$tmp/signalrgb.conf" >> "$tmp/pacman-sync.conf"
        "${elevate[@]}" pacman --config "$tmp/pacman-sync.conf" -Sy </dev/tty
        "${elevate[@]}" pacman -S --needed signalrgb </dev/tty
        "${elevate[@]}" pacman -Q signalrgb >/dev/null || {
            echo 'SignalRGB installation was cancelled or did not complete.' >&2
            return 1
        }
    fi
    echo "SignalRGB installed from $channel. Launch SignalRGB from your application menu."
    rm -rf "$tmp"
    trap - EXIT
}
main "$@"
