#!/usr/bin/env bash
# This script takes one argument, which is the ACTION_TYPE
#
# ACTION_TYPE can be one of the following:
#   LID_OPEN - The script is called when the lid is opened
#   LID_CLOSE - The script is called when the lid is closed
#
# Requirements for using clamshell mode:
#   - wm.clamshell.enabled is set to true
#   - An inbuilt display is found
#   - More than one display is connected

ACTION_TYPE=$1


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

# on_ac_power exits 0 on mains power, 1 on battery and 255 when the power
# source is unknown (no power sensors); only exit status 1 means battery.
on_battery() {
  on_ac_power
  [[ $? -eq 1 ]]
}

get_lid_close_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_sway "$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: $1"
  esac
}

# Lock the session before suspending, so that a suspend that is delayed or
# fails never leaves the session unlocked. `gtklock -d` returns once the
# compositor has confirmed the lock; a locker that does not daemonize keeps
# running and the bounded wait just times out.
lock_before_sleep() {
  local DEFAULT_LOCK="gtklock -d --background $(trawlcat regolith.lockscreen.wallpaper.file /dev/null)"
  local LOCK=$( trawlcat wm.program.lock_sway "$DEFAULT_LOCK" )
  $LOCK &
  local LOCK_PID=$!
  for _ in {1..50}; do
    kill -0 "$LOCK_PID" 2>/dev/null || return 0
    sleep 0.1
  done
  echo "Locker still running after 5 seconds, continuing"
}

exec_lid_close_action() {
  case "$1" in
    "SLEEP" | "HIBERNATE")
      lock_before_sleep
      ;;
  esac
  exec $2
}

handle_clamshell() {
  if [[ "$ACTION_TYPE" == "LID_CLOSE" ]]; then
    echo "clamshell mode: Turning off inbuilt display for lid close"
    swaymsg output "$INBUILT_DISPLAY" disable
  elif [[ "$ACTION_TYPE" == "LID_OPEN" ]]; then
    echo "clamshell mode: Turning on inbuilt display for lid open"
    swaymsg output "$INBUILT_DISPLAY" enable
  else
    exit_with_error "clamshell mode: Unhandled ACTION_TYPE - $ACTION_TYPE"
  fi
}

DEFAULT_INBUILT_DISPLAY=$( swaymsg -t get_outputs --raw | jq -r '[ .[] | select(.name | startswith("eDP")).name ] | .[0]' )
INBUILT_DISPLAY=$( trawlcat wm.clamshell.display "$DEFAULT_INBUILT_DISPLAY" )
DISPLAY_COUNT=$( swaymsg -t get_outputs --raw | jq 'length')
CLAMSHELL_ENABLED=$( trawlcat wm.clamshell.enabled "true" )
AC_ACTION=$( trawlcat wm.lidclose.action.power "LOCK" )
BATTERY_ACTION=$( trawlcat wm.lidclose.action.battery "SLEEP" )
AC_ACTION_CMD=$( get_lid_close_cmd "$AC_ACTION" )
BATTERY_ACTION_CMD=$( get_lid_close_cmd "$BATTERY_ACTION" )


if [[ $DISPLAY_COUNT > 1 ]]; then
  if [[ -n $INBUILT_DISPLAY && "$CLAMSHELL_ENABLED" == "true" ]]; then
    handle_clamshell
    exit 0
  elif [[ -n $INBUILT_DISPLAY && "$CLAMSHELL_ENABLED" == "false" ]]; then
    echo "External display connected but clamshell mode is disabled"
  elif [[ -z $INBUILT_DISPLAY ]]; then
    echo "Inbuilt display not found."
  else
    exit_with_error "External display connected but invalid or missing value for resource wm.clamshell.enabled"
  fi
else
  echo "No external display is connected."
fi

echo "Clamshell requirements not met. Executing lid close action."

if [[ "$ACTION_TYPE" == "LID_OPEN" ]]; then
  echo "Turning on inbuilt display for lid open"
  exec swaymsg output "$INBUILT_DISPLAY" enable
elif [[ "$ACTION_TYPE" == "LID_CLOSE" ]]; then
  if ! on_battery; then
    echo "Executing lid close action on Power - $AC_ACTION"
    exec_lid_close_action "$AC_ACTION" "$AC_ACTION_CMD"
  else
    echo "Executing lid close action on Battery- $BATTERY_ACTION"
    exec_lid_close_action "$BATTERY_ACTION" "$BATTERY_ACTION_CMD"
  fi
else
  exit_with_error "Unhandled ACTION_TYPE - $ACTION_TYPE"
fi

