#!/usr/bin/env bash
set -euo pipefail
. /usr/lib/fiordland/lib.sh
BASE=${FIORDLAND_ISO_BASE:-https://fiordlandlinux.org/iso}
DIR=/var/lib/fiordland/reinstall
ISO=$DIR/fiordland-server.iso
ARMED=$DIR/armed
GRUBD=/etc/grub.d/09_fiordland_reinstall

usage() {
  cat <<USAGE
usage: fiordland reinstall [prepare | status | cancel]

Reinstalls this computer without a USB stick or a monitor. prepare downloads
the newest Fiordland Server ISO, checks it, and makes the next boot start the
installer. Then reboot, and finish in a browser at http://fiordland-install.local
The disk is only erased once you confirm in the installer.
  prepare   download and check the ISO, then boot the installer next time
  status    show whether a reinstall is ready
  cancel    boot this system normally again and delete the ISO
USAGE
  exit "${1:-0}"
}

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

field() {
  python3 -c 'import json,sys; print(json.load(sys.stdin)[sys.argv[1]])' "$1"
}

status() {
  if [ -f "$ARMED" ] && [ -f "$ISO" ] && [ -x "$GRUBD" ]; then
    echo "ready: the next boot starts the Fiordland Server installer ($(cat "$ARMED"))"
  elif [ -f "$ISO" ]; then
    echo "downloaded, not armed"
  else
    echo "not prepared"
  fi
}

write_grubd() {
  cat > "$GRUBD" <<'GRUB'
#!/bin/sh
set -e
iso=/var/lib/fiordland/reinstall/fiordland-server.iso
[ -f "$iso" ] || exit 0
uuid=$(grub-probe --target=fs_uuid "$iso")
rel=$(grub-mkrelpath "$iso")
armed=$(grub-mkrelpath /var/lib/fiordland/reinstall)/armed
cat <<CFG
insmod part_gpt
insmod part_msdos
insmod btrfs
insmod loopback
insmod iso9660
search --no-floppy --fs-uuid --set=fiordland_reinstall_root $uuid
if [ -f (\$fiordland_reinstall_root)$armed ]; then
  set default=fiordland-reinstall
  set timeout=3
fi
menuentry "Reinstall Fiordland Server (erases this disk after you confirm)" --class arch --id fiordland-reinstall {
  set root=\$fiordland_reinstall_root
  loopback loop $rel
  linux (loop)/arch/boot/x86_64/vmlinuz-linux archisobasedir=arch img_dev=UUID=$uuid img_loop=$rel copytoram=y fiordland.reinstall=1
  initrd (loop)/arch/boot/x86_64/initramfs-linux.img
}
CFG
GRUB
  chmod 755 "$GRUBD"
}

cancel() {
  rm -f "$ARMED" "$ISO" "$ISO.part" "$GRUBD"
  grub_regen >/dev/null 2>&1 || true
  echo "Reinstall cancelled. This system boots normally."
}

prepare() {
  [ "$(findmnt -no FSTYPE /)" = btrfs ] || { echo "only btrfs installs can reinstall this way" >&2; exit 1; }
  mkdir -p "$DIR"
  chmod 700 "$DIR"
  local meta file sum size free
  meta=$(curl -fsSL -m 30 "$BASE/server.json") || { echo "couldn't reach $BASE" >&2; exit 1; }
  file=$(field file <<<"$meta")
  sum=$(field sha256 <<<"$meta")
  size=$(field size <<<"$meta")
  [[ $file =~ ^fiordland-server-[0-9.]+(-[0-9]+)?-x86_64\.iso$ ]] || { echo "unexpected ISO name: $file" >&2; exit 1; }
  [[ $sum =~ ^[0-9a-f]{64}$ ]] || { echo "unexpected checksum" >&2; exit 1; }
  free=$(df --output=avail -B1 "$DIR" | tail -1)
  [ "$free" -gt $((size + 1073741824)) ] || { echo "not enough free space for the ISO" >&2; exit 1; }
  if [ -f "$ISO" ] && [ -f "$DIR/sha256" ] && [ "$(cat "$DIR/sha256")" = "$sum" ]; then
    echo "already downloaded $file"
  else
    rm -f "$ISO" "$DIR/sha256"
    [ -f "$DIR/name" ] && [ "$(cat "$DIR/name")" != "$file" ] && rm -f "$ISO.part"
    echo "$file" > "$DIR/name"
    echo "downloading $file"
    curl -fL --retry 3 -C - -o "$ISO.part" "$BASE/$file"
    echo "checking it"
    if [ "$(sha256sum "$ISO.part" | cut -d' ' -f1)" != "$sum" ]; then
      rm -f "$ISO.part"
      echo "the download is damaged, try again" >&2
      exit 1
    fi
    mv -f "$ISO.part" "$ISO"
    echo "$sum" > "$DIR/sha256"
  fi
  write_grubd
  date '+%Y-%m-%d %H:%M' > "$ARMED"
  if ! grub_regen; then
    rm -f "$ARMED" "$GRUBD"
    grub_regen || true
    echo "couldn't update the boot menu" >&2
    exit 1
  fi
  echo "Ready. Reboot, then open http://fiordland-install.local from another computer."
}

case ${1:-status} in
  -h|--help|help) usage ;;
  status) status ;;
  prepare) root "$@"; prepare ;;
  cancel) root "$@"; cancel ;;
  *) usage 2 ;;
esac
