#!/bin/sh
# Installed Moodtop: make GRUB and fstab find / by UUID. Installs made before 1.1.2 booted
# root=/dev/sdX, which drops to a BusyBox prompt when the drive letters shift.
grep -qw boot=live /proc/cmdline 2>/dev/null && exit 0
cfg=/boot/grub/grub.cfg
[ -f "$cfg" ] || exit 0
uuid=$(findmnt -no UUID / 2>/dev/null)
[ -n "$uuid" ] || exit 0
dev='/dev/(sd|nvme|mmcblk|vd|hd)[a-z0-9]+'
if grep -Eq "^[[:space:]]*linux[[:space:]].*root=$dev" "$cfg"; then
  cp -a "$cfg" "$cfg.pre-uuid"
  command -v update-grub >/dev/null && update-grub >/dev/null 2>&1 || true
  sed -Ei "s#root=$dev([[:space:]]|\$)#root=UUID=$uuid\\2#" "$cfg"
  logger -t mood-fix-boot "grub.cfg now boots root=UUID=$uuid" 2>/dev/null || true
fi
if awk '$2=="/" && $1 ~ /^\/dev\//{f=1} END{exit !f}' /etc/fstab 2>/dev/null; then
  cp -a /etc/fstab /etc/fstab.pre-uuid
  awk -v u="UUID=$uuid" 'BEGIN{OFS="\t"} $2=="/" && $1 ~ /^\/dev\//{$1=u} {print}' /etc/fstab.pre-uuid > /etc/fstab
fi
exit 0
