#!/bin/bash

export DISPLAY=:0

case "$1" in
    on)
        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
        /opt/vc/bin/tvservice --preferred || echo "no tvservice"
        xset dpms force on
    ;;
    off)
        /opt/vc/bin/tvservice -off || echo "no tvservice"
        echo "standby 0" | cec-client -s > /dev/null
        xset dpms force off
    ;;
    state)
        tvstate=`/opt/vc/bin/tvservice -s 2>&1`
        if [[ $? != 0 ]] || [[ $tvstate == *"Failed to connect"* ]] ; then
            echo 'unavailable'
        elif [[ $tvstate == *"off"* ]] ; then
            echo 'off'
        else
            echo 'on'
        fi
    ;;
    subscribe)
        /opt/vc/bin/tvservice -M
    ;;
    screens)
        xrandr | awk '/ connected/{print $1}'
    ;;
    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 [ "$BOARD_ID" = 'rpi' ]; then
             raspi2png --stdout -h 100
         else
             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|waitForX}"
        exit 1
    ;;
esac

exit 0
