#!/bin/sh

export cafile=/home/tc/etc/cert/p2p_cacert.pem
export certfile=/home/tc/etc/cert/p2p_servcert.pem
export keyfile=/home/tc/etc/cert/p2p_servkey.pem

max_nodes=500
max_seeds=2000

prog=tc-delivery-core-tracker
exec=/home/tc/bin/$prog
lockfile=/var/lock/subsys/$prog
pidfile=/var/run/$prog.pid
logfile=/var/log/$prog-`date +%Y%m%d%H%M%S`.log

catpidfile=/var/run/$prog-cat.pid

fakepipe=/var/run/$prog-f.fifo
ctrlpipe=/var/run/$prog-c.fifo

check() {
  # Check that we're a privileged user
  [ `id -u` = 0 ] || exit 4

  # Check if prog is executable
  [ -x $exec ] || exit 5
}

start ()
{
  check

  echo -n $"Starting $prog: "

  rm -f $fakepipe $ctrlpipe
  mkfifo $fakepipe $ctrlpipe

  cat $fakepipe >$ctrlpipe &
  echo $! >$catpidfile

  $exec $max_nodes $max_seeds <$ctrlpipe >$logfile 2>&1 &
  RETVAL=$?
  echo $! >$pidfile

  [ $RETVAL -eq 0 ] && touch $lockfile
  echo $RETVAL

  return $RETVAL
}

stop ()
{
  check

  echo -n $"Stopping $prog: "

  pid=`cat $catpidfile`
  kill $pid
  RETVAL=$?

  rm -f $fakepipe $ctrlpipe

  [ $RETVAL -eq 0 ] && rm -f $lockfile
  echo OK
}

restart()
{
  stop
  start
}

full ()
{
  ex -c 'g/^.*\(\<[0-9]\+\)\/.*$/ya|pu|s::readlink /proc/\1/exe:|.!sh' -c 'g/^\//-ya|pu|-2s/^\(.*\<[0-9]\+\)\/[^[:space:]]*\(.*\)$/\1/|+2s//\2/|-2j!3' -c%p -c 'q!' /dev/stdin
}

status ()
{
#  ncat -v -w 1 --send-only 127.0.0.1 4620 </dev/null
  netstat -nlp | full | grep $prog
  RETVAL=$?
  echo "status=$RETVAL"
  return $RETVAL
}


case $1 in
  start)
    status
    if [ $? -ne 0 ] ; then
      echo "not running, execute it..."
      start
    fi
  ;;

  stop)
    stop
  ;;

  restart)
    restart
  ;;

  status)
    status
  ;;

  *)
    echo $"Usage: $prog {start|stop|restart}"
    RETVAL=2
  ;;
esac

exit $RETVAL

