#!/bin/bash
# Installs (or updates) LibreAccess on a Debian or Ubuntu server, then shows an invite for the LibrePortal app.
#
#   curl -fsSL https://get.libreportal.org/libreaccess.sh | sudo bash
#   curl -fsSL https://get.libreportal.org/libreaccess.sh | sudo bash -s -- --version v0.1.1   (a chosen release; or LIBREACCESS_VERSION=v0.1.1)
#   curl -fsSL https://get.libreportal.org/libreaccess.sh | sudo bash -s -- --no-invite        (install or update only)
#
# Nothing is installed unless the package matches its published sha256 AND carries a good signature from the LibrePortal release key,
# for exactly that version. Running it again updates LibreAccess; it replaces an unused invite with a new one and never adds keys.
set -euo pipefail

INSTALLER_VERSION="0.1.1"
LATEST_BASE="https://libreportal.org/download"                                        # the newest release
RELEASE_BASE="https://git.libreportal.org/LibrePortal/LibreAccess/releases/download"  # a chosen release: <base>/vX.Y.Z/<file>
# LibrePortal release signing key (libreportal.pub in the LibrePortal repository)
PUBKEY="RWRBf8o+a1KSvF08fA3oKrVz/71D60YeF4GO66ntVeJvzAkI57sjgM1S"

say()  { printf '==> %s\n' "$*"; }
fail() { printf '\nLibreAccess was not installed: %s\n' "$*" >&2; exit 1; }

usage() {
    cat <<'U'
Installs or updates LibreAccess, then shows an invite for the LibrePortal app.
  --version vX.Y.Z   install that release instead of the newest (or set LIBREACCESS_VERSION)
  --no-invite        do not show an invite
U
}

fetch() { # <url> <file>   https only; returns curl's status (22 = the server answered with an error such as 404)
    curl -fsSL --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 300 --retry 2 -o "$2" "$1"
}
apt_get() { DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=300 "$@" </dev/null; }
APT_FRESH=0
apt_refresh() {
    (( APT_FRESH )) && return 0
    say "Refreshing the package lists"
    apt_get update -qq >/dev/null || say "Some package lists could not be refreshed; carrying on"
    APT_FRESH=1
}

check_system() {
    [[ "$(id -u)" == 0 ]] || fail "it needs root. Run:  curl -fsSL https://get.libreportal.org/libreaccess.sh | sudo bash"
    local id="" like=""
    if [[ -r /etc/os-release ]]; then
        id="$(. /etc/os-release && printf '%s' "${ID:-}")"; like="$(. /etc/os-release && printf '%s' "${ID_LIKE:-}")"
    fi
    [[ " $id $like " == *" debian "* || " $id $like " == *" ubuntu "* ]] && command -v apt-get >/dev/null 2>&1 \
        || fail "this installer is for Debian and Ubuntu servers (this one says: ${id:-unknown})."
    command -v curl >/dev/null 2>&1 || fail "curl is missing (apt install curl)."
}

need_minisign() {
    command -v minisign >/dev/null 2>&1 && return 0
    apt_refresh
    say "Installing minisign, to check the signature"
    apt_get install -y -qq minisign >/dev/null || fail "could not install minisign, so the signature cannot be checked (on Ubuntu it is in the 'universe' repository)."
}

