#!/bin/sh
# logor installer.
#
#   curl -fsSL https://apt.logor.cloud/install.sh | sudo sh
#
# Adds the signed apt repository and installs the logor package on
# Debian/Ubuntu. Safe to re-run: every step is idempotent. The source
# of truth for this file is logor-engine/docs/install.sh (the repo is
# private — this served copy at /srv/apt/logor/install.sh is the
# public face); deploy a change with scp + install -m644.
set -eu

REPO="https://apt.logor.cloud"
KEYRING="/usr/share/keyrings/logor.gpg"
LIST="/etc/apt/sources.list.d/logor.list"

fail() { echo "logor 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 is 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 "logor 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 "logor install: trusting the repository signing key"
curl -fsSL "$REPO/KEY.asc" | gpg --dearmor --yes -o "$KEYRING"
chmod 644 "$KEYRING"

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

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

echo
echo "logor install: done. The first-run wizard's address is printed"
echo "just above; check the service with:  systemctl status logor"
