#!/bin/bash

CONFIG="/opt/pos/etc/config.ini"
MUSIC_FOLDER="/opt/pos/common/music"
PLAYLIST="/opt/pos/common/music/mp3playlist"
PLAYER="mpg123 -v -@ ${PLAYLIST}"
MACHINE_ID=`/opt/pos/common/bin/machine_id`
SELECTED_PLAYLIST="/opt/pos/common/music/selected_playlist.txt"

if [ ! -d "" ]; then
  mkdir -p ${MUSIC_FOLDER}
fi

HAS_MUSIC=`cat $CONFIG | grep MUSIC_PLAY | grep -v grep | grep 1`

if [ "$HAS_MUSIC" != "" ]; then
  /opt/pos/common/bin/music_rebuild_playlist.sh
fi

while [ true ]; do
  HAD_FILES="0"
  PLAY_MUSIC="YES"

  if [ -e "$SELECTED_PLAYLIST" ]; then
    NAME=`cat $SELECTED_PLAYLIST`

    echo "##### $SELECTED_PLAYLIST - $NAME"

    if [ "$NAME" = "--------" ]; then
      HAD_FILES="0"
      PLAY_MUSIC="NO"
    elif [ "$NAME" = "MANUAL" ]; then
      HAD_FILES="0"
      PLAY_MUSIC="YES"
    elif [ "$NAME" = "REMOTE" ]; then
      REMOTE_PLAYLIST=`cat $SELECTED_PLAYLIST`
      HAS_NETWORK=`/opt/pos/common/bin/has_network`

      if [ "$HAS_NETWORK" != "NO" ]; then
        HAD_FILES=`/opt/pos/common/bin/music_sync_playlist.pl $NAME`
        PLAY_MUSIC="YES"
      fi
    fi
  fi

  if [ "$PLAY_MUSIC" = "YES" ]; then
    if [ "$HAD_FILES" = "1" ]; then
      /opt/pos/common/bin/music_rebuild_playlist.sh
    fi

    if [ "$HAS_MUSIC" != "" ]; then
      if [ -s "$PLAYLIST" ]; then
        echo "Will play music"
        ${PLAYER} $@

        SHUFFLE=`cat $CONFIG | grep MUSIC_SHUFFLE | grep -v grep | grep 1`

        if [ "$SHUFFLE" != "" ]; then
          cat $PLAYLIST | /opt/pos/common/bin/music_shuffle_playlist.pl > $PLAYLIST.shuffle
          mv -f $PLAYLIST.shuffle $PLAYLIST
        fi
      else
        echo "playlist is empty..."
      fi

      sleep 10
    else
      sleep 30
    fi
  else
    sleep 30
  fi
done

