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

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

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

[ "$(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

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-quee install: fetching prerequisites:$need"
    apt-get update -qq
    # shellcheck disable=SC2086
    apt-get install -y -qq --no-install-recommends $need
fi

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

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

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

echo
echo "xcon-quee install: done. The setup wizard address and its one-time"
echo "key are printed just above; check the service with:"
echo "  systemctl status xcon-quee"
