#!/usr/bin/env bash
# Daily, from the dev server (cron): if the droplet has a pending kernel or libc update
# that needs a reboot, email rian once a day until it is done. Automatic reboots are off
# on bwlive because one killed an overnight collection (11 Sep); the reboot is a human
# decision, taken outside a crawl window: `ssh deploy@bwlive sudo reboot`, about a minute.
set -uo pipefail
ROOT=/srv/apps/dutyfreeprofessor
if ssh -o BatchMode=yes -o ConnectTimeout=20 deploy@bwlive 'test -f /var/run/reboot-required' 2>/dev/null; then
  pkgs=$(ssh -o BatchMode=yes deploy@bwlive 'cat /var/run/reboot-required.pkgs 2>/dev/null | tr "\n" " "')
  key=$(sed -n 's/^RESEND_API_KEY=//p' "$ROOT/.app.env" | tr -d '\r\n')
  python3 - "$pkgs" "$key" << 'PY'
import json, sys, urllib.request
pkgs, key = sys.argv[1:3]
req = urllib.request.Request("https://api.resend.com/emails", method="POST",
    data=json.dumps({"from": "Duty Free Professor monitor <monitor@dutyfreeprofessor.com>", "to": ["rian@rian.ca"],
        "subject": "bwlive needs a reboot (pending: %s)" % (pkgs.strip() or "kernel"),
        "text": "The droplet has installed an update that needs a reboot. Pick a moment with no collection running (check .logs/runs/ for an open window), then: ssh deploy@bwlive sudo reboot. About a minute of downtime; containers come back on their own."}).encode(),
    headers={"Authorization": "Bearer " + key, "Content-Type": "application/json", "User-Agent": "dfp-uptime/1.0"})
try: urllib.request.urlopen(req, timeout=20)
except Exception as e: print("reboot mail failed", e, file=sys.stderr)
PY
fi
exit 0
