#!/bin/sh
# Add the Excelano apt repository to this system.
#
#   curl -fsSL https://excelano.com/apt/setup.sh | sudo sh
#
# Idempotent: safe to re-run. Installs the signing key, registers the
# source, and runs 'apt update'. Does NOT install any tools — it prints
# the install line at the end so you choose what to install.

set -eu

KEYRING=/usr/share/keyrings/excelano-archive-keyring.gpg
LIST=/etc/apt/sources.list.d/excelano.list
KEY_URL=https://excelano.com/apt/excelano-archive-keyring.gpg
REPO_LINE="deb [signed-by=$KEYRING] https://excelano.com/apt stable main"

# Use sudo for privileged steps only when not already root (so the script
# works both as 'curl | sudo sh' and 'curl | sh').
if [ "$(id -u)" -eq 0 ]; then
    SUDO=""
else
    SUDO="sudo"
fi

if ! command -v apt-get >/dev/null 2>&1; then
    echo "Error: no apt-get found. The Excelano repo is for Debian/Ubuntu." >&2
    exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
    echo "Error: curl is required." >&2
    exit 1
fi

# Download the key to a temp file first. POSIX sh has no pipefail, so a
# direct 'curl | tee' would silently write an empty keyring if curl failed.
TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT
echo "Fetching signing key"
if ! curl -fsSL "$KEY_URL" -o "$TMP"; then
    echo "Error: failed to download key from $KEY_URL" >&2
    exit 1
fi
if [ ! -s "$TMP" ]; then
    echo "Error: downloaded key is empty." >&2
    exit 1
fi

echo "Installing key -> $KEYRING"
$SUDO install -D -m 0644 "$TMP" "$KEYRING"

echo "Registering source -> $LIST"
echo "$REPO_LINE" | $SUDO tee "$LIST" >/dev/null

echo "Refreshing package lists"
$SUDO apt-get update

cat <<'EOF'

Excelano apt repository added.

Install the tools:
  sudo apt install ved spsql sqlcsv xql checkin paxc

Updates flow through 'apt upgrade' from here on.
EOF
