#!/bin/bash
# Wombat-Email: apply what the panel changed (installed by installer/89-sync.sh as
# /usr/local/sbin/wombat-email-sync). The panel can't do root work itself; it changes the database
# and leaves a request file (/var/lib/wombat-email/requests/sync), which wombat-email-sync.path
# notices; this then runs the installer, which brings everything in line with the database (DKIM keys,
# DNS records, certificates, the web sites, aliases). The result goes to sync-status.json, which the
# panel shows. One run at a time; a request made during a run gets its own run afterwards.
# Two requests carry a value, read here as data and checked: requests/renew (a certificate's name, to
# renew now) and requests/admin-email (the owner's new address). requests/backup-saved says the owner
# has a copy of the backup password. requests/reboot restarts the server, only when an update asks for
# that. All are followed by the sync request.
set -uo pipefail
STATUS=/var/lib/wombat-email/sync-status.json
LOG=/var/log/wombat-email/sync.log
exec 9>/run/wombat-email-sync.lock
flock 9

# The panel shows a run like the Update page: what it's for (the requests' reasons), the installer's
# current piece as the step, pieces done of all as the bar, how long it has run, and how long the last took.
WHY= STEP= PIECE= N=0 TOTAL=0 STARTED=0
status() {   # STATE [CHANGES] [MESSAGE]
    STATE=$1 CHANGES=${2:-0} MESSAGE=${3:-} WHY=$WHY STEP=$STEP N=$N TOTAL=$TOTAL STARTED=$STARTED python3 -I - "$STATUS" <<'PY'
import json, os, sys, time
path = sys.argv[1]
try: old = json.load(open(path))
except Exception: old = {}
e = os.environ
s = {"state": e["STATE"], "changes": int(e["CHANGES"]), "message": e["MESSAGE"], "why": e["WHY"], "step": e["STEP"],
     "n": int(e["N"]), "total": int(e["TOTAL"]), "started": int(e["STARTED"]) or int(time.time())}
s["last_took"] = old.get("last_took", 0)
if s["state"] != "running":
    s["finished"] = int(time.time())
    if s["state"] == "ok": s["last_took"] = s["finished"] - s["started"]
json.dump(s, open(path + ".new", "w")); os.chmod(path + ".new", 0o644); os.replace(path + ".new", path)
PY
}

request() {   # NAME: the first line of a request file, once, or nothing
    local f=/var/lib/wombat-email/requests/$1
    [ -f "$f" ] && [ ! -L "$f" ] && head -c 300 "$f" | head -1
    rm -f "$f"
}

while [ -e /var/lib/wombat-email/requests/sync ]; do
    STARTED=$(date +%s) STEP=Starting N=0 TOTAL=0
    status running                              # first: the panel must never see neither a request nor a run
    # What it's for: each request's reason ("<time> <who>: <why>"), taken whole so none is lost
    mv -f /var/lib/wombat-email/requests/sync /run/wombat-email-sync.why 2>/dev/null || true
    WHY=$(sed -E 's/^[^ ]+ [^:]*: //' /run/wombat-email-sync.why 2>/dev/null | awk 'NF && !seen[$0]++' | paste -sd ';' - | sed 's/;/; /g' | cut -c1-300)
    rm -f /run/wombat-email-sync.why
    status running
    if [ -n "$(request reboot || true)" ] && [ -f /var/run/reboot-required ]; then
        echo "$(date -Is) restart asked for in the panel" >> "$LOG"
        status ok 0
        systemctl reboot
        exit 0
    fi
    name=$(request renew || true)
    if [[ "$name" =~ ^[a-z0-9.-]+$ ]] && [ -d "/etc/letsencrypt/live/$name" ]; then
        STEP="renewing the certificate $name"; status running
        certbot renew --cert-name "$name" --force-renewal --no-random-sleep-on-renew >> "$LOG" 2>&1 || echo "renewing $name failed" >> "$LOG"
    fi
    args=()
    email=$(request admin-email || true)
    [[ "$email" =~ ^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}$ ]] && args=(--admin-email "$email")
    [ -n "$(request backup-saved || true)" ] && args+=(--backup-password-saved)
    pieces=(@WE_ROOT@/installer/[0-9][0-9]-*.sh); TOTAL=${#pieces[@]} N=0 STEP="starting"; status running
    out=
    while IFS= read -r line; do
        out+="$line"$'\n'
        if [[ "$line" =~ ^==\ ([a-z0-9-]+)$ ]]; then N=$((N + 1)); PIECE=${BASH_REMATCH[1]}; STEP=$PIECE; status running
        elif [[ "$line" =~ ^\ \ \ working:\ (.{1,120}) ]]; then STEP="$PIECE: ${BASH_REMATCH[1]}"; status running; continue; fi
    done < <(bash @WE_ROOT@/install.sh "${args[@]}" </dev/null 2>&1 | sed -u 's/\x1b\[[0-9;]*m//g'; echo "rc=${PIPESTATUS[0]}")
    rc=$(sed -n 's/^rc=//p' <<<"$out" | tail -1); rc=${rc:-1}
    out=$(grep -v '^rc=[0-9]*$' <<<"$out")
    STEP=
    printf '%s\n' "$out" >> "$LOG"
    changes=$(grep -c '^   changed: ' <<<"$out" || true)
    if [ $rc -eq 0 ]; then
        status ok "$changes"
    else
        status failed "$changes" "$(grep '^!! ' <<<"$out" | tail -1 | cut -c4-)"
    fi
done
