#!/bin/bash
# Script to control and query a connected screen
# For infoscreen purposes
# Tries to use cec-client and falls back to DPMS
# Usage: ./screencontrol.sh [query | on | off]

export DISPLAY=:0
if [ -z "${1}" ]; then
  set -- "query"
fi

if [ "${1}" == "query" ]; then
  if status=$(echo "pow 0" | cec-client -s -d 1); then
    if [[ ${status} =~ (power status: on) ]]; then
      echo "Screen is on"
    else
      echo "Screen is off"
    fi
  else
    if status=$(xset q); then
      if [[ ${status} =~ (Monitor is Off) ]]; then
        echo "Screen is off"
      else
        echo "Screen is on"
      fi
    else
      echo "Unable to determine status of screen"
      exit 1
    fi
  fi
elif [ "${1}" == "on" ]; then
  if echo "on 0" | cec-client -s -d 1 >/dev/null; then
    xset s off
    xset s noblank
    xset -dpms
    echo "Screen turned on (CEC)"
  else
    if xset dpms force on; then
      xset s off
      xset s noblank
      xset -dpms
      echo "Screen turned on (DPMS)"
    else
      echo "Unable to turn screen on"
      exit 1
    fi
  fi
elif [ "${1}" == "off" ]; then
  if echo "standby 0" | cec-client -s -d 1 >/dev/null; then
    echo "Screen turned off (CEC)"
  else
    if xset dpms force off; then
      echo "Screen turned off (DPMS)"
    else
      echo "Unable to turn screen off"
    fi
  fi
else
  echo "Error: Unknown command"
  exit 1
fi
