#!/usr/bin/env bash

exit_with_error() {
  echo "$1"
  echo "Exiting..."
  exit 1
}

get_action_cmd() {
  # Actions to take based on the value of wm.lidclose.action
  local DEFAULT_LOCK="gtklock --background $(trawlcat regolith.lockscreen.wallpaper.file /dev/null)"
  local LOCK=$( trawlcat wm.program.lock "$DEFAULT_LOCK")
  local SLEEP=$( trawlcat wm.program.sleep "systemctl suspend" )
  local HIBERNATE=$( trawlcat wm.program.hibernate "systemctl hibernate" )
  local SHUTDOWN=$( trawlcat wm.program.shutdown "gnome-session-quit --power-off --no-prompt")

  case "$1" in
    "DO_NOTHING")
      echo "true"
      ;;

    "LOCK")
      echo "$LOCK"
      ;;

    "SLEEP")
      echo "$SLEEP"
      ;;

    "HIBERNATE")
      echo "$HIBERNATE"
      ;;

    "SHUTDOWN")
      echo "$SHUTDOWN"
      ;;

    *)
      exit_with_error "Invalid or missing value for resource wm.lidclose.action"
  esac
}

INBUILT_DISPLAY=$( swaymsg -t get_outputs --raw | jq -r '[ .[] | select(.name | startswith("eDP")).name ] | .[0]' )

# Early return if there is no inbuilt display
if [[ -z $INBUILT_DISPLAY ]]; then
  echo "No inbuilt display found. Exiting..."
  exit 0
fi

# Determine the action to take based on whether an external display is connected
DISPLAY_COUNT=$( swaymsg -t get_outputs --raw | jq 'length')
CLAMSHELL_ENABLED=$( trawlcat wm.clamshell.enabled "true" )
if [[ $DISPLAY_COUNT > 1 ]]; then
  if [[ "$CLAMSHELL_ENABLED" == "true" ]]; then
    echo "External display connected and clamshell mode enabled"
    swaymsg "bindswitch --locked --reload lid:off output $INBUILT_DISPLAY enable"
    swaymsg "bindswitch --locked --reload lid:on output $INBUILT_DISPLAY disable"
    exit 0
  elif [[ "$CLAMSHELL_ENABLED" == "false" ]]; then
    echo "External display connected and clamshell mode disabled. Falling back to lid close action"
  else
    exit_with_error "Multiple displays connected but invalid or missing value for resource wm.clamshell.enabled"
  fi
fi

echo "No external display is connected."


AC_ACTION=$( trawlcat wm.lidclose.action.power "LOCK" )
BATTERY_ACTION=$( trawlcat wm.lidclose.action.battery "SLEEP" )
AC_ACTION_CMD=$( get_action_cmd "$AC_ACTION" )
BATTERY_ACTION_CMD=$( get_action_cmd "$BATTERY_ACTION" )
ACTION_CMD="bash -c \"if on_ac_power; then $AC_ACTION_CMD; else $BATTERY_ACTION_CMD; fi\""

echo "Lid close action on Power - $AC_ACTION"
echo "Lid close action on Battery- $BATTERY_ACTION"


swaymsg "bindswitch --locked --reload lid:on exec '$ACTION_CMD'"
swaymsg "bindswitch --locked --reload lid:off exec true"
