#!/bin/bash

# --- DEFAULTS ---
FILE="/etc/default/grub"
DRY_RUN=false
NEW_SETTING=""

# --- HELP FUNCTION ---
usage() {
  echo "Usage: sudo $0 [OPTION] \"setting=value\""
  echo "Example: sudo $0 \"consoleblank=3\""
  echo ""
  echo "Options:"
  echo "  -d, --dry-run    Show changes without applying them"
  echo "  -h, --help       Display this help message"
  exit 1
}

# --- ARGUMENT PARSING ---
while [[ $# -gt 0 ]]; do
  case $1 in
  -d | --dry-run)
    DRY_RUN=true
    shift
    ;;
  -h | --help)
    usage
    ;;
  *)
    NEW_SETTING="$1"
    shift
    ;;
  esac
done

# Check if a setting was actually provided
if [[ -z "$NEW_SETTING" ]]; then
  echo "❌ Error: No GRUB setting provided."
  usage
fi

# --- LOGIC ---
apply_grub_change() {
  local TARGET="$1"
  # Regex: Appends TARGET inside the quotes of GRUB_CMDLINE_LINUX_DEFAULT
  local SED_LOGIC="/^GRUB_CMDLINE_LINUX_DEFAULT=/ s/\"\([^\"]*\)\"/\"\1 $TARGET\"/; s/  */ /g; s/ $TARGET\"/$TARGET\"/"

  # 1. PRE-CHECK
  if grep -q "$TARGET" "$FILE"; then
    echo "ℹ️  SKIP: '$TARGET' already exists in $FILE."
    return 0
  fi

  # 2. EXECUTION
  if [ "$DRY_RUN" = true ]; then
    echo "🔍 DRY RUN: Simulating '$TARGET' addition..."
    grep "^GRUB_CMDLINE_LINUX_DEFAULT=" "$FILE" | sed "$SED_LOGIC"
  else
    # Ensure script is run as root for actual changes
    if [[ $EUID -ne 0 ]]; then
      echo "❌ Error: This script must be run with sudo to apply changes."
      exit 1
    fi

    echo "💾 Backing up to $FILE.bak..."
    cp "$FILE" "$FILE.bak"

    echo "🔧 Applying '$TARGET' to $FILE..."
    sed -i "$SED_LOGIC" "$FILE"

    # 3. VERIFICATION & UPDATE
    if grep -q "$TARGET" "$FILE"; then
      echo "✅ SUCCESS: Updating bootloader..."
      update-grub
    else
      echo "❌ ERROR: Failed to apply changes."
      exit 1
    fi
  fi
}

# --- EXECUTE ---
apply_grub_change "$NEW_SETTING"
