#!/bin/bash

export DISPLAY=:0

tvservice=`which tvservice >/dev/null ; echo $?`
vcgencmd=`which vcgencmd >/dev/null ; echo $?`

case "$1" in
    root-on)
        if [ $tvservice = 0 ]; then
          # must be run in sudo mode
          /opt/vc/bin/tvservice --preferred || echo "no tvservice"
          # Hack to enable virtual terminal nr 7 again:
          chvt 6
          chvt 7
          sleep 1
        fi
    ;;
    on)
      # power on
      if [ $vcgencmd = 0 ]; then
        # https://raspberrypi.stackexchange.com/questions/52042/turning-tvservice-on-and-off-leaves-screen-blank
        vcgencmd display_power 1 || echo "no vcgencmd"
      else
        for screen in `xrandr | awk '/ connected/{print $1}'`; do
          xrandr --output "$screen" --auto
        done
      fi

      # Force screen on
      xset dpms force on

      # CEC
      echo "on 0" | cec-client -s > /dev/null
      NOT_CEC_COMPATIBLE=$?
      if [ $NOT_CEC_COMPATIBLE -ne 0 ]; then
        ( sleep 5 ; echo "as" | cec-client -s > /dev/null ) &
      fi
    ;;

    off)
        # CEC
        echo "standby 0" | cec-client -s > /dev/null

        # force screen off
        xset dpms force off

        # power off
        if [ $vcgencmd = 0 ]; then
          vcgencmd display_power 0 || echo "no vcgencmd"
        else
          for screen in `xrandr | awk '/ connected/{print $1}'`; do
            xrandr --output "$screen" --off
          done
        fi
    ;;
    state)
        powerstate=`vcgencmd display_power 2>&1`
        # if [[ $? != 0 ]] || [[ $tvstate == *"Failed to connect"* ]] ; then
        if [[ $? != 0 ]] ; then
            listmonitors=`xrandr --listmonitors`
            if [[ $? != 0 ]]; then
              echo 'unavailable'
            elif [[ $listmonitors == "Monitors: 0" ]] ; then
              echo 'off'
            elif [[ $listmonitors == *"Monitors:"* ]] ; then
              echo 'on'
            else
              echo 'unavailable'
            fi
        elif [[ $powerstate == "display_power=0" ]] ; then
            echo 'off'
        else
            echo 'on'
        fi
    ;;
    subscribe)
        /opt/vc/bin/tvservice -M
    ;;
    screens)
        xrandr | awk '/ connected/{print $1}'
    ;;
    screens-on)
        for screen in ${@:2}; do
          xrandr --output "$screen" --auto
        done
    ;;
    screens-off)
        for screen in ${@:2}; do
          xrandr --output "$screen" --off
        done
    ;;
    screen-off)
        xrandr --output "$2" --off
    ;;
    screen-on)
        xrandr --output "$2" --auto ${@:3}
    ;;
    reverse-screen)
        xrandr --output "$2" --auto --rotate inverted
        if [ -z "$3" ]; then
          echo "No xinput device provided"
        else
          xinput set-prop "$3" "Coordinate Transformation Matrix" -1 0 1 0 -1 1 0 0 1
        fi
    ;;
    displays)
        ps -u $(id -u) -o pid= | \
            while read pid; do
                cat /proc/$pid/environ 2>/dev/null | tr '\0' '\n' | grep '^DISPLAY=:'
            done | grep -o ':[0-9]*' | sort -u
    ;;
    screenshot)
         if [ "$2" = 'rpi' ]; then
             nice -19 raspi2png --stdout -h 100
         else
             nice -19 scrot -t 20 -q 50 /tmp/screenshot.jpg || exit 1
             rm /tmp/screenshot.jpg
             cat /tmp/screenshot-thumb.jpg
         fi
    ;;
    waitForX)
      MAX=120 # About 60 seconds
      CT=0
      while ! xdpyinfo >/dev/null 2>&1; do
          sleep 0.50s
          CT=$(( CT + 1 ))
          if [ "$CT" -ge "$MAX" ]; then
              echo "FATAL: $0: Gave up waiting for X server $DISPLAY"
              exit 1
          fi
      done
    ;;
    *)
        echo "Usage screen.sh {on|off|state|subscribe|screenshot [rpi]|waitForX}"
        exit 1
    ;;
esac

exit 0
