#!/bin/sh
# =============================================================================
#  TechEve APT repository — client setup
#
#  Adds (or removes) the https://repo.techeve.de package repository on a
#  Debian- or Ubuntu-based system.
#
#  Quick install:
#      curl -fsSL https://repo.techeve.de/setup.sh | sudo sh
#  or:
#      wget -qO- https://repo.techeve.de/setup.sh | sudo sh
#
#  Uninstall:
#      curl -fsSL https://repo.techeve.de/setup.sh | sudo sh -s -- --uninstall
#
#  POSIX sh, no bashisms — runs on minimal images too.
# =============================================================================
set -eu

# --- configuration (override via environment if ever needed) -----------------
REPO_HOST="${REPO_HOST:-repo.techeve.de}"
REPO_URL="${REPO_URL:-https://${REPO_HOST}}"
SUITE="${SUITE:-stable}"
COMPONENTS="${COMPONENTS:-main}"
KEYRING="/etc/apt/keyrings/techeve-repo.gpg"
SOURCES="/etc/apt/sources.list.d/techeve.sources"
KEY_URL="${REPO_URL}/repo-key.gpg"

# --- pretty output -----------------------------------------------------------
if [ -t 1 ]; then B="$(printf '\033[1m')"; G="$(printf '\033[32m')"; Y="$(printf '\033[33m')"; R="$(printf '\033[31m')"; N="$(printf '\033[0m')"; else B=; G=; Y=; R=; N=; fi
info() { printf '%s==>%s %s\n' "$G$B" "$N" "$*"; }
warn() { printf '%s!!%s  %s\n' "$Y$B" "$N" "$*" >&2; }
die()  { printf '%serror:%s %s\n' "$R$B" "$N" "$*" >&2; exit 1; }

ACTION=install
for arg in "$@"; do
  case "$arg" in
    --uninstall|--remove) ACTION=uninstall ;;
    -h|--help)
      sed -n '2,20p' "$0" 2>/dev/null | sed 's/^#\{0,1\} \{0,1\}//'
      exit 0 ;;
    *) die "unknown argument: $arg (use --uninstall or --help)" ;;
  esac
done

# --- must be root ------------------------------------------------------------
[ "$(id -u)" -eq 0 ] || die "please run as root (e.g. pipe into 'sudo sh')."

# --- must be Debian/Ubuntu family -------------------------------------------
[ -r /etc/os-release ] || die "/etc/os-release not found — unsupported system."
. /etc/os-release
case " ${ID:-} ${ID_LIKE:-} " in
  *" debian "*|*" ubuntu "*) : ;;
  *) die "this repository targets Debian/Ubuntu; detected ID='${ID:-?}'." ;;
esac
command -v apt-get >/dev/null 2>&1 || die "apt-get not found — not an APT-based system."

# --- uninstall path ----------------------------------------------------------
if [ "$ACTION" = uninstall ]; then
  info "Removing TechEve repository"
  rm -f "$SOURCES" && info "removed $SOURCES" || true
  rm -f "$KEYRING" && info "removed $KEYRING" || true
  apt-get update -qq || true
  info "Done. The repository has been removed."
  exit 0
fi

# --- pick a downloader -------------------------------------------------------
if command -v curl >/dev/null 2>&1; then
  DL="curl -fsSL"
elif command -v wget >/dev/null 2>&1; then
  DL="wget -qO-"
else
  info "Neither curl nor wget present — installing curl"
  apt-get update -qq
  apt-get install -y -qq --no-install-recommends curl ca-certificates
  DL="curl -fsSL"
fi

# ensure TLS trust store exists
if [ ! -d /etc/ssl/certs ] || [ -z "$(ls -A /etc/ssl/certs 2>/dev/null)" ]; then
  apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates
fi

info "Installing signing key from ${KEY_URL}"
install -d -m 0755 /etc/apt/keyrings
tmpkey="$(mktemp)"
# shellcheck disable=SC2086
$DL "$KEY_URL" > "$tmpkey" || die "could not download the signing key from $KEY_URL"
[ -s "$tmpkey" ] || die "downloaded key is empty — check $REPO_URL is reachable."
# Accept either a binary keyring or an ASCII-armored key and store as binary keyring.
if grep -q "BEGIN PGP PUBLIC KEY" "$tmpkey" 2>/dev/null; then
  gpg --dearmor < "$tmpkey" > "$KEYRING"
else
  cat "$tmpkey" > "$KEYRING"
fi
chmod 0644 "$KEYRING"
rm -f "$tmpkey"

info "Writing source list ${SOURCES}"
cat > "$SOURCES" <<EOF
# TechEve package repository — managed by techeve-repo-setup.sh
Types: deb
URIs: ${REPO_URL}
Suites: ${SUITE}
Components: ${COMPONENTS}
Architectures: $(dpkg --print-architecture)
Signed-By: ${KEYRING}
EOF

info "Refreshing package lists"
apt-get update -qq

printf '\n%sTechEve repository is ready.%s\n' "$G$B" "$N"
printf '  Source:  %s\n' "$SOURCES"
printf '  Keyring: %s\n' "$KEYRING"
printf '  URL:     %s  (suite: %s, components: %s)\n\n' "$REPO_URL" "$SUITE" "$COMPONENTS"
printf 'Install a package with, e.g.:\n  %ssudo apt-get install <package>%s\n' "$B" "$N"
