#!/bin/bash
# Wombat-Email: fetches the installer and runs it. On your VPS, as root:
#
#   curl -fsSL https://wombat-email.com/get.sh | bash -s -- --hostname mail.example.com --admin-email you@example.org
#
# Everything after -- goes to install.sh, and whatever's left out it asks for. Running this again
# updates the installer's files in /opt/wombat-email; settings and mail are elsewhere and untouched.
# It's all in one function, so a download cut short runs nothing.
#
# The download must be signed with Wombat-Email's release key. A server that already has Wombat-Email
# checks it against the key it was installed with (/etc/wombat-email/release-signers); a new one against
# the copy below, the same key.
set -euo pipefail

SOURCE=https://wombat-email.com/download.php?via=install   # counted as an install (download.php)
SIG=https://wombat-email.com/wombat-email/wombat-email.tar.gz.sig
TARGET=/opt/wombat-email
SIGNERS='release@wombat-email.com namespaces="wombat-email-release" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDsHYAZrBp008xv8ZB2YJcVVOQQdjzqKWRbKmBWndPBQ'

main() {
    [ "$(id -u)" = 0 ] || { echo "Run this as root."; exit 1; }
    . /etc/os-release
    [ "$ID $VERSION_ID" = "ubuntu 26.04" ] || { echo "Wombat-Email needs Ubuntu 26.04 LTS; this is $PRETTY_NAME."; exit 1; }
    local new dl signers ok=
    new=$(mktemp -d /opt/wombat-email.XXXXXX)
    dl=$(mktemp -d)
    trap 'rm -rf "$new" "$dl"' EXIT
    signers=/etc/wombat-email/release-signers
    [ -s "$signers" ] || { printf '%s\n' "$SIGNERS" > "$dl/signers"; signers=$dl/signers; }
    echo "Fetching Wombat-Email..."
    for attempt in 1 2; do   # twice: a release published between the two downloads doesn't match its signature
        curl -fsSL -o "$dl/we.tar.gz" "$SOURCE" && curl -fsSL -o "$dl/we.tar.gz.sig" "$SIG" || { sleep 3; continue; }
        if ssh-keygen -Y verify -f "$signers" -I release@wombat-email.com -n wombat-email-release -s "$dl/we.tar.gz.sig" < "$dl/we.tar.gz" > /dev/null 2>&1; then ok=1; break; fi
        sleep 3
    done
    [ -n "$ok" ] || { echo "The download isn't signed with Wombat-Email's release key (or couldn't be fetched), so nothing was installed."; exit 1; }
    echo "Signature checked: signed with Wombat-Email's release key."
    tar -xzf "$dl/we.tar.gz" --strip-components=1 -C "$new"
    [ -f "$new/install.sh" ] || { echo "The download didn't contain the installer."; exit 1; }
    rm -rf "$TARGET"
    mv "$new" "$TARGET"
    chmod 755 "$TARGET"
    rm -rf "$dl"
    trap - EXIT
    exec bash "$TARGET/install.sh" "$@"
}
main "$@"
