#!/bin/bash

DELAY=5

function ShowFile() {
    f=${2#file:}
    if [ "${2:0:5}" == "file:" -a ! -r ${f} ]; then
      return
    fi
    DISPLAY=:0 xset s activate
    DISPLAY=:0 xdg-open ${f} >/dev/null 2>/dev/null &
    PID=$!
    WID=""
    i=0
    while [ "${i}" -lt 100 -a -z "${WID}" ]; do
      if [ "${2:0:5}" == "file:" -a ! -r ${f} ]; then
        break
      fi
      i=$((${i}+1))
      CPID=""
      j=0
      while [ "${j}" -lt 100 -a -z "${CPID}" ]; do
        if [ "${2:0:5}" == "file:" -a ! -r ${f} ]; then
          break
        fi
        j=$((${j}+1))
        CPID=$(pgrep -P ${PID} | tail -n 1)
      done
      WID=$(DISPLAY=:0 wmctrl -l -p | grep "\s${CPID}\s")
      WID=${WID%% *}
    done
    if [ -n "${WID}" ]; then
      DISPLAY=:0 wmctrl -i -b add,fullscreen -r ${WID}
      sleep 1
      DISPLAY=:0 xset s reset
      if [ ${1} == "0" ]; then
        while [ $(pgrep -P ${PID} | tail -n 1) == ${CPID} ]; do
          sleep 0.5
        done
      else
        sleep ${1}
      fi
      DISPLAY=:0 xset s activate
      DISPLAY=:0 wmctrl -i -c ${WID}
    fi
    DISPLAY=:0 xset s reset
}

function PlayPls() {
  exec 3<${1}
  while read -u 3 -r pl; do
    d=${pl%%;*}
    f=${pl##*;}
    if [ "${f:0:5}" == "file:" ]; then
      ShowFile ${d} file:${1%/*}/${f:5}
    else
      ShowFile ${d} ${f}
    fi
  done
  exec 3<&-
}

while /bin/true; do
  e=0
  for m in $(ls -1d /media/usb?); do
    if [ -s ${m}/playlist.txt ]; then
      e=1
      PlayPls ${m}/playlist.txt
    elif [ ! -e ${m}/playlist.txt ]; then
      fl=$(find /media/usb? -type f)
      for f in ${fl}; do
        e=1
        ShowFile $DELAY file:${f}
      done
    fi
  done
  if [ "$e" == "0" ]; then
    if [ -s /var/www/html/pictur/upload/playlist.txt ]; then
      e=1
      PlayPls /var/www/html/pictur/upload/playlist.txt
    elif [ ! -e /var/www/html/pictur/upload/playlist.txt ]; then
      fl=$(find /var/www/html/pictur/upload -type f)
      for f in ${fl}; do
        e=1
        ShowFile $DELAY file:${f}
      done
    fi
  fi
  if [ "$e" == "0" ]; then
    sleep 10
  fi
done
