#!/bin/bash
#-----------------------------------------------------------------------------
# x11tera_on_unlock
# The script to use with the x11tera 'on_disconnect' function.
# This script is called when a disconnection occurs.
#-----------------------------------------------------------------------------

# used for restore monitors to active state
export WITH_MONITORS_ON=1
# used for unlock attached keyboards and pointers (mouses, touchpads, trackpoints)
export WITH_UNLOCK_INPUTS=1
# used for lock session automatically
export WITH_LOCK_SESSION=1
# used for power on connected displays
export WITH_DPMS_ON=0
# used for forced stop x11tera service on user' disconnect
export WITH_FORCED_STOP=0

# Don't edit behind this line
operation=$1
case "$operation" in
  all|"")
    echo "x11tera_on_unlock ALL operation in progress..."
    operation=all
    ;;
  logout|stage0)
    echo "x11tera_on_unlock LOGOUT operation in progress..."
    operation=logout
    ;;
  logout-systemd|stage0-systemd)
    echo "x11tera_on_unlock LOGOUT (systemd-logind only) operation in progress..."
    operation=logout-systemd
    ;;
  logout-lightdm|stage0-lightdm)
    echo "x11tera_on_unlock LOGOUT (lightdm only) operation in progress..."
    operation=logout-lightdm
    ;;
  inout|stage1)
    echo "x11tera_on_unlock IN/OUT restore operation in progress..."
    operation=inout
    ;;
  finish|stage2)
    echo "x11tera_on_unlock FINISH restore operation in progress..."
    operation=finish
    ;;
  *)
    echo "unsupported '$operation' operation" 1>&2
    exit 1
    ;;
esac

echo "x11tera_on_unlock (uid=$UID, user=$USER, display=$DISPLAY, xauth=$XAUTHORITY, operation=$operation)"

export TMP_USER_UNLOCK=/tmp/x11tera_xrandr_restore
export DIR_PERMANENT_CFGS=/etc/termidesk/tera
export PATH_USER_LOCK=$DIR_PERMANENT_CFGS/x11tera_user_lock.conf
export PATH_USER_UNLOCK=$DIR_PERMANENT_CFGS/x11tera_user_unlock.conf
export PATH_GREETER_LOCK=$DIR_PERMANENT_CFGS/x11tera_greeter_lock.conf
export PATH_GREETER_UNLOCK=$DIR_PERMANENT_CFGS/x11tera_greeter_unlock.conf

if [ "$operation" == "all" -o "$operation" == "logout" -o "$operation" == "logout-systemd" ]; then
  # lock session automatically (loginctl, part of systemd-logind)
  if [[ ! -z "$(which loginctl)" ]] && [[ "$WITH_LOCK_SESSION" == "1" || "$WITH_LOCK_SESSION" == "yes" ]]; then
    for id in $(loginctl show-seat seat0 | grep Sessions= | cut -d'=' -f2); do
      s=$(loginctl show-session $id --p Id --p Remote --p Name --p Type --p Class --p Active --p IdleHint --p LockedHint | tr '\n' ' ' | grep Remote=no.*Class=user.*Active=yes)
      if [[ ! -z "$s" ]]; then
        echo "Lock session $s"
        loginctl lock-session $id
        break
      fi
    done
  fi
fi

if [ "$operation" == "all" -o "$operation" == "logout" -o "$operation" == "logout-lightdm" ]; then
  # lock session automatically (dm-tool, part of lightdm)
  if [[ $(which dm-tool) ]] && \
     [[ $(grep lightdm$ /etc/X11/default-display-manager) ]] && \
     [[ $(which loginctl) ]] && \
     [[ "$WITH_LOCK_SESSION" == "1" || "$WITH_LOCK_SESSION" == "yes" ]]; then
    for id in $(loginctl show-seat seat0 | grep Sessions= | cut -d'=' -f2); do
      s=$(loginctl show-session $id --p Id --p Remote --p Name --p Type --p Class --p Active --p IdleHint --p LockedHint | tr '\n' ' ' | grep Remote=no.*Class=user.*Active=yes)
      if [[ ! -z "$s" ]]; then
        echo "Lock session $s"
        XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0 dm-tool lock
        break
      fi
    done
  fi
fi

is_greeter_active()
{
  for id in $(loginctl show-seat seat0 | grep Sessions= | cut -d'=' -f2); do
    s=$(loginctl show-session $id --p Id --p Remote --p Name --p Type --p Class --p Active --p IdleHint --p LockedHint | tr '\n' ' ' | grep Remote=no.*Class=greeter.*Active=yes)
    if [[ ! -z "$s" ]]; then
      return 0
      break
    fi
  done
  return 1
}

monitors_unlock()
{
  unlock_mode=""
  list=""
  while read -r line; do
    output=$(echo "$line" | cut -d' ' -f1)
    unlock_mode="$unlock_mode --output $output --brightness 1"
    list="$list $output"
  done < <(xrandr | grep -E " connected .*x.* \(")
  xrandr $unlock_mode && rc=$? || rc=$?
  if [ $rc -eq 0 ]; then
    echo "Monitor(s)$list unlocked, code=$rc"
  else
    echo "WARNING: Monitor(s)$list not unlocked, code=$rc" 1>&2
  fi
  return 0
}

