#!/bin/bash

# This file is used for switching back and forth of the latest nixos gen
# and the default archlinux installment


# Directory where the NixOS generation files are located
gen_dir="/boot/loader/entries"

# Function to update loader.conf with the specified entry
update_loader_conf() {
  local entry="$1"
  sed -i "s/default .*\.conf/default $entry/" /boot/loader/loader.conf
  echo "Updated /boot/loader/loader.conf with $entry"
}

# Check if an argument is provided
if [ $# -eq 1 ]; then
  if [ "$1" == "highest" ]; then
    # Find the NixOS generation file with the highest number
    highest_gen_file=""
    highest_gen_number=0

    for file in "$gen_dir"/nixos-generation-*.conf; do
      # Extract the generation number from the filename
      gen_number=$(echo "$file" | sed 's/.*nixos-generation-\([0-9]*\)\.conf/\1/')
      if [ "$gen_number" -gt "$highest_gen_number" ]; then
        highest_gen_number="$gen_number"
        highest_gen_file="$file"
      fi
    done

    if [ -n "$highest_gen_file" ]; then
      update_loader_conf "$(basename "$highest_gen_file")"
    else
      echo "No NixOS generation files found in $gen_dir"
    fi
  elif [ "$1" == "default" ]; then
    # Set loader.conf back to default arch_linux.conf
    update_loader_conf "arch_linux.conf"
  else
    echo "Invalid argument. Use 'highest' to set to the highest NixOS generation or 'default' to set to arch_linux.conf."
  fi
else
  echo "Usage: $0 <highest|default>"
fi
