#!/bin/sh

# Main infotv script.

set -eu

run_idid()
{
  # Hide the mouse cursor except when moving
  unclutter -idle 0.1 -root &

  # Start idid and keep it running
  while true; do
    # idid does something funny with windows sometimes and minimizes itself
    # after starting, failing to come up. add a safeguard to make sure it won't
    # stay running minimized and leaving the screen empty oh so blue
    sleep 20 && wmctrl -i -a `wmctrl -l | awk '{print $1;}'` &

    logger -p local0.info -t infotv 'starting up idid'

    # exit idid if it reports errors in loading URLs
    expect -c '
      set timeout -1
      spawn idid
      expect {
        {Failed to load URL: https://idid2.fi/player/pwa?electron with error: ERR_INTERNET_DISCONNECTED} { exit 1 }
        {Failed to load URL: https://idid2.fi/player/pwa?electron with error: ERR_NAME_NOT_RESOLVED}     { exit 1 }
        eof { exit 0 }
      }
    ' || true
    logger -p local0.err -t infotv \
           'The idid process has exited or crashed, restarting it...'
    sleep 5
  done
}

# Start mutter and keep it running
(
  while true; do
    mutter || true
    logger -p local0.err -t infotv \
           'mutter has exited or crashed, restarting it...'
    sleep 5
  done
) &

# Disable screen blanking and power saving features
xset s 0 0
xset s off
xset s noblank
xset dpms 0 0 0
xset -dpms

# Run the specified software
case "$(puavo-conf puavo.infotv.software)" in
  idid)
    run_idid
    break
    ;;
  *)
    while true; do
      logger -p local0.err -t infotv \
             'Invalid/missing software specified in puavo.infotv.software'
      sleep 300
    done
    break
    ;;
esac

# We should never get here...
logger -p local0.err -t infotv \
       'The info-tv-session script is exiting! This should not happen!'
exit 1
