#!/bin/bash

set -euo pipefail

REPO_BASE_URL="https://packages.omoti.work/debian"
KEYRING_FILE="/usr/share/keyrings/omoti-packages-archive-keyring.asc"
REPO_SUITE="${1:-stable}"
REPO_LIST_FILE="/etc/apt/sources.list.d/omoti-packages-${REPO_SUITE}.list"
ARCHITECTURE="$(dpkg --print-architecture)"

case "${REPO_SUITE}" in
  stable|beta)
    ;;
  *)
    echo "Usage: $0 [stable|beta]" >&2
    exit 1
    ;;
esac

# Step 1: Install the repository keyring
wget -qO - "${REPO_BASE_URL}/public.key" | sudo tee "${KEYRING_FILE}" > /dev/null
sudo chmod 644 "${KEYRING_FILE}"

# Step 2: Add the repository source
sudo bash -c "cat > \"${REPO_LIST_FILE}\" <<EOF
deb [arch=${ARCHITECTURE} signed-by=${KEYRING_FILE}] ${REPO_BASE_URL}/ ${REPO_SUITE} non-free
EOF"
sudo chmod 644 "${REPO_LIST_FILE}"

# Step 3: Refresh package metadata
sudo apt-get update

echo "Repository ${REPO_SUITE} added and package list updated."
