#!/usr/bin/env bash

# This script sets up the KiBot repository using the modern deb822 format.
# Optimized for Debian (Bullseye/Bookworm) and modern security standards.

set -e

# --- Variables ---
APP="kibot"
RELEASE="bullseye" # Toggle to "bookworm" if needed
AVAILABLE="/etc/apt/sources.list-available"
ACTIVE="/etc/apt/sources.list.d"
KEY_HOME="/usr/share/keyrings"
KEYRING="${KEY_HOME}/kibot-archive-keyring.gpg"
GPG_KEY_URL="https://set-soft.github.io/debian/kibot.gpg"

# Repository Specifics
ENABLED="yes"
TYPES="deb"
URIS="https://set-soft.github.io/debian/"
SUITES="${RELEASE}"
COMPONENTS=(main)
# ARCHITECTURES=$(dpkg --print-architecture)
ARCHITECTURES=(amd64)

# --- Prep Work ---
echo "Installing prerequisites..."
sudo apt update && sudo apt install -y wget gpg

# --- Key Management ---
echo "Importing KiBot GPG key to ${KEYRING}..."
# Using gpg --dearmor to ensure binary format for the Signed-By field
wget -qO- "$GPG_KEY_URL" | gpg --dearmor | sudo tee "$KEYRING" >/dev/null

# --- Deb822 Configuration ---
conf_print_kibot_sources() {
  cat <<EOF
Enabled: ${ENABLED}
Types: ${TYPES}
URIs: ${URIS}
Suites: ${SUITES}
Architectures: ${ARCHITECTURES[*]}
Components: ${COMPONENTS[*]}
Signed-By: ${KEYRING}
EOF
}

echo "Generating deb822 source file..."
sudo mkdir -p "$AVAILABLE"
conf_print_kibot_sources | sudo tee "${AVAILABLE}/${APP}.sources" >/dev/null

# Create symbolic link to activate the repo
# Note: Using .sources extension for DEB822 compatibility
sudo ln -sf "${AVAILABLE}/${APP}.sources" "${ACTIVE}/${APP}.sources"

# --- Installation ---
echo "Updating package lists and installing KiBot and dependencies..."
sudo apt update

# Install KiBot suite and utilities
sudo apt install -y \
  kibot \
  kicost \
  kibom.inti-cmnb \
  interactivehtmlbom.inti-cmnb \
  librsvg2-bin \
  python3-mistune \
  kikit \
  xcvt \
  kidiff

# Install Blender for 3D export
# sudo apt install -y blender

# Verify installation
kibot-check

echo "KiBot repository setup and installation complete."
