#!/bin/sh

###############################################################################
#
# /etc/init.d/freg - System control script for the file registration daemon.
# Also accessed via a symbolic link named /usr/local/sbin/rcfregd.
#
# Copyright (c) 2006, all rights reserved
# License- GPL
# Author-  Jeremy P Thien, David W. Glover
# Company- Adtec Digital, Inc.
# Date-    2006-08-07
#
###############################################################################

readonly DAEMON="/usr/local/sbin/fregd"
readonly PIDFILE="/var/run/fregd.pid"
readonly START_OPTIONS="-d -p $PIDFILE"
readonly DB_FILE=freg.db

# Indicate whether reloads are supported via signals (usually SIGHUP (1)).
# If so, define RELOAD_SIGNAL to the signal. If not, comment out.
#RELOAD_SIGNAL="1"

# Include the common script for all service scripts.
source /etc/init.d/rcservices

export LD_LIBRARY_PATH=/usr/local/lib

#------------------------------------------------------------------------------
# Start the service.
do_start ()
{
  # special handing for potentially driveless systems.
  if [ "${PRODUCT}" != "edje-5110" ]; then
    echo -n "Starting $DAEMON daemon "  
    $DAEMON $START_OPTIONS
    case $? in
      0) RESULT=$SUCCESS;;             # Started OK
      1) RESULT=$PROGRAM_IS_RUNNING;;  # Already running
      *) RESULT=$FAILED;;              # Trouble
    esac
    sleep 2  # give the above processes time to create db
    # do cleanup
    fregd -c > /dev/null 2>&1 &   # not sure if we chould background here.  
  fi

  # check all items
  set -- `echo $MEDIAPATH | (IFS=: ; while read dir recurse; do echo $dir $recurse; done)`
  for ITEM in $@; do
    DIR=${ITEM%%,*}
    RECURSE=${ITEM#*,}
    if [ "$RECURSE"="recurse" ]; then
      $DAEMON -f $DIR > /dev/null 2>&1 &
    elif [ "$RECURSE"="norecurse" ]; then
      find $DIR -type f -prune -name ".*" -o -exec fregd -f {} \; > /dev/null 2>&1 &
    fi
  done
  print_result
  return $RESULT
}

#------------------------------------------------------------------------------
# Stop the service.
do_stop ()
{
  echo -n "Stopping $DAEMON daemon "
  start-stop-daemon --quiet --stop --pidfile $PIDFILE --exec $DAEMON
  case $? in
    0) RESULT=$SUCCESS;;              # Stopped OK
    1) RESULT=$PROGRAM_NOT_RUNNING;;  # No process running
    *) RESULT=$FAILED;;               # Trouble
  esac
  print_result
  return $RESULT
}

# refresh the freg database
do_reset ()
{
  do_stop
  if [ -n "$METAPATH" ]; then
  	/bin/rm -f "$METAPATH/$DB_FILE"
  fi
  do_start
}

# restart freg
do_restart ()
{
  do_stop
  do_start
}


# Do the service.
dispatch_service $1
