#!/usr/bin/env bash
set -euo pipefail
TIMER=fiordland-autoupdate.timer
STATE=/var/lib/fiordland/autoupdate
LOCK=/run/fiordland-update.lock

usage() {
  cat <<USAGE
usage: fiordland autoupdate [on | off | status | run]

Updates are manual by default. Every update takes a btrfs snapshot first,
so a bad one can be undone from the boot menu.
  on       update once a week, Sunday at 04:00, then keep the server running
  off      stop updating automatically
  status   show whether automatic updates are on and how the last update went
  run      update now, the same way the timer does
USAGE
  exit "${1:-0}"
}

root() {
  [ "$(id -u)" -eq 0 ] || exec sudo "$0" "$@"
}

reboot_needed() {
  [ ! -d "/usr/lib/modules/$(uname -r)" ]
}

status() {
  if [ "$(systemctl is-enabled "$TIMER" 2>/dev/null || true)" = enabled ]; then
    echo "automatic updates: on ($(systemctl show -P NextElapseUSecRealtime "$TIMER" 2>/dev/null | sed 's/^$/next run unknown/'))"
  else
    echo "automatic updates: off"
  fi
  if [ -f "$STATE/last" ]; then
    echo "last update: $(cat "$STATE/last")"
  else
    echo "last update: never"
  fi
  reboot_needed && echo "a new kernel is installed, reboot to use it"
  true
}

run() {
  mkdir -p "$STATE"
  exec 9>"$LOCK"
  flock -n 9 || { echo "another update is running" >&2; exit 1; }
  local rc=0
  pacman -Sy --needed --noconfirm archlinux-keyring fiordland-keyring || rc=$?
  [ "$rc" -eq 0 ] && { pacman -Su --noconfirm || rc=$?; }
  if [ "$rc" -eq 0 ]; then
    echo "$(date '+%Y-%m-%d %H:%M') ok" > "$STATE/last"
  else
    echo "$(date '+%Y-%m-%d %H:%M') failed, see journalctl -u fiordland-autoupdate" > "$STATE/last"
  fi
  return "$rc"
}

case ${1:-status} in
  -h|--help|help) usage ;;
  status) status ;;
  on) root "$@"; systemctl enable --now "$TIMER"; echo "Automatic updates are on." ;;
  off) root "$@"; systemctl disable --now "$TIMER"; echo "Automatic updates are off." ;;
  run) root "$@"; run ;;
  *) usage 2 ;;
esac
