#!/usr/bin/env bash
set -euo pipefail

# Toggle DP-1 between 4K@165 and 1080p@330 and keep DP-2 positioned flush so
# you don't get a "dead gap" for the mouse.

PROFILE_FILE="/home/raga/.config/sway/scripts/display-profile/display-profile.conf"

MODE_4K="3840x2160@165Hz"
MODE_GAME="1920x1080@330Hz"

# Bar tuning per mode
BAR_HEIGHT_4K="40"
BAR_FONT_4K="pango: FontAwesome, monospace 14"

BAR_HEIGHT_GAME="16"
BAR_FONT_GAME="pango: FontAwesome, monospace 8"

# DP-2 bar settings (static)
DP2_BAR_HEIGHT="24"
DP2_BAR_FONT="pango: FontAwesome, monospace 10"

get_current_profile_mode() {
  # Reads the last-written profile state instead of querying the monitor.
  # This makes toggling deterministic even if the display reports odd modes.
  if [[ ! -f "$PROFILE_FILE" ]]; then
    echo "$MODE_4K"
    return
  fi

  # Example line: set $lg_left_monitor_mode 3840x2160@165Hz
  awk '$1=="set" && $2=="$lg_left_monitor_mode" {print $3; found=1} END {if(!found) exit 1}' "$PROFILE_FILE" 2>/dev/null \
    || echo "$MODE_4K"
}

write_profile() {
  local lg_left_monitor_mode="$1"
  local lg_left_monitor_bar_height="$2"
  local lg_left_monitor_bar_font="$3"
  local right_monitor_x="$4"

  local tmp
  tmp="$(mktemp)"
  cat >"$tmp" <<EOF
# Autogenerated by display-profile-toggle.sh. Manual edits will be overwritten.

set \$lg_left_monitor_mode ${lg_left_monitor_mode}
set \$lg_left_monitor_bar_height ${lg_left_monitor_bar_height}
set \$lg_left_monitor_bar_font ${lg_left_monitor_bar_font}

set \$right_monitor_x ${right_monitor_x}
set \$right_monitor_bar_height ${DP2_BAR_HEIGHT}
set \$right_monitor_bar_font ${DP2_BAR_FONT}
EOF

  mkdir -p "$(dirname "$PROFILE_FILE")"
  mv -f "$tmp" "$PROFILE_FILE"
}

main() {
  local current_mode
  current_mode="$(get_current_profile_mode)"

  if [[ "$current_mode" == "$MODE_4K" ]]; then
    # Switch to game mode (1080p @ high refresh)
    write_profile "$MODE_GAME" "$BAR_HEIGHT_GAME" "$BAR_FONT_GAME" "1920"
  else
    # Switch back to 4K
    write_profile "$MODE_4K" "$BAR_HEIGHT_4K" "$BAR_FONT_4K" "3840"
  fi

  swaymsg reload >/dev/null
}

main "$@"
