#!/bin/bash
# Wombat-Email: Roundcube, from its own signed releases (installed by installer/84-webmail.sh; run by the
# installer, and each morning before the report). Takes the newest release of SERIES when it's newer
# than what runs, checks the signature against the key in the repository, updates the database, then
# switches over; on any failure what runs keeps running. The result goes to webmail.json for the report.
# A new series (1.8) can change more, so it's reported, not taken.
set -uo pipefail
SERIES=1.7
RC=/var/www/wombat-webmail
KEY=/etc/wombat-email/roundcube-pubkey.asc
STATUS=/var/lib/wombat-email/webmail.json
now=$(basename "$(readlink "$RC/current" 2>/dev/null)")

finish() {   # MESSAGE (empty: all well)
    MSG=$1 NEWER=${newer:-} VERSION=$(basename "$(readlink "$RC/current" 2>/dev/null)") python3 -I - "$STATUS" <<'PY'
import json, os, sys, time
json.dump({"version": os.environ["VERSION"], "error": os.environ["MSG"], "newer_series": os.environ["NEWER"], "checked": int(time.time())},
          open(sys.argv[1] + ".new", "w"))
os.chmod(sys.argv[1] + ".new", 0o644); os.replace(sys.argv[1] + ".new", sys.argv[1])
PY
    [ -z "$1" ] || { echo "webmail update: $1" >&2; exit 1; }
    exit 0
}

tags=$(curl -4 -fsS --max-time 30 'https://api.github.com/repos/roundcube/roundcubemail/releases?per_page=30' \
    | python3 -I -c 'import json,sys; [print(r["tag_name"]) for r in json.load(sys.stdin) if not r["prerelease"] and not r["draft"]]') \
    || finish "couldn't ask GitHub for Roundcube's releases"
want=$(grep -E "^${SERIES//./\\.}\.[0-9]+$" <<<"$tags" | sort -V | tail -1)
newer=$(grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' <<<"$tags" | sort -V | tail -1)
[ "$(printf '%s\n' "$SERIES.999" "$newer" | sort -V | tail -1)" = "$SERIES.999" ] && newer=
[ -n "$want" ] || finish "no Roundcube $SERIES release found"
[ "$now" = "$want" ] && finish ""
[ -z "$now" ] || [ "$(printf '%s\n' "$now" "$want" | sort -V | tail -1)" = "$want" ] || finish ""

tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
url=https://github.com/roundcube/roundcubemail/releases/download/$want/roundcubemail-$want-complete.tar.gz
curl -4 -fsSL --max-time 300 -o "$tmp/rc.tar.gz" "$url" && curl -4 -fsSL --max-time 30 -o "$tmp/rc.asc" "$url.asc" \
    || finish "couldn't download Roundcube $want"
export GNUPGHOME=$tmp/gpg; install -d -m 700 "$GNUPGHOME"
gpg --quiet --batch --import "$KEY" 2>/dev/null
gpg --quiet --batch --status-fd 1 --verify "$tmp/rc.asc" "$tmp/rc.tar.gz" 2>/dev/null | grep -q '^\[GNUPG:\] VALIDSIG .* F3E4C04BB3DB5D4215C45F7F5AB2BAA141C4F7D5$' \
    || finish "Roundcube $want's signature doesn't check out; not installed"

new=$RC/releases/$want
rm -rf "$new"; install -d -m 755 "$new"
tar -xzf "$tmp/rc.tar.gz" -C "$new" --strip-components=1 --no-same-owner || finish "couldn't unpack Roundcube $want"
rm -rf "$new/installer"
chown -R root:root "$new"; chmod -R go-w "$new"
ln -sf /etc/wombat-email/webmail.config.inc.php "$new/config/config.inc.php"
rm -rf "$new/temp" "$new/logs"; ln -s "$RC/tmp" "$new/temp"; ln -s /var/log/wombat-email/webmail "$new/logs"
[ ! -d "$RC/wombat_look" ] || cp -a "$RC/wombat_look" "$new/plugins/wombat_look"   # Wombat-Email's look (84-webmail.sh)
for p in "$RC"/dav/plugins/*/; do [ -d "$p" ] && cp -a "$p" "$new/plugins/$(basename "$p")"; done   # webmail's calendar and contacts (86-dav.sh)

export PGPASSWORD; PGPASSWORD=$(cat /etc/wombat-email/secrets/db-we_webmail)
psqlrc() { psql -X -q -At -v ON_ERROR_STOP=1 -h 127.0.0.1 -U we_webmail -d roundcube "$@"; }
if [ "$(psqlrc -c "SELECT 1 FROM information_schema.tables WHERE table_name = 'system'")" != 1 ]; then
    psqlrc -f "$new/SQL/postgres.initial.sql" >/dev/null || finish "couldn't set up Roundcube's database"
else
    runuser -u wombat-webmail -- php "$new/bin/updatedb.sh" --package=roundcube --dir="$new/SQL" >/dev/null \
        || finish "couldn't update Roundcube's database for $want"
fi

ln -sfn "$new" "$RC/current.new" && mv -T "$RC/current.new" "$RC/current"
systemctl reload php8.5-fpm
[ -z "$now" ] || echo "Roundcube $now -> $want"
[ -n "$now" ] || echo "Roundcube $want installed"
for old in "$RC"/releases/*; do
    v=$(basename "$old"); [ "$v" = "$want" ] || [ "$v" = "$now" ] || rm -rf "$old"
done
finish ""
