#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Installs MiracleIRC on FreeBSD, built from the source tarball on the CDN.
# The .deb there is a Linux binary; this builds the same release natively.
#
#   fetch -o - https://cdn.thern.io/files/freebsd/install-miracleirc.sh | sh
#
# Run it again to update to the newest build, or with --uninstall to remove
# what it installed. As root, or as a user with sudo or doas.
#
# MIRACLE_SRC_URL points it somewhere other than the CDN, PREFIX somewhere
# other than /usr/local.

set -eu

SRC_URL=${MIRACLE_SRC_URL:-https://cdn.thern.io/files/freebsd}
PREFIX=${PREFIX:-/usr/local}
MANIFEST=$PREFIX/share/miracleirc/install_manifest.txt
DEPS="qt6-base cmake-core ninja pkgconf"

say() { printf '==> %s\n' "$*"; }
die() { printf 'install-miracleirc: %s\n' "$*" >&2; exit 1; }

[ "$(uname -s)" = FreeBSD ] || die "this is for FreeBSD; Debian and Ubuntu have apt"

if [ "$(id -u)" -eq 0 ]; then
    AS_ROOT=
elif command -v doas >/dev/null 2>&1; then
    AS_ROOT=doas
elif command -v sudo >/dev/null 2>&1; then
    AS_ROOT=sudo
else
    die "run as root, or install sudo or doas"
fi

if [ "${1:-}" = --uninstall ]; then
    [ -f "$MANIFEST" ] || die "nothing to remove: $MANIFEST is not there"
    say "Removing MiracleIRC from $PREFIX"
    # The manifest lists files only, one per line.
    while IFS= read -r file; do
        $AS_ROOT rm -f "$file"
    done <"$MANIFEST"
    $AS_ROOT rm -f "$MANIFEST"
    $AS_ROOT rmdir "$PREFIX/share/miracleirc" 2>/dev/null || true
    say "Done. The build dependencies ($DEPS) are still installed."
    exit 0
fi

say "Installing build dependencies: $DEPS"
$AS_ROOT env ASSUME_ALWAYS_YES=yes pkg install -y $DEPS

WORK=$(mktemp -d -t miracleirc)
trap 'rm -rf "$WORK"' EXIT INT TERM
cd "$WORK"

say "Looking up the newest build at $SRC_URL"
fetch -q -o latest "$SRC_URL/miracleirc.latest"
read -r TARBALL SUM <latest
case $TARBALL in
    miracleirc-*.tar.gz) ;;
    *) die "unexpected miracleirc.latest: $TARBALL" ;;
esac

say "Fetching $TARBALL"
fetch -q -o "$TARBALL" "$SRC_URL/$TARBALL"
[ "$(sha256 -q "$TARBALL")" = "$SUM" ] || die "$TARBALL does not match its checksum"
tar -xzf "$TARBALL"

say "Building (this takes a few minutes)"
cmake -S "${TARBALL%.tar.gz}" -B build -G Ninja \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX="$PREFIX" \
    -DMIRACLE_BUILD_TESTS=OFF >/dev/null
cmake --build build -j"$(sysctl -n hw.ncpu)"

say "Installing to $PREFIX"
$AS_ROOT cmake --install build --strip >/dev/null
$AS_ROOT mkdir -p "$(dirname "$MANIFEST")"
$AS_ROOT cp build/install_manifest.txt "$MANIFEST"

say "Installed ${TARBALL%.tar.gz}. Start it with: miracle"
if ! pkg info -e oidentd 2>/dev/null; then
    say "Optional: 'pkg install oidentd' gives servers your user name without a ~"
fi
