#!/bin/bash

# omarchy:summary=Set up hibernation with swap and boot resume configuration
# omarchy:requires-sudo=true
# omarchy:args=[--force] [--no-rebuild]

FORCE=false
NO_REBUILD=false
for arg in "$@"; do
  case "$arg" in
    --force) FORCE=true ;;
    --no-rebuild) NO_REBUILD=true ;;
  esac
done

# Resume is Limine-oriented and hibernate is unreliable on Asahi.
if omarchy-hw-aarch64-apple; then
  echo "Skipping hibernation setup (not supported on Apple Silicon)"
  exit 0
fi

if omarchy-sleep-disabled; then
  echo "Hibernation is turned off on this machine" >&2
  exit 0
fi

if [[ ! -f /sys/power/image_size ]]; then
  echo -e "Hibernation is not supported on your system" >&2
  exit 0
fi

# The resume= parameters go on the command line of the boot loader Omarchy
# manages. With --no-rebuild the caller builds the boot image afterwards.
if [[ $(omarchy-boot-backend) == none ]]; then
  echo "Skipping hibernation setup (requires a boot loader Armbian manages)"
  exit 0
fi

MKINITCPIO_CONF="/etc/mkinitcpio.conf.d/omarchy_resume.conf"
SWAP_FILE="/swap/swapfile"
RESUME_REBUILD_PENDING="/var/lib/omarchy/hibernation-resume-rebuild"

# The running kernel can keep image_size while refusing hibernation, for
# example under lockdown. An offline setup may boot a different kernel.
kernel_allows_hibernation() {
  local states
  read -r states 2>/dev/null </sys/power/state && [[ " $states " == *" disk "* ]]
}

install_root_file() {
  local source="$1"
  local destination="$2"
  local mode="$3"
  local stage

  stage=$(sudo /usr/bin/mktemp -- "${destination%/*}/.${destination##*/}.omarchy.XXXXXX") || return 1
  safe_stage_path "$stage" "$destination" || return 1

  if sudo /usr/bin/install -m "$mode" -o root -g root -T "$source" "$stage" &&
    sudo /usr/bin/mv -Tf -- "$stage" "$destination"; then
    return 0
  else
    safe_stage_path "$stage" "$destination" && sudo /usr/bin/rm -f -- "$stage"
    return 1
  fi
}

