#!/bin/bash
# Wombat-Email: update to the newest version, asked for with the panel's Update button (installed by
# installer/89-sync.sh as /usr/local/sbin/wombat-email-update; wombat-email-update.path runs it when the
# panel leaves /var/lib/wombat-email/requests/update). The panel can only ask; what runs is decided here.
#
#   1. Download the newest release and its signature. Refused unless the release key this server already
#      has (/etc/wombat-email/release-signers) signed it, so a changed download is never installed.
#   2. Keep the running version as /opt/wombat-email.previous and put the new one in /opt/wombat-email.
#   3. Run the new installer, as a run by hand does, without questions and never restarting the server.
#   4. Check the panel answers and the mail services run. If not, or the installer stopped, put the
#      previous version back and run its installer, so the server is as it was.
#
# Progress and result: /var/lib/wombat-email/update-status.json (the panel's Update page reads it), and an
# email to the owner. Log: /var/log/wombat-email/update.log.
# By hand, as root: wombat-email-update. For trying a test release, WE_UPDATE_SOURCE and WE_UPDATE_SIG name
# other files (paths or URLs); they must be signed with the release key all the same.
#
# wombat-email-update --packages: Ubuntu's own waiting updates instead, asked for with the panel's "Install
# updates now" (requests/packages, wombat-email-packages.path). apt-get upgrade, as the installer does it;
# progress in packages-status.json. Packages can't be taken back, so there is no putting back here; the
# check afterwards still runs and says so if something stopped. Never restarts the server either.
set -uo pipefail

# Run from a copy: the installer replaces this file while it runs.
if [ "${WE_UPDATE_COPY:-}" != 1 ]; then
    install -m 700 "$0" /run/wombat-email-update.run
    WE_UPDATE_COPY=1 exec bash /run/wombat-email-update.run "$@"
fi