# used for restore monitor settings (permanent configs of this computer)

monitors_restore_failure()
{
  # Failed state:
  # HDMI-0 connected (normal left inverted right x axis y axis)
  #    1280x1024     60.02 +  75.02
  #    1920x1080     59.94
  #    1280x800      59.81
  #    ...
  # DP-4 connected primary (normal left inverted right x axis y axis)
  #    3840x2160     60.00 +  30.00
  #    2560x1440     59.95
  #    ...
  output=""
  mode=""
  xrandr | grep " connected" -A1 | while read -r line; do
    if [ "$line" = "--" ]; then
      output=""
      mode=""
    elif [ -z "$output" ]; then
      x=$(echo "$line" | cut -d'(' -f1)
      output=$(echo "$x" | cut -d' ' -f1)
      if [ ! -z "$output" ]; then
        echo "Found monitor: $output"
      fi
    elif [ -z "$mode" ]; then
      mode=$(echo "$line" | awk '{print $1}')
      xrandr --output $output --mode $mode && rc=$? || rc=$?
      echo "Monitor $output restored to $mode, code=$rc"
      output=""
      mode=""
    fi
  done
}

if [ "$operation" == "all" -o "$operation" == "inout" ]; then
  if [[ "$WITH_MONITORS_ON" == "1" || "$WITH_MONITORS_ON" == "yes" ]]; then
    xrandr | grep " connected" | while read -r line; do
     echo "Found monitor: $line"
    done

    # xrandr restore of monitor modes on client' disconnect
    if [[ ! -z "$(which xrandr)" ]]; then
      failure=1
      if is_greeter_active; then
        permanent_config=$PATH_GREETER_UNLOCK
      else
        permanent_config=$PATH_USER_UNLOCK
      fi
      if [ -f $permanent_config ]; then
        unlock_mode=$(cat $permanent_config)
        echo "Permanent unlock mode ($permanent_config): $unlock_mode"
        if [[ ! -z "$unlock_mode" ]]; then
          xrandr --verbose $unlock_mode && rc=$? || rc=$?
          if [ $rc -eq 0 ]; then
            echo "Monitor settings applied, code=$rc"
            failure=0
          else
            echo "WARNING: Monitor settings not applied, code=$rc" 1>&2
          fi
        else
          echo "WARNING: illegal lock mode to apply" 1>&2
        fi
      elif [ -f $TMP_USER_UNLOCK ]; then
        prev_mode=$(cat $TMP_USER_UNLOCK)
        echo "Previous dynamic mode: $prev_mode"
        if [[ ! -z "$prev_mode" ]]; then
          xrandr --verbose $prev_mode && rc=$? || rc=$?
          if [ $rc -eq 0 ]; then
            echo "Monitor settings restored, code=$rc"
            failure=0
          else
            echo "WARNING: Monitor settings not restored, code=$rc" 1>&2
          fi
        else
          echo "WARNING: illegal previous mode to restore" 1>&2
        fi
        rm -fv $TMP_USER_UNLOCK
      else
        echo "Not found $TMP_USER_UNLOCK (xrandr off disabled?)" 1>&2
      fi
    fi
    if [ $failure -eq 1 ]; then
      monitors_restore_failure
    fi
    # если падает видео-драйвер, то рестарт занимает около 6 сек
    # обычно экраны становятся готовы в теч. 1 сек
    sleep 6 && monitors_unlock &
  fi

  # unlock attached keyboards and pointers (mouses, touchpads, trackpoints)
  if [[ ! -z "$(which xinput)" ]] && [[ "$WITH_UNLOCK_INPUTS" == "1" || "$WITH_UNLOCK_INPUTS" == "yes" ]]; then
    # fix: ASTRA17 does not display the list of floating devices
    xinput list | tr '\t' ' ' | grep "\[slave \+\(keyboard\|pointer\)" | while read -r line; do
      id=$(echo "$line" | awk -F "id=" '{print $2}' | cut -d' ' -f1)
      if [[ ! -z "$id" ]]; then
        nm=$(echo "$line" | awk -F "id=" '{print $1}')  # | awk -F "↳" '{print $2}'
        echo "Enable active input id=$id $nm"
        xinput enable $id
      fi
    done
    # activate floating devices
    xinput list | tr '\t' ' ' | grep "\[floating \+slave\]" | while read -r line; do
      id=$(echo "$line" | awk -F "id=" '{print $2}' | cut -d' ' -f1)
      if [[ ! -z "$id" ]]; then
        nm=$(echo "$line" | awk -F "id=" '{print $1}')  # | awk -F "~" '{print $2}'
        echo "Enable floating input id=$id $nm"
        xinput enable $id
      fi
    done
  fi

  # power on connected displays
  if [[ ! -z "$(which xset)" ]] && [[ "$WITH_DPMS_ON" == "1" || "$WITH_DPMS_ON" == "yes" ]]; then
    echo "Force DPMS mode ON"
    xset dpms force on
  fi
fi

if [ "$operation" == "all" -o "$operation" == "finish" ]; then
  # stopping x11tera application (to restart it by systemd)
  if [[ "$WITH_FORCED_STOP" == "1" || "$WITH_FORCED_STOP" == "yes" ]]; then
    echo "Forced STOP detected"
    /usr/bin/x11tera.sh stop
  fi
fi

exit 0