safe_stage_path() {
  local stage="$1"
  local destination="$2"
  local prefix suffix

  prefix="${destination%/*}/.${destination##*/}.omarchy."
  [[ $stage == "$prefix"* ]] || return 1
  suffix=${stage#"$prefix"}
  [[ $suffix =~ ^[[:alnum:]]{6}$ ]]
}

# The device resume= names for the filesystem holding the swapfile. A kernel name
# such as /dev/nvme0n1p2 follows probe order, so on a machine with two NVMe disks
# it can name the other disk at the next boot, and resume then finds no image.
# The filesystem UUID names the same disk on every boot. A device-mapper name is
# set by whoever opened it (/dev/mapper/root on an encrypted install), so it stays.
resume_device() {
  local source uuid

  source=$(findmnt -no SOURCE -T "$SWAP_FILE" | sed 's/\[.*\]//')
  if [[ $source != /dev/mapper/* ]] && uuid=$(findmnt -no UUID -T "$SWAP_FILE") && [[ -n $uuid ]]; then
    echo "UUID=$uuid"
  else
    echo "$source"
  fi
}

# Earlier setups named an unencrypted root by its kernel name. Rename it in the
# parameters setup writes; parameters edited by hand are left to whoever edited
# them. The boot image keeps the old name until it is rebuilt, so a marker
# written before the parameters change stays until a rebuild succeeds. A failed
# or interrupted rebuild then leaves the marker, and the next run rebuilds again.
rename_resume_device() {
  local previous device offset

  [[ -f $SWAP_FILE ]] || return 0
  previous=$(omarchy-boot-cmdline get resume)
  [[ $previous =~ ^resume=(/dev/[^[:space:]]+)\ resume_offset=([0-9]+)$ ]] || return 0
  [[ ${BASH_REMATCH[1]} != /dev/mapper/* ]] || return 0
  offset=${BASH_REMATCH[2]}
  device=$(resume_device)
  [[ $device == UUID=* ]] || return 0

  if { $NO_REBUILD || sudo install -Dm644 /dev/null "$RESUME_REBUILD_PENDING"; } &&
    sudo omarchy-boot-cmdline set resume "resume=$device" "resume_offset=$offset"; then
    echo "Named the resume device by $device"
    return 0
  fi

  return 1
}

rebuild_renamed_resume_device() {
  [[ -e $RESUME_REBUILD_PENDING ]] && ! $NO_REBUILD || return 0

  if sudo omarchy-boot-rebuild; then
    sudo rm -f "$RESUME_REBUILD_PENDING"
    return
  fi

  echo "Could not rebuild the boot image with the renamed resume device; run omarchy-hibernation-setup again once that is fixed" >&2
  return 1
}

# Check if hibernation is already configured
if [[ -f $MKINITCPIO_CONF ]] && grep -q "^HOOKS+=(resume)$" "$MKINITCPIO_CONF"; then
  # Fix empty resume_offset if btrfs map-swapfile failed during initial setup
  RESUME_PARAMS=$(omarchy-boot-cmdline get resume)
  if [[ $RESUME_PARAMS == *resume_offset= && -f $SWAP_FILE ]]; then
    RESUME_OFFSET=$(sudo btrfs inspect-internal map-swapfile -r "$SWAP_FILE" 2>/dev/null)
    if [[ -n $RESUME_OFFSET ]]; then
      echo "Fixing empty resume_offset ($RESUME_OFFSET)"
      sudo omarchy-boot-cmdline set resume "$RESUME_PARAMS$RESUME_OFFSET"
      if ! $NO_REBUILD; then
        sudo omarchy-boot-rebuild
      fi
    fi
  fi

  # After the offset repair, which leaves the device as it found it.
  rename_resume_device || exit 1
  rebuild_renamed_resume_device || exit 1
  if ! $NO_REBUILD && ! kernel_allows_hibernation; then
    echo "Hibernation is unavailable with the running kernel; resume configuration remains in place" >&2
  else
    echo "Hibernation is already set up"
  fi
  exit 0
fi

if ! $NO_REBUILD && ! kernel_allows_hibernation; then
  echo "Hibernation is unavailable with the running kernel; skipping setup" >&2
  exit 0
fi

if ! $FORCE; then
  MEM_TOTAL_HUMAN=$(LC_ALL=C free --human | awk '/Mem/ {print $2}')
  if ! gum confirm "Use $MEM_TOTAL_HUMAN on boot drive to make hibernation available?"; then
    exit 0
  fi
fi

SWAP_SUBVOLUME="/swap"

# Create btrfs subvolume for swap
if ! sudo btrfs subvolume show "$SWAP_SUBVOLUME" &>/dev/null; then
  echo "Creating Btrfs subvolume"
  sudo btrfs subvolume create "$SWAP_SUBVOLUME"
  sudo chattr +C "$SWAP_SUBVOLUME"
fi

# Create swapfile
if ! sudo swaplabel "$SWAP_FILE" &>/dev/null; then
  echo "Creating swapfile in Btrfs subvolume"
  MEM_TOTAL_KB="$(awk '/MemTotal/ {print $2}' /proc/meminfo)k"
  sudo btrfs filesystem mkswapfile -s "$MEM_TOTAL_KB" "$SWAP_FILE"
fi

# Add swapfile to fstab
if ! grep -Fq "$SWAP_FILE" /etc/fstab; then
  echo "Adding swapfile to /etc/fstab"
  sudo cp -a /etc/fstab "/etc/fstab.$(date +%Y%m%d%H%M%S).back"
  printf "\n# Btrfs swapfile for system hibernation\n%s none swap defaults,pri=0 0 0\n" "$SWAP_FILE" | sudo tee -a /etc/fstab >/dev/null
fi

# Enable swap
if ! swapon --show | grep -q "$SWAP_FILE"; then
  echo "Enabling swap on $SWAP_FILE"
  sudo swapon -p 0 "$SWAP_FILE"
fi

# Ensure keyboard backlight doesn't prevent sleep
# Install this before writing the resume marker so a failed install remains
# retryable through the normal setup command.
if ! install_root_file "$OMARCHY_PATH/default/systemd/system-sleep/keyboard-backlight" \
  /usr/lib/systemd/system-sleep/keyboard-backlight 0755; then
  echo "Could not install the keyboard-backlight system-sleep hook" >&2
  exit 1
fi

# Add resume= kernel parameters so the initramfs resume hook knows where to find the
# hibernation image. Without these, resume happens late (after GPU drivers load) and fails.
# Always rewrite them: parameters left by an earlier setup names that swapfile's offset.
# Write them before the hook: once the hook exists, a rerun reports hibernation as
# set up and never comes back for them, so a failed lookup stops here, changing nothing.
echo "Adding resume kernel parameters"
sudo swapon -p 0 "$SWAP_FILE" 2>/dev/null
RESUME_DEVICE=$(resume_device)
RESUME_OFFSET=$(sudo btrfs inspect-internal map-swapfile -r "$SWAP_FILE")
if [[ -z $RESUME_DEVICE || -z $RESUME_OFFSET ]]; then
  echo "Warning: Could not determine resume parameters for $SWAP_FILE; run omarchy-hibernation-setup again once that is fixed" >&2
  exit 0
fi
sudo omarchy-boot-cmdline set resume "resume=$RESUME_DEVICE" "resume_offset=$RESUME_OFFSET" || exit 1

# Add resume hook to mkinitcpio
sudo mkdir -p /etc/mkinitcpio.conf.d
echo "Adding resume hook to $MKINITCPIO_CONF"
echo "HOOKS+=(resume)" | sudo tee "$MKINITCPIO_CONF" >/dev/null

# Use ACPI alarm for RTC wakeup on s2idle systems (needed for suspend-then-hibernate)
if grep -q "\[s2idle\]" /sys/power/mem_sleep 2>/dev/null && [[ -z $(omarchy-boot-cmdline get rtc-alarm) ]]; then
  echo "Enabling ACPI RTC alarm for s2idle suspend"
  sudo omarchy-boot-cmdline set rtc-alarm rtc_cmos.use_acpi_alarm=1
fi

if ! $NO_REBUILD; then
  echo "Regenerating initramfs..."
  if ! sudo omarchy-boot-rebuild; then
    echo "Could not rebuild the boot image for hibernation; run omarchy-hibernation-setup again once that is fixed" >&2
    exit 1
  fi
  echo
fi

if ! $FORCE && ! $NO_REBUILD && gum confirm "Reboot to enable hibernation?"; then
  omarchy-system reboot
fi
