#!/bin/bash

################################################################################
#      Copyright (C) 2009-2010 OpenELEC.tv
#      http://www.openelec.tv
#
#  Boblightd addon maintained by Adam Boeglin: adamrb@gmail.com
#
#  This Program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2, or (at your option)
#  any later version.
#
#  This Program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with OpenELEC.tv; see the file COPYING.  If not, write to
#  the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110, USA.
#  http://www.gnu.org/copyleft/gpl.html
################################################################################

. /etc/profile

ADDON_DIR="$HOME/.xbmc/addons/service.multimedia.boblightd"
ADDON_HOME="$HOME/.xbmc/userdata/addon_data/service.multimedia.boblightd"

mkdir -p $ADDON_HOME

LOG_FILE="$ADDON_HOME/service.log"

# Boblight config file created by user
BOBLIGHT_CONFIG="$ADDON_HOME/boblight.conf"

# Flag file to start boblight-x11 daemon
BOBLIGHT_X11="$ADDON_HOME/boblight.X11"

LOCKDIR="/var/lock/"
LOCKFILE="boblightd.disabled"

export LD_LIBRARY_PATH="$ADDON_DIR/lib:$LD_LIBRARY_PATH"

cp -R $ADDON_DIR/config/*.sample $ADDON_HOME > $LOG_FILE 2>&1

if [ -f "$LOCKDIR/$LOCKFILE" ] ; then
  rm -rf "$LOCKDIR/$LOCKFILE"
fi

if [ -f "$BOBLIGHT_CONFIG" ] ; then
  if [ ! "$(pidof boblightd)" ]; then
    while [ true ] ; do
      if [ -f "$LOCKDIR/$LOCKFILE" ] ; then
        break
      fi
      # Make sure the xserver has started up
      wait_for_xorg
      # Start the boblight daemon
      boblightd -c $BOBLIGHT_CONFIG >> $LOG_FILE 2>&1
    done &
  fi

  if [ -e $BOBLIGHT_X11 ]; then
    if [ ! "$(pidof boblight-X11)" ]; then
      while [ true ] ; do
        if [ -f "$LOCKDIR/$LOCKFILE" ] ; then
          break
        fi
        # Make sure the xserver has started up
        wait_for_xorg
        # Start the boblight daemon
        boblight-X11 >> $LOG_FILE 2>&1
      done &
    fi
  fi
fi
