#!/bin/sh
# xcon-db installer.
#
#   curl -fsSL https://apt.xcon-db.com/install.sh | sudo sh
#
# Adds the signed apt repository and installs the xcon-db package on
# Debian/Ubuntu. Safe to re-run: every step is idempotent. The source
# of truth for this file is xcon-db-server/docs/install.sh; the served
# copy lives at /srv/apt/xcon-db/install.sh on the repo host.
set -eu

REPO="https://apt.xcon-db.com"
KEYRING="/usr/share/keyrings/xcon-db.gpg"
LIST="/etc/apt/sources.list.d/xcon-db.list"

fail() { echo "xcon-db install: $*" >&2; exit 1; }

# The classic mistake is pasting this into the laptop instead of the
# server — catch it with a message that says where to go.
[ "$(uname -s)" = "Linux" ] || fail "this installs a Linux server package — you are on $(uname -s). SSH into the target machine and run it there."
[ -e /etc/debian_version ] || fail "this system has no apt — supported: Debian 12+ and Ubuntu 22.04+."
command -v apt-get >/dev/null 2>&1 || fail "apt-get not found — supported: Debian 12+ and Ubuntu 22.04+."
[ "$(id -u)" = "0" ] || fail "root needed. Run:  curl -fsSL $REPO/install.sh | sudo sh"

ARCH=$(dpkg --print-architecture)
[ "$ARCH" = "amd64" ] || fail "only amd64 packages are published today; this machine is $ARCH."

export DEBIAN_FRONTEND=noninteractive

# Minimal images ship without curl or gpg; fetch them first.
need=""
command -v curl >/dev/null 2>&1 || need="$need curl ca-certificates"
command -v gpg >/dev/null 2>&1 || need="$need gnupg"
if [ -n "$need" ]; then
    echo "xcon-db install: fetching prerequisites:$need"
    apt-get update -qq
    # shellcheck disable=SC2086 # word splitting is the point
    apt-get install -y -qq --no-install-recommends $need
fi

echo "xcon-db install: trusting the repository signing key"
curl -fsSL "$REPO/KEY.asc" | gpg --dearmor --yes -o "$KEYRING"
chmod 644 "$KEYRING"

echo "xcon-db install: adding the repository"
echo "deb [signed-by=$KEYRING] $REPO stable main" > "$LIST"

echo "xcon-db install: installing the package"
apt-get update -qq
apt-get install -y xcon-db

echo
echo "xcon-db install: done. If this is a fresh install, the setup"
echo "wizard address and its one-time key are printed just above;"
echo "check the service with:  systemctl status xcon-db"
