#!/bin/sh

# TODO :  Add rc.status
#  status not kernel portable?

CFG="/etc/sysconfig/mirror.cfg"
MIRROR_BIN="/usr/local/bin/mirror"
MIRROR_PID="/var/tmp/mirror.lock"
SSD_BIN="/sbin/start-stop-daemon"
USER=adtec

#We really just want the LOCAL_DIR:
test -f $CFG && . $CFG

#JPT Found that wget was not found without path setting provided by profile
. /etc/profile

# make sure adtec owns the CFG file
chown adtec: $CFG

case "$1" in
    start)

        echo "Starting mirror daemon"
        $SSD_BIN --start --exec $MIRROR_BIN --background --pidfile $MIRROR_PID --make-pidfile --chuid $USER -- DAEMON
        ;;
    stop)
        echo "Shutting down mirror daemon"
        /usr/bin/pkill ftpcopy
        $SSD_BIN -K -n mirror -p $MIRROR_PID 
        rm -f $MIRROR_PID
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    status)
        #echo "Checking for mirror daemon: "
        cat $MIRROR_PID | while read ; do
            if [ `ps -e | grep -c $REPLY` ] ; then
                echo -n "mirror is running. PID="
                cat $MIRROR_PID
                fpid=`ps -e | grep -w wget | cut -d" " -f2`
                ftp_pid=`echo $fpid`
                #echo $ftp_pid, $LOCAL_DIR
                echo "Downloading: " 
                (find "/proc/${ftp_pid}/fd/" -lname "${LOCAL_DIR}/*" -printf %l\\n)
                #echo $stmt
                #`echo $stmt`
	    else 
                echo "mirror is stopped."
            fi
        done
        ;;
    halt)
        #not yet implemented.  Instead of kill how about other signal.
        fpid=`echo ps -e | grep -w wget | cut -d" " -f2`
        
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac
