#!/bin/bash
# APT Repository Setup Script
# Generated for: apt.renesas.kaylordut.com
# Auto-detects CPU arch and Ubuntu version.
# Adds common (all) + distro-specific sources.
set -e

REPO_HOST="apt.renesas.kaylordut.com"
GPG_NAME="renesas_pai"
KEYRING="/usr/share/keyrings/${GPG_NAME}-archive-keyring.asc"
LIST_FILE="/etc/apt/sources.list.d/${GPG_NAME}.list"

# ---- Auto-detect CPU architecture ----
ARCH=$(dpkg --print-architecture 2>/dev/null || uname -m)
case "$ARCH" in
    x86_64)  ARCH=amd64 ;;
    aarch64) ARCH=arm64 ;;
esac

# ---- Auto-detect Ubuntu version ----
if command -v lsb_release &>/dev/null; then
    DISTRO=$(lsb_release -cs)
else
    DISTRO=$(grep VERSION_CODENAME /etc/os-release 2>/dev/null | cut -d= -f2 || echo "")
fi

echo ">>> CPU: $ARCH | Distro: ${DISTRO:-unknown} | Channels: stable,devel"

# ---- Import GPG key ----
sudo curl -fsSL "http://${REPO_HOST}/${GPG_NAME}-public-key.asc" \
    -o "${KEYRING}"

# ---- Add sources ----
sudo rm -f "${LIST_FILE}"

# Common repo (always — works on all distros)
echo "deb [arch=${ARCH} signed-by=${KEYRING}] http://${REPO_HOST}/ all stable" | sudo tee -a "${LIST_FILE}" > /dev/null
echo "deb [arch=${ARCH} signed-by=${KEYRING}] http://${REPO_HOST}/ all devel" | sudo tee -a "${LIST_FILE}" > /dev/null

# Distro-specific repo (only if detected distro is known)
case "$DISTRO" in
  jammy|noble|focal|trixie)
echo "deb [arch=${ARCH} signed-by=${KEYRING}] http://${REPO_HOST}/ ${DISTRO} stable" | sudo tee -a "${LIST_FILE}" > /dev/null
echo "deb [arch=${ARCH} signed-by=${KEYRING}] http://${REPO_HOST}/ ${DISTRO} devel" | sudo tee -a "${LIST_FILE}" > /dev/null
    ;;
esac

# ---- APT pin priorities (stable > devel) ----
PREF_FILE="/etc/apt/preferences.d/${GPG_NAME}.pref"
sudo rm -f "${PREF_FILE}"

# stable channel: highest priority (default 990) so 'apt install' prefers stable
cat <<EOF | sudo tee "${PREF_FILE}" > /dev/null
Package: *
Pin: release c=stable
Pin-Priority: 990

Package: *
Pin: release c=devel
Pin-Priority: 500
EOF

echo ">>> APT pin priorities: stable=990 (preferred) > devel=500"

# ---- Update ----
sudo apt update

echo ">>> Done!"
echo ">>> Sources added:"
cat "${LIST_FILE}"
echo ">>> Usage: sudo apt install <package>"
