#!/usr/bin/env bash
# ============================================================
# CYHD APT Repository Setup Script
#
# Usage:
#   curl -fsSL https://repo.chengyistudio.com/setup.sh | sudo bash
#
# What this script does:
#   1. Downloads and installs the CYHD GPG signing key
#   2. Adds the CYHD APT repository source
#   3. Updates the package index
#   4. Optionally installs the cyhd package
#
# Copyright (c) 2025-2026 Chengdu Chengyi Future Technology Co., Ltd.
# ============================================================

set -euo pipefail

# --- Configuration ---
REPO_URL="https://repo.chengyistudio.com"
GPG_KEY_URL="${REPO_URL}/cyhd.gpg"
KEYRING_PATH="/usr/share/keyrings/cyhd.gpg"
SOURCE_LIST="/etc/apt/sources.list.d/cyhd.list"
CODENAME="noble"
COMPONENT="main"
PACKAGE_NAME="cyhd"

# --- Colors ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# --- Pre-checks ---
echo ""
echo "======================================"
echo "  CYHD APT Repository Setup"
echo "======================================"
echo ""

if [ "$(id -u)" -ne 0 ]; then
    error "This script must be run as root. Try: curl -fsSL ${REPO_URL}/setup.sh | sudo bash"
fi

# Check architecture
ARCH=$(dpkg --print-architecture 2>/dev/null || echo "unknown")
if [ "$ARCH" != "amd64" ]; then
    warn "CYHD currently only supports amd64 architecture. Detected: ${ARCH}"
    read -p "Continue anyway? [y/N] " -n 1 -r
    echo
    [[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
fi

# Check required tools
for cmd in curl tee; do
    if ! command -v "$cmd" &>/dev/null; then
        error "'$cmd' is required but not found. Install it with: apt-get install -y $cmd"
    fi
done

# --- Step 1: Install GPG Key ---
info "Downloading GPG signing key..."

if curl -fsSL "$GPG_KEY_URL" -o "$KEYRING_PATH"; then
    ok "GPG key installed → ${KEYRING_PATH}"
else
    error "Failed to download GPG key from ${GPG_KEY_URL}"
fi

chmod 644 "$KEYRING_PATH"

# --- Step 2: Add APT Source ---
info "Configuring APT repository..."

# Remove old openradar source if it exists
if [ -f /etc/apt/sources.list.d/openradar.list ]; then
    rm -f /etc/apt/sources.list.d/openradar.list
    warn "Removed legacy source: /etc/apt/sources.list.d/openradar.list"
fi

# Remove old keyring if it exists
if [ -f /usr/share/keyrings/openradar.gpg ]; then
    rm -f /usr/share/keyrings/openradar.gpg
    warn "Removed legacy keyring: /usr/share/keyrings/openradar.gpg"
fi

echo "deb [signed-by=${KEYRING_PATH} arch=${ARCH}] ${REPO_URL} ${CODENAME} ${COMPONENT}" \
    | tee "$SOURCE_LIST" > /dev/null

ok "APT source configured → ${SOURCE_LIST}"

# --- Step 3: Update Package Index ---
info "Updating package index..."

if apt-get update -qq -o Dir::Etc::sourcelist="$SOURCE_LIST" -o Dir::Etc::sourceparts="-" 2>/dev/null; then
    ok "Package index updated successfully."
else
    warn "apt-get update had warnings. This is usually fine."
fi

# --- Step 4: Show Available Package ---
echo ""
echo "======================================"
echo "  Setup Complete!"
echo "======================================"
echo ""

AVAILABLE=$(apt-cache policy "$PACKAGE_NAME" 2>/dev/null | grep -i "candidate" | awk '{print $2}')

if [ -n "$AVAILABLE" ] && [ "$AVAILABLE" != "(none)" ]; then
    ok "CYHD v${AVAILABLE} is available for installation."
    echo ""
    echo "  Install with:    sudo apt install ${PACKAGE_NAME}"
    echo "  Remove with:     sudo apt remove ${PACKAGE_NAME}"
    echo "  Uninstall repo:  sudo rm ${SOURCE_LIST} ${KEYRING_PATH}"
else
    warn "Package '${PACKAGE_NAME}' not found. Repository may not have packages yet."
fi

echo ""