# Sets VER, WANT_SHA, DEB (a verified file in $WORK).
get_package() { # <wanted version, or empty for the newest>
    local want="$1" url sigurl rc=0
    if [[ -z "$want" ]]; then
        say "Looking up the newest LibreAccess"
        fetch "$LATEST_BASE/libreaccess-linux.json" "$WORK/latest.json" || fail "could not read $LATEST_BASE/libreaccess-linux.json. Check the network and try again."
        VER="$(tr -d '\n' <"$WORK/latest.json" | sed -nE 's/.*"version"[[:space:]]*:[[:space:]]*"([0-9]+\.[0-9]+\.[0-9]+)".*/\1/p')"
        WANT_SHA="$(tr -d '\n' <"$WORK/latest.json" | sed -nE 's/.*"sha256"[[:space:]]*:[[:space:]]*"([0-9a-f]{64})".*/\1/p')"
        [[ -n "$VER" && -n "$WANT_SHA" ]] || fail "the release information at $LATEST_BASE is not readable. Try again later."
        url="$LATEST_BASE/libreaccess-linux.deb"; sigurl="$url.minisig"
    else
        VER="$want"
        url="$RELEASE_BASE/v$VER/libreaccess_${VER}-1_all.deb"; sigurl="$url.minisig"
        say "Looking up LibreAccess $VER"
        fetch "$url.sha256" "$WORK/sha256" || rc=$?
        (( rc != 22 )) || fail "there is no LibreAccess $VER release to download (see https://git.libreportal.org/LibrePortal/LibreAccess/releases)."
        (( rc == 0 )) || fail "could not reach $RELEASE_BASE. Check the network and try again."
        WANT_SHA="$(awk 'NR==1{print $1}' "$WORK/sha256")"
        [[ "$WANT_SHA" =~ ^[0-9a-f]{64}$ ]] || fail "the checksum file of $VER is not readable."
    fi
    DEB="$WORK/libreaccess_${VER}-1_all.deb"
    say "Downloading LibreAccess $VER"
    fetch "$url" "$DEB" || fail "could not download $url"
    fetch "$sigurl" "$DEB.minisig" || fail "LibreAccess $VER has no signature to check ($sigurl)."
    local got; got="$(sha256sum "$DEB" | cut -d' ' -f1)"
    [[ "$got" == "$WANT_SHA" ]] || fail "the download does not match its published checksum (expected $WANT_SHA, got $got). Nothing was changed. Try again; if it happens twice, do not install it."
    need_minisign
    local comment
    comment="$(minisign -V -Q -P "$PUBKEY" -m "$DEB" -x "$DEB.minisig" 2>/dev/null </dev/null)" \
        || fail "the signature is not a good one from the LibrePortal release key. Nothing was changed. Do not install this file."
    [[ "$comment" == "libreaccess $VER (stable)" ]] || fail "the signature belongs to something else (\"$comment\"), not LibreAccess $VER. Nothing was changed."
    [[ "$(dpkg-deb -f "$DEB" Package 2>/dev/null)" == libreaccess && "$(dpkg-deb -f "$DEB" Version 2>/dev/null)" == "$VER-1" ]] \
        || fail "the file is not the LibreAccess $VER package."
    say "Checksum and signature are good"
}

installed_version() { dpkg-query -W -f='${db:Status-Abbrev} ${Version}' libreaccess 2>/dev/null | sed -n 's/^ii *//p' || true; }

install_package() { # <1 when a version was chosen: going back is then allowed>
    local chosen="$1" have; have="$(installed_version)"
    if [[ -n "$have" ]] && (( ! chosen )) && dpkg --compare-versions "$have" gt "$VER-1"; then
        say "LibreAccess ${have%-1} is already installed, newer than the published $VER: keeping it"
        return 0
    fi
    if [[ "$have" == "$VER-1" ]]; then say "LibreAccess $VER is already installed"; return 0; fi
    apt_refresh
    if [[ -n "$have" ]]; then say "Changing LibreAccess ${have%-1} to $VER"; else say "Installing LibreAccess $VER"; fi
    local extra=(); (( chosen )) && extra=(--allow-downgrades)
    apt_get install -y -qq "${extra[@]}" "$DEB" >"$WORK/apt.log" 2>&1 || { tail -n 15 "$WORK/apt.log" >&2; fail "apt could not install the package (its last lines are above)."; }
    [[ "$(installed_version)" == "$VER-1" ]] || fail "apt finished but LibreAccess $VER is not installed."
}

show_invite() {
    if command -v systemctl >/dev/null 2>&1 && [[ -d /run/systemd/system ]] && ! systemctl is-active --quiet ssh ssh.socket 2>/dev/null; then
        say "Note: the SSH service is not running, and the app needs it:  systemctl enable --now ssh"
    fi
    printf '\n'
    # one open invite at a time: an unused earlier one is withdrawn first
    libreaccess invite --cancel </dev/null >/dev/null 2>&1 || true
    libreaccess invite </dev/null || { printf '\nLibreAccess is installed, but no invite could be made (see above). Try:  sudo libreaccess invite\n' >&2; exit 1; }
}

main() {
    local want="${LIBREACCESS_VERSION:-}" invite=1
    while (( $# )); do
        case "$1" in
            --version) [[ $# -ge 2 && -n "$2" ]] || fail "--version needs a version, such as v0.1.1"; want="$2"; shift ;;
            --version=*) want="${1#--version=}"; [[ -n "$want" ]] || fail "--version needs a version, such as v0.1.1" ;;
            --no-invite) invite=0 ;;
            -h|--help) usage; return 0 ;;
            *) fail "unknown option: $1 (--help lists them)" ;;
        esac
        shift
    done
    if [[ -n "$want" ]]; then
        want="${want#v}"
        [[ "$want" =~ ^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$ ]] || fail "not a version: $want (use the form v0.1.1)"
    fi
    check_system
    WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
    chmod 755 "$WORK"          # apt reads the package as its own user
    umask 022
    get_package "$want"
    install_package "$([[ -n "$want" ]] && echo 1 || echo 0)"
    if (( invite )); then show_invite; else say "Done. To pair the app later:  sudo libreaccess invite"; fi
}

# everything above is only definitions: a download cut off half way runs nothing
main "$@"
