#!/bin/bash

## Copyright (C) 2025 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## OK:
#set superusers="root"
#password_pbkdf2 root grub.pbkdf2.sha512.10000.<hashed-password>

## OK:
#set superusers="user"
#password_pbkdf2 user grub.pbkdf2.sha512.10000.<hashed-password>

## INCORRECT (username mismatch between superuser and password entry):
#set superusers="user"
#password_pbkdf2 root grub.pbkdf2.sha512.10000.<hashed-password>

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

GRUB_CFG="/boot/grub/grub.cfg"

if [ "$(id -u)" -ne 0 ]; then
  printf "%s\n" "$0: ERROR: Must be run as root." >&2
  exit 2
fi

if ! package-installed-check 'grub2-common'; then
  printf "%s\n" "$0: ERROR: Package 'grub2-common' missing." >&2
  exit 3
fi

if ! test -d "/boot"; then
  printf "%s\n" "$0: ERROR: Folder '/boot' does not exist." >&2
  exit 4
fi

if ! test -d "/boot/grub"; then
  printf "%s\n" "$0: ERROR: Folder '/boot/grub' does not exist." >&2
  exit 5
fi

if ! test -r "$GRUB_CFG"; then
  printf "%s\n" "$0: ERROR: File '$GRUB_CFG' does not exist or is not readable." >&2
  exit 6
fi

superuser=""
password_user=""

superuser=$(grep --extended-regexp --only-matching '^set superusers=([\"'\''"]?)([^\"'\''[:space:]]+)\1$' "$GRUB_CFG" \
  | sed -E 's/^set superusers=["'\''"]?([^"'\''"]+)["'\''"]?$/\1/' \
  || true)

if [ -z "${superuser:-}" ]; then
  printf "%s\n" "$0: ERROR: No valid 'set superusers' entry found in file '$GRUB_CFG'." >&2
  exit 7
fi

password_user=$(grep --extended-regexp --only-matching '^password.*[[:space:]]+([^[:space:]]+)[[:space:]]+grub\.pbkdf2\.sha512\.' "$GRUB_CFG" \
  | sed -E 's/^password.*[[:space:]]+([^[:space:]]+)[[:space:]]+grub\.pbkdf2\..*/\1/' \
  | head -n1 \
  || true)

if [ -z "${password_user:-}" ]; then
  printf "%s\n" "$0: ERROR: No valid 'password_pbkdf2' entry found in file '$GRUB_CFG'." >&2
  exit 8
fi

if [ "${superuser:-}" != "${password_user:-}" ]; then
  printf "%s\n" "$0: ERROR: Mismatch: superuser is '$superuser', but password entry is for '$password_user'" >&2
  exit 9
fi

printf "%s\n" "$0: INFO: OK."
exit 0
