#!/bin/bash

set -e

THEME_NAME="parch-grub-theme"
THEME_DIR="/boot/grub/themes/${THEME_NAME}"
PKG_DIR="/usr/share/grub/themes/${THEME_NAME}"

if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root. Try: sudo $0"
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [ -f "${SCRIPT_DIR}/src/theme.txt" ]; then
  SOURCE_DIR="${SCRIPT_DIR}/src"
elif [ -f "${PKG_DIR}/theme.txt" ]; then
  SOURCE_DIR="${PKG_DIR}"
  echo "Found package-installed theme at ${SOURCE_DIR}"
else
  echo "Error: Cannot find theme files."
  echo "Run this script from the theme directory or after installing the package."
  exit 1
fi

echo "Installing Parch GRUB Theme..."
echo "Source: ${SOURCE_DIR}"
echo "Target: ${THEME_DIR}"

mkdir -p "${THEME_DIR}/icons"

for f in \
  theme.txt background.png logo.png \
  unifont-16.pf2 \
  din2014_regular_18.pf2 din2014_regular_20.pf2 din2014_regular_23.pf2 \
  terminus-14.pf2 terminus-16.pf2 \
  select_w.png select_c.png select_e.png; do
  if [ -f "${SOURCE_DIR}/$f" ]; then
    cp -v "${SOURCE_DIR}/$f" "${THEME_DIR}/"
  fi
done

cp -rv "${SOURCE_DIR}/icons/"*.png "${THEME_DIR}/icons/"

if grep -q "^GRUB_THEME=" /etc/default/grub; then
  sed -i "s|^GRUB_THEME=.*|GRUB_THEME=\"${THEME_DIR}/theme.txt\"|" /etc/default/grub
else
  echo "GRUB_THEME=\"${THEME_DIR}/theme.txt\"" >> /etc/default/grub
fi

if ! grep -q "^GRUB_GFXMODE=" /etc/default/grub; then
  echo "GRUB_GFXMODE=1920x1080" >> /etc/default/grub
  echo "Set GRUB_GFXMODE=1920x1080 (change if your display needs a different resolution)"
fi

FONT_LOADER="/etc/grub.d/09_parch_theme"
cat > "${FONT_LOADER}" << 'EOF'
#!/bin/sh
for f in unifont-16.pf2 terminus-14.pf2 terminus-16.pf2 din2014_regular_18.pf2 din2014_regular_20.pf2 din2014_regular_23.pf2; do
  echo "loadfont /boot/grub/themes/parch-grub-theme/$f"
done
EOF
chmod +x "${FONT_LOADER}"

if command -v grub-mkconfig > /dev/null 2>&1; then
  echo "Updating GRUB configuration..."
  grub-mkconfig -o /boot/grub/grub.cfg
elif command -v update-grub > /dev/null 2>&1; then
  echo "Updating GRUB configuration..."
  update-grub
fi

echo ""
echo "Parch GRUB Theme installed successfully!"
echo "Reboot to see the changes."