TARGET=/opt/wombat-email
SOURCE=${WE_UPDATE_SOURCE:-https://wombat-email.com/download.php?via=update}   # counted as an update, not an install
SIG=${WE_UPDATE_SIG:-https://wombat-email.com/wombat-email/wombat-email.tar.gz.sig}
SIGNERS=/etc/wombat-email/release-signers
JOB=update; [ "${1:-}" = --packages ] && JOB=packages
STATUS=/var/lib/wombat-email/$JOB-status.json
LOG=/var/log/wombat-email/update.log
WORK=/var/lib/wombat-email/update

exec 9>/run/wombat-email-sync.lock      # never alongside the panel's other changes: both run the installer
flock 9
install -d -m 750 /var/log/wombat-email
exec >> "$LOG" 2>&1
echo
echo "######## update, $(date '+%Y-%m-%d %H:%M:%S %Z')"

FROM=$(cat "$TARGET/VERSION" 2>/dev/null || echo unknown)
TO= N=0 TOTAL=0
status() {   # STATE STEP [MESSAGE]: running (STEP says where; N of TOTAL installer pieces), ok, current, rolled-back, failed
    echo "-- $1: $2 ${3:-}"
    STATE=$1 STEP=$2 MESSAGE=${3:-} FROM=$FROM TO=$TO N=$N TOTAL=$TOTAL python3 -I - "$STATUS" <<'PY'
import json, os, sys, time
path = sys.argv[1]
try: old = json.load(open(path))
except Exception: old = {}
s = {k: os.environ[k.upper()] for k in ("state", "step", "message", "from", "to")}
s["n"], s["total"] = int(os.environ["N"]), int(os.environ["TOTAL"])
s["started"] = old.get("started", int(time.time())) if old.get("state") == "running" else int(time.time())
if s["state"] != "running": s["finished"] = int(time.time())
json.dump(s, open(path + ".new", "w")); os.chmod(path + ".new", 0o644); os.replace(path + ".new", path)
PY
}
# "Running" is written before the panel's request goes, so the panel never sees neither.
if [ "$JOB" = packages ]; then status running "Getting the list of updates"; else status running "Downloading the newest version"; fi
rm -f "/var/lib/wombat-email/requests/$JOB"
. /usr/local/lib/wombat-email/common.sh   # tell_owner: the result by email, as the server's other mail
fetch() {   # FROM TO: a URL or a local file
    case $1 in
        https://*) curl -fsS --max-time 300 -o "$2" "$1" ;;
        *) cp "$1" "$2" ;;
    esac
}
verified() { ssh-keygen -Y verify -f "$SIGNERS" -I release@wombat-email.com -n wombat-email-release -s "$WORK/new.tar.gz.sig" < "$WORK/new.tar.gz"; }

# Does the server work? The mail services run, Rspamd rejects the GTUBE spam test (it scans, so mail
# isn't held back waiting for it: Rspamd's own updates come from rspamd.com with Ubuntu's) and the
# panel's sign-in page answers. Asked a few times, as services may still be starting after the installer.
gtube_rejected() {
    rspamc -i 203.0.113.9 <<<$'From: test@example.org\r\nSubject: GTUBE\r\n\r\nXJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X\r\n' 2>/dev/null \
        | grep -q '^Action: reject'
}
healthy() {
    local host tries
    host=$(. /etc/wombat-email/settings && echo "$HOSTNAME")
    for tries in 1 2 3 4 5 6; do
        if systemctl is-active --quiet postfix dovecot rspamd apache2 php8.5-fpm postgresql \
           && gtube_rejected \
           && curl -fsS --max-time 20 --resolve "$host:443:127.0.0.1" "https://$host/panel/signin.php" 2>/dev/null | grep -q '<form'; then
            return 0
        fi
        sleep 10
    done
    return 1
}
# The installer in /opt/wombat-email, its pieces shown as the step. 0 when it finished.
install_run() {   # WHAT (for the step: "Installing 0.3.4")
    local line piece= rc=/run/wombat-email-update.rc pieces=("$TARGET"/installer/[0-9][0-9]-*.sh)
    echo 1 > "$rc"
    N=0 TOTAL=${#pieces[@]}
    status running "$1: starting"
    while IFS= read -r line; do
        printf '%s\n' "$line"
        if [[ "$line" =~ ^==\ ([a-z0-9-]+)$ ]]; then N=$((N + 1)); piece=${BASH_REMATCH[1]}; status running "$1: $piece"
        elif [[ "$line" =~ ^\ \ \ working:\ (.{1,120}) ]]; then status running "$1: $piece: ${BASH_REMATCH[1]}"; fi   # a long piece says where it is
    done < <(bash "$TARGET/install.sh" </dev/null 2>&1 | sed -u 's/\x1b\[[0-9;]*m//g'; echo "${PIPESTATUS[0]}" > "$rc")
    return "$(cat "$rc")"
}

# Ubuntu's waiting updates, one line each for an email: name, installed -> new, security marked (the
# columns line up in the email's fixed-width font). PACKAGE... (optional): only these.
pkg_list() {
    apt-get -s upgrade 2>/dev/null | awk -v only=" $* " '/^Inst / {
        name = $2; if (only != "  " && index(only, " " name " ") == 0) next
        old = $3; gsub(/[\[\]]/, "", old); new = $4; sub(/^\(/, "", new)
        printf "  %-30s %s -> %s%s\n", name, old, new, (index($0, "-security") ? "   (security)" : "") }'
}
pkg_names() { apt-get -s upgrade 2>/dev/null | awk '/^Inst / {print $2}'; }

# ---- Ubuntu's updates (--packages)
if [ "$JOB" = packages ]; then
    export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a   # services restart by themselves, no questions
    apt=(-o DPkg::Lock::Timeout=900 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
    if ! apt-get "${apt[@]}" -qq update; then
        status failed "" "Ubuntu's list of updates couldn't be fetched just now. Nothing was installed; try again later."
        exit 1
    fi
    TOTAL=$(apt-get -s upgrade 2>/dev/null | grep -c '^Inst ' || true)
    list=$(pkg_list)   # what's about to change, for the email
    if [ "$TOTAL" -eq 0 ]; then
        TOTAL=0; status current "" "Nothing to install: every package is up to date."
        /usr/local/sbin/wombat-email-report --print > /dev/null 2>&1 || true   # the Dashboard's count follows
        exit 0
    fi
    status running "Installing $TOTAL updates"
    rc=/run/wombat-email-update.rc; echo 1 > "$rc"
    while IFS= read -r line; do
        printf '%s\n' "$line"
        if [[ "$line" =~ ^Setting\ up\ ([^ :]+) ]]; then
            [ "$N" -ge "$TOTAL" ] || N=$((N + 1))
            status running "Installing updates: ${BASH_REMATCH[1]}"
        fi
    done < <(apt-get "${apt[@]}" -y upgrade 2>&1; echo "$?" > "$rc")
    done_n=$TOTAL
    status running "Checking that everything works"
    /usr/local/sbin/wombat-email-report --print > /dev/null 2>&1 || true   # the Dashboard's count follows
    restart=; [ ! -f /var/run/reboot-required ] || restart=$'\nA restart finishes it: Settings › Restart, when it suits you.'
    if [ "$(cat "$rc")" = 0 ] && healthy; then
        N=0 TOTAL=0
        status ok "" "Installed $done_n update$([ "$done_n" = 1 ] || echo s).$restart"
        tell_owner "$done_n update$([ "$done_n" = 1 ] || echo s) installed" "Installed $done_n of Ubuntu's updates.$restart

$list"
        exit 0
    fi
    N=0 TOTAL=0
    status failed "" "Installing the updates didn't finish cleanly, or the panel or mail services didn't answer afterwards. The details are in /var/log/wombat-email/update.log. Try again; if it happens again, ask in the forum.$restart"
    tell_owner "updates didn't finish" "Ubuntu's updates didn't finish, or the panel or mail
didn't answer afterwards. Details: /var/log/wombat-email/update.log
Try again; if it happens again, ask in the forum:
https://wombat-email.com/forum/

What it was installing:
$list"
    exit 1
fi

# ---- 1. the newest release, checked
[ -s "$SIGNERS" ] || { status failed "" "This server doesn't have Wombat-Email's release key yet, so it can't check a download. Update once by hand (as root: curl -fsSL https://wombat-email.com/get.sh | bash); after that, this button works."; exit 1; }
rm -rf "$WORK"; install -d -m 700 "$WORK"
ok=
for attempt in 1 2; do          # twice: a release published between the two downloads doesn't match its signature
    fetch "$SOURCE" "$WORK/new.tar.gz" && fetch "$SIG" "$WORK/new.tar.gz.sig" || { sleep 5; continue; }
    verified && { ok=1; break; }
    sleep 5
done
if [ -z "$ok" ]; then
    if [ -s "$WORK/new.tar.gz.sig" ]; then
        status failed "" "The download isn't signed with Wombat-Email's release key, so it wasn't installed. Nothing was changed."
        tell_owner "update refused" "The download from wombat-email.com isn't signed with
Wombat-Email's release key, so it wasn't installed.
Nothing was changed. If it happens again, say so in the forum:
https://wombat-email.com/forum/"
    else
        status failed "" "The new version couldn't be downloaded from wombat-email.com. Nothing was changed; try again later."
    fi
    exit 1
fi
install -d -m 700 "$WORK/new"
tar -xzf "$WORK/new.tar.gz" --strip-components=1 -C "$WORK/new" || { status failed "" "The download couldn't be unpacked. Nothing was changed."; exit 1; }
TO=$(cat "$WORK/new/VERSION" 2>/dev/null)
[[ "$TO" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] && [ -f "$WORK/new/install.sh" ] || { TO=; status failed "" "The download isn't a Wombat-Email release. Nothing was changed."; exit 1; }
# Renumbered from 1.x to 0.x (2026-11-04): an old 1.x here reads as 0.x against a 0.x release, so that's newer.
from_cmp=$FROM; [[ "$TO" == 0.* && "$FROM" =~ ^1\.[0-9]+\.[0-9]+$ ]] && from_cmp=0.${FROM#1.}
if [ "$TO" = "$from_cmp" ] || [ "$(printf '%s\n%s\n' "$from_cmp" "$TO" | sort -V | tail -1)" = "$from_cmp" ]; then
    status current "" "This server already has the newest version, v$FROM. Nothing was changed."
    rm -rf "$WORK"; exit 0
fi

# Ubuntu's waiting updates now: the installer installs them too, and the email says which.
apt-get -o DPkg::Lock::Timeout=900 -qq update > /dev/null 2>&1 || true
before=$(pkg_names | tr '\n' ' ')
ubuntu_list=$(pkg_list)

# ---- 2. the new version in place, the running one kept
rm -rf "$TARGET.previous"
if ! cp -a "$TARGET" "$TARGET.previous"; then   # a disk too full for the copy: the running version stays as it is
    rm -rf "$TARGET.previous" "$WORK"
    status failed "" "The running version couldn't be copied aside first (is the disk full?), so nothing was changed. Free some space and try again."
    exit 1
fi
rm -rf "$TARGET"
mv "$WORK/new" "$TARGET"
chmod 755 "$TARGET"

# ---- 3 and 4. its installer, then the check
why=
if ! install_run "Installing v$TO"; then
    why="stopped while installing ($(grep '^!! ' "$LOG" | tail -1 | cut -c4-))"
elif status running "Checking that v$TO works" && ! healthy; then
    why="was installed, but then the panel or the mail services didn't answer"
fi
N=0 TOTAL=0
if [ -z "$why" ]; then
    rm -rf "$WORK"
    # Which of Ubuntu's waiting updates went in along the way (those no longer waiting).
    still=" $(pkg_names | tr '\n' ' ') " gone=()
    for p in $before; do [[ "$still" == *" $p "* ]] || gone+=("$p"); done
    msg="Updated from v$FROM to v$TO."
    [ ${#gone[@]} -eq 0 ] || msg="$msg Ubuntu's ${#gone[@]} waiting update$([ ${#gone[@]} = 1 ] || echo s) were installed too."
    [ ! -f /var/run/reboot-required ] || msg="$msg"$'\nA restart finishes it: Settings › Restart, when it suits you.'
    status ok "" "$msg"
    installed=
    if [ ${#gone[@]} -gt 0 ]; then
        installed=$'\n\nUbuntu\'s updates installed along the way:'
        while IFS= read -r line; do
            name=$(awk '{print $1}' <<<"$line")
            [[ " ${gone[*]} " == *" $name "* ]] && installed+=$'\n'"$line"
        done <<<"$ubuntu_list"
    fi
    tell_owner "updated to v$TO" "$msg

What's new: https://wombat-email.com/releases.php$installed"
    exit 0
fi

# ---- the previous version back
status running "Putting v$FROM back"
rm -rf "$TARGET"
mv "$TARGET.previous" "$TARGET"
if install_run "Putting v$FROM back" && status running "Checking that v$FROM works" && healthy; then
    status rolled-back "" "Version v$TO $why, so v$FROM was put back and runs as before. Nothing else needs doing. The details are in /var/log/wombat-email/update.log."
    tell_owner "update to v$TO undone" "Version v$TO $why,
so v$FROM was put back and runs as before. Nothing else needs doing.
Details: /var/log/wombat-email/update.log
Please say what happened in the forum, so it gets fixed:
https://wombat-email.com/forum/"
    exit 1
fi
status failed "" "Version v$TO $why, and putting v$FROM back didn't finish either. Log in as root and run: curl -fsSL https://wombat-email.com/get.sh | bash"
tell_owner "update to v$TO failed" "Version v$TO $why,
and putting v$FROM back didn't finish either. Log in as root and run:

    curl -fsSL https://wombat-email.com/get.sh | bash

Details: /var/log/wombat-email/update.log"
exit 1
