#!/bin/bash
source $HOME/.config/sway/bin/sway_helpers
BAT_PATH=/sys/class/power_supply
BAT=BAT0
MODE=suspend-then-hibernate
INHIBIT_FILE=$HOME/.inhibit_suspend

## helpers
# 0: charging
# 1: discharging/unknown
function _state() {
  f=$BAT_PATH/$BAT/status
  s=1
  if [ -e $f ]; then
    s=$(grep -c Discharging $f)
  fi
  echo $s
}

function _suspend() {
  _check_inhibit $INHIBIT_FILE
  state=$(_state)
  force=${1:-0}
  if [ $state -eq 1 -o $force -eq 1 ]; then
    systemctl $MODE
  else
    _log SUSPEND INFO aborting. state: $state, force: $force
  fi
}

## main
_log SUSPEND INFO args: $*

case $1 in
  i*)
    _set_inhibit $INHIBIT_FILE $2
    ;;
  suspend)
    _suspend 0
    ;;
  force)
    _suspend 1
    ;;
  *)
    echo "invalid argument: \"$1\""
    echo "arguments: [inhibit [on|off]|suspend|force]"
    ;;
esac
