#!/usr/bin/env bash
# setup-redpanda.deb.sh — Configure the Redpanda stable apt repository (GCP Artifact Registry).
#
# This script is intentionally self-contained — it is distributed as a
# standalone file and fetched directly via: curl ... | sudo bash
#
# Configures /etc/apt/sources.list.d/redpanda.list to point to the GCP AR
# apt repository. Does NOT install any packages.
#
# Usage:
#   curl -fsSL --tlsv1.2 https://linux.pkg.redpanda.com/setup-redpanda.deb.sh | sudo bash
#   sudo bash setup-redpanda.deb.sh

set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

AR_REPO="redpanda-apt"
KEYRING="/usr/share/keyrings/artifact-registry.gpg"
SOURCES="/etc/apt/sources.list.d/redpanda.list"
LOG=$(mktemp /tmp/redpanda-setup-XXXXXX.log)

# --- Helpers ---

if [[ -t 1 ]]; then
  GREEN='\e[32m'
  RED='\e[31m'
  RESET='\e[0m'
  BOLD='\e[1m'
else
  GREEN=''
  RED=''
  RESET=''
  BOLD=''
fi

trap 'rm -f "$LOG"' EXIT

log() { echo -e "${BOLD}==> $*${RESET}"; }
ok() { echo -e "${GREEN} OK${RESET}: $*"; }
fail() { echo -e "${RED}FAIL${RESET}: $*" >&2; }
die() {
  fail "$*"
  echo "     log: $LOG" >&2
  trap - EXIT
  exit 1
}

check_tool() {
  command -v "$1" &>/dev/null || die "'$1' is required but not found"
}

import_gpg_key() {
  curl -fsSL --tlsv1.2 --retry 7 --retry-delay 2 https://linux.pkg.redpanda.com/redpanda-deb-signing-public.gpg |
    gpg --dearmor --batch >"$KEYRING" 2>>"$LOG" ||
    die "Failed to fetch Redpanda GPG signing key"
  chmod 644 "$KEYRING"
  [[ -s $KEYRING ]] || die "GPG keyring is empty after fetch"
}

# --- Main ---

if [[ $EUID -ne 0 ]]; then
  die "must run as root (sudo bash)"
fi

check_tool apt-get

log "Configuring Redpanda apt repository (stable)..."

log "Installing prerequisites..."
apt-get update -qq &>>"$LOG" || die "initial apt-get update failed — see log"
apt-get install -y --no-install-recommends apt-transport-https ca-certificates curl gnupg &>>"$LOG" || die "Failed to install prerequisites — see log"
ok "Prerequisites installed"

log "Importing Google Artifact Registry signing key..."
import_gpg_key
ok "GPG key imported"

log "Writing apt source..."
[[ -f $SOURCES ]] && log "Warning: overwriting existing repo config at $SOURCES"
printf 'deb [signed-by=%s] https://linux.pkg.redpanda.com/apt %s main\n' \
  "$KEYRING" "$AR_REPO" \
  >"$SOURCES"
chmod 644 "$SOURCES"
ok "Wrote $SOURCES"

log "Updating apt cache..."
apt-get update &>>"$LOG" || die "apt-get update failed — see log"
ok "apt cache updated"

echo
echo -e "${GREEN}${BOLD}Repository configured successfully.${RESET}"
echo
echo "Repository file:    $SOURCES"
echo "  View:             cat $SOURCES"
echo
echo "Available packages:"
echo "  List:             apt-cache show redpanda"
echo
echo "Install:"
echo "  Latest:           apt-get install redpanda"
echo "  Specific version: apt-get install redpanda=<version>"
