#!/usr/bin/env bash

SCREEN_WIDTH="$(xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f1)"
SCREEN_HEIGHT="$(xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f2)"
SCREEN_RATIO="$(awk -v height={{ screen_height.stdout }} -v width={{ screen_width.stdout }} 'BEGIN { print ((height / width) * 1000) }')"
SCREEN_RATIO="${SCREEN_RATIO%.*}"
SCREEN_RATIO_ULTRAWIDE="2100"
GRUB_RESOLUTION_TYPE="1080p"

### Determine if screen is ultrawide
if (( $(echo "$SCREEN_RATIO $SCREEN_RATIO_ULTRAWIDE" | awk '{print ($1 > $2)}') )); then
  GRUB_RESOLUTION_TYPE="ultrawide"
fi

### Optimize the GRUB resolution
logg info 'Optimizing the GRUB resolution'
if cat /etc/default/grub | grep GRUB_GFX_MODE; then
  sudo sed -i '/.*GRUB_GFXMODE.*/GRUB_GFXMODE=auto/' /etc/default/grub
else
  echo "GRUB_GFXMODE=auto" | sudo tee -a /etc/default/grub
fi

### Add GRUB_GFXPAYLOAD_LINUX=keep
logg info 'Ensuring GRUB_GFXPAYLOAD_LINUX is set to keep'
if cat /etc/default/grub | grep GRUB_GFXPAYLOAD_LINUX; then
  sudo sed -i '/.*GRUB_GFXPAYLOAD_LINUX.*/GRUB_GFXPAYLOAD_LINUX="keep"/' /etc/default/grub
else
  echo 'GRUB_GFXPAYLOAD_LINUX="keep"' | sudo tee -a /etc/default/grub
fi

### Set GRUB theme
logg info "Setting GRUB2 theme to {{ .theme }}-$GRUB_RESOLUTION_TYPE"
if cat /etc/default/grub | grep GRUB_THEME; then
  sudo sed -i '/.*GRUB_THEME.*/GRUB_THEME="{{ .theme }}-'"$GRUB_RESOLUTION_TYPE"'"/' /etc/default/grub
else
  echo 'GRUB_THEME="{{ .theme }}-'"$GRUB_RESOLUTION_TYPE"'"' | sudo tee -a /etc/default/grub
fi

### Set GRUB background
logg info 'Set GRUB background to prevent FOUC'
if cat /etc/default/grub | grep GRUB_BACKGROUND; then
  sudo sed -i '/.*GRUB_BACKGROUND.*/GRUB_BACKGROUND="/usr/local/share/grub/{{ .theme }}-blue.png"/' /etc/default/grub
else
  echo 'GRUB_BACKGROUND="/usr/local/share/grub/{{ .theme }}-blue.png"' | sudo tee -a /etc/default/grub
fi

### Configure Shift to see menu feature
logg info 'Configuring Shift to see GRUB2 menu feature'
sed -i '/GRUB_FORCE_HIDDEN_MENU/d' /etc/default/grub
echo "GRUB_FORCE_HIDDEN_MENU={{ .grub.shiftToSeeMenu }}" > /etc/default/grub

### Remove duplicate lines
logg info 'Ensuring there are no duplicate entries in /etc/default/grub'
cat /etc/default/grub | uniq -u | sudo tee /etc/default/grub
