#!/bin/bash
# Panilux Repository Installation Script

set -euo pipefail

log_info() { echo "[INFO] $*"; }
log_warn() { echo "[WARN] $*" >&2; }
log_error() { echo "[ERROR] $*" >&2; }
die() { log_error "$*"; exit 1; }

require_root() {
	if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
		die "Please run as root (example: curl -fsSL https://repos.panilux.com/deb/install.sh | sudo bash)"
	fi
}

cleanup_old_install() {
	rm -f /etc/apt/sources.list.d/panilux.list
	rm -f /etc/apt/trusted.gpg.d/panilux-archive-keyring.gpg
}

apt_install_prereqs() {
	if ! command -v apt-get >/dev/null 2>&1; then
		die "apt-get not found"
	fi

	log_info "Installing prerequisites..."
	apt-get update
	DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl gnupg
}

install_gpg_key() {
	local key_url="https://repos.panilux.com/deb/panilux-archive-keyring.gpg"
	local keyring_path="/usr/share/keyrings/panilux-archive-keyring.gpg"
	local tmp_key

	log_info "Installing GPG key..."
	install -d -m 0755 /usr/share/keyrings

	tmp_key="$(mktemp)"
	if ! curl -fsSL "$key_url" -o "$tmp_key"; then
		rm -f "$tmp_key"
		die "Failed to download GPG key"
	fi

	if ! gpg --dearmor --yes --output "$keyring_path" "$tmp_key" >/dev/null 2>&1; then
		rm -f "$tmp_key"
		die "Failed to convert GPG key to a keyring file"
	fi
	rm -f "$tmp_key"

	chmod 0644 "$keyring_path"
	log_info "GPG key installed successfully"
}

add_repository() {
	local repo_url="https://repos.panilux.com/deb/"
	local keyring_path="/usr/share/keyrings/panilux-archive-keyring.gpg"
	local sources_path="/etc/apt/sources.list.d/panilux.list"

	log_info "Adding repository..."
	printf 'deb [signed-by=%s] %s %s main\n' "$keyring_path" "$repo_url" "$REPO_DISTRO" >"$sources_path"
}

update_package_list() {
	log_info "Updating package list..."
	apt-get update
}

# Detect distribution
require_root
cleanup_old_install

if [[ -f /etc/os-release ]]; then
	# shellcheck disable=SC1091
	. /etc/os-release
	case "${ID:-}" in
		debian)
			case "${VERSION_ID:-}" in
				11) REPO_DISTRO="debian11" ;;
				12) REPO_DISTRO="debian12" ;;
				*) die "Unsupported Debian version: ${VERSION_ID:-unknown}" ;;
			esac
			;;
		ubuntu)
			case "${VERSION_ID:-}" in
				20.04) REPO_DISTRO="ubuntu20" ;;
				22.04) REPO_DISTRO="ubuntu22" ;;
				24.04) REPO_DISTRO="ubuntu24" ;;
				*) die "Unsupported Ubuntu version: ${VERSION_ID:-unknown}" ;;
			esac
			;;
		*) die "Unsupported distribution: ${ID:-unknown}" ;;
	esac
else
	die "Cannot detect distribution"
fi

log_info "Detected: ${ID} ${VERSION_ID} -> ${REPO_DISTRO}"

apt_install_prereqs
install_gpg_key
add_repository
update_package_list

log_info "Panilux repository installed successfully!"
log_info "Install packages with: apt-get install <package-name>"
