#!/bin/bash

# blob:summary=Toggle dedicated vs integrated GPU mode via supergfxd (for hybrid gpu laptops, like Asus G14).
# blob:requires-sudo=true

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

  stage=$(sudo /usr/bin/mktemp -- "${destination%/*}/.${destination##*/}.blob.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##*/}.blob."
  [[ $stage == "$prefix"* ]] || return 1
  suffix=${stage#"$prefix"}
  [[ $suffix =~ ^[[:alnum:]]{6}$ ]]
}

if blob-cmd-missing supergfxctl; then
  blob-pkg-add supergfxctl

  # Create config before starting service to prevent hang on first boot
  sudo tee /etc/supergfxd.conf >/dev/null <<'CONF'
{
  "mode": "Hybrid",
  "vfio_enable": true,
  "vfio_save": false,
  "always_reboot": false,
  "no_logind": false,
  "logout_timeout_s": 180,
  "hotplug_type": "None"
}
CONF

  sudo systemctl enable --now supergfxd
fi

gpu_mode=""
for attempt in {1..3}; do
  if gpu_mode=$(timeout --kill-after=1s 3s supergfxctl -g 2>/dev/null) && [[ -n $gpu_mode ]]; then
    break
  fi

  gpu_mode=""
  (( attempt < 3 )) && sleep 1
done

if [[ -z $gpu_mode ]]; then
  echo "supergfxd is not responding. Try again, or check: systemctl status supergfxd" >&2
  exit 1
fi

case "$gpu_mode" in
"Integrated")
  if gum confirm "Enable dedicated GPU and reboot?"; then
    # Switch to hybrid mode
    sudo sed -i "s/\"mode\": \".*\"/\"mode\": \"Hybrid\"/" /etc/supergfxd.conf

    # Let hybrid mode be the default after system sleep
    sudo rm -rf /usr/lib/systemd/system-sleep/force-igpu

    # Remove the startup delay override (not needed for Hybrid mode)
    sudo rm -rf /etc/systemd/system/supergfxd.service.d/delay-start.conf

    blob-system-reboot
  fi
  ;;
"Hybrid")
  if gum confirm "Use only integrated GPU and reboot?"; then
    # Delay supergfxd startup to avoid race condition with display manager
    # that can cause system freeze when booting in Integrated mode
    sudo mkdir -p /etc/systemd/system/supergfxd.service.d
    if ! install_root_file "$BLOB_PATH/default/systemd/system/supergfxd.service.d/delay-start.conf" \
      /etc/systemd/system/supergfxd.service.d/delay-start.conf 0644; then
      echo "Could not install the supergfxd startup-delay override" >&2
      exit 1
    fi

    # Publish the self-guarding sleep hook before enabling Integrated mode. It
    # remains inert while the config says Hybrid, so any failed step is safe to
    # retry without leaving the GPU config partially switched.
    sudo mkdir -p /usr/lib/systemd/system-sleep
    if ! install_root_file "$BLOB_PATH/default/systemd/system-sleep/force-igpu" \
      /usr/lib/systemd/system-sleep/force-igpu 0755; then
      echo "Could not install the force-igpu system-sleep hook" >&2
      exit 1
    fi

    # Switch both settings in one atomic config rewrite only after every
    # supporting file has been installed successfully.
    sudo sed -i \
      -e 's/"mode": ".*"/"mode": "Integrated"/' \
      -e 's/"vfio_enable": false/"vfio_enable": true/' \
      /etc/supergfxd.conf

    blob-system-reboot
  fi
  ;;
*)
  echo "Hybrid GPU not found or in unknown mode."
  exit 1
  ;;
esac
