#!/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
#
# Otherwise the lid close action is the one systemd-logind is configured with,
# as in the X11 session: HandleLidSwitchExternalPower on AC (falling back to
# HandleLidSwitch, as logind does) and HandleLidSwitch on battery, both
# "suspend" by default. regolith-powerd keeps logind from acting on the lid
# itself. The resources wm.lidclose.action.power and wm.lidclose.action.battery,
# when set, take precedence.

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 ]]
}

# The lock program is wm.program.lock_sway, as for the lock key. When it is
# unset, the default is regolith-sway-gtklock, from the regolith-sway-gtklock
# package; set wm.program.lock_sway to use another lock application.
get_lid_close_cmd() {
  # Actions to take based on the value of wm.lidclose.action
  local DEFAULT_LOCK="regolith-sway-gtklock"
  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"
      ;;

    "HYBRID_SLEEP")
      echo "systemctl hybrid-sleep"
      ;;

    "SUSPEND_THEN_HIBERNATE")
      echo "systemctl suspend-then-hibernate"
      ;;

    *)
      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="regolith-sway-gtklock -d"
  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"
}

# Print logind's setting for the lid switch property $1 (HandleLidSwitch,
# HandleLidSwitchExternalPower), or nothing when it is unset or unreadable.
logind_lid_setting() {
  busctl get-property org.freedesktop.login1 /org/freedesktop/login1 \
    org.freedesktop.login1.Manager "$1" 2>/dev/null | sed -n 's/^s "\(.*\)"$/\1/p'
}

# Print the clamshell action for a logind lid switch setting, or $2 for an
# empty or unknown setting.
logind_lid_action() {
  case "$1" in
    "ignore")                 echo "DO_NOTHING" ;;
    "lock")                   echo "LOCK" ;;
    "suspend" | "sleep")      echo "SLEEP" ;;
    "hibernate")              echo "HIBERNATE" ;;
    "hybrid-sleep")           echo "HYBRID_SLEEP" ;;
    "suspend-then-hibernate") echo "SUSPEND_THEN_HIBERNATE" ;;
    "poweroff" | "halt")      echo "SHUTDOWN" ;;
    *)                        echo "$2" ;;
  esac
}

exec_lid_close_action() {
  case "$1" in
    "SLEEP" | "HIBERNATE" | "HYBRID_SLEEP" | "SUSPEND_THEN_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
}

# The inbuilt display is the first output on a laptop panel connector: eDP,
# LVDS (older laptops) or DSI (tablets and some small laptops). With none of
# them, it is empty, not jq's "null", so that the lid close action still runs.
DEFAULT_INBUILT_DISPLAY=$( swaymsg -t get_outputs --raw | jq -r '[ .[] | select(.name | test("^(eDP|LVDS|DSI)")).name ] | .[0] // empty' )
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" )
LOGIND_BATTERY_ACTION=$( logind_lid_action "$( logind_lid_setting HandleLidSwitch )" "SLEEP" )
LOGIND_AC_ACTION=$( logind_lid_action "$( logind_lid_setting HandleLidSwitchExternalPower )" "$LOGIND_BATTERY_ACTION" )
AC_ACTION=$( trawlcat wm.lidclose.action.power "$LOGIND_AC_ACTION" )
BATTERY_ACTION=$( trawlcat wm.lidclose.action.battery "$LOGIND_BATTERY_ACTION" )
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
  if [[ -z $INBUILT_DISPLAY ]]; then
    exit 0
  fi
  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

