#!/bin/sh

# nvidia_dpms_fix.sh
# 2011-06-12
# by Gernot WALZL

# nasty workaround for nvidia drivers to resume from dpms off/suspend

export DISPLAY=:0

getXauthority () {
  export XAUTHORITY=$(ps -C X -f | grep " $DISPLAY " \
    | sed -n 's/.* -auth \([^ ]*\).*/\1/p')
}

handle_line () {
  if echo "$1" | grep -e "(EE) NVIDIA.* DisplayPort link training failed" \
      > /dev/null; then
    getXauthority
    xset dpms force on
  fi
}

tail --follow=name /var/log/Xorg.0.log --retry --lines=1 2> /dev/null \
  | while read line; do
    handle_line "$line"
  done