#!/bin/sh
#
# Function that loads the kernel modules and starts the daemon/service
#
do_start()
{
    echo -n "Loading: "
    echo -n "NiRioSrv "
    modprobe NiRioSrv
    echo -n "niusrpriok "
    modprobe niusrpriok
    echo ""
    if [ -d /dev/ni ];
    then
        chmod +x /dev/ni
    fi
    echo "Starting: niusrpriorpc"
    if [ -z $(ps -a | grep -o niusrpriorpc) ]; then
        /usr/local/natinst/niusrp/bin/niusrpriorpc &
    fi
}

#
# Function that stops the daemon/service and unloads the kernel modules
#
do_stop()
{
    echo "Stopping: niusrpriorpc"
    pkill niusrpriorpc
    echo -n "Unloading: "
    echo -n "niusrpriok "
    modprobe -r niusrpriok
    echo -n "NiRioSrv "
    modprobe -r NiRioSrv
    echo ""
}

#
# Function that gets the status of loaded kernel modules and daemon/service
#
get_status()
{
    echo -n "Modules Loaded: "
    echo -n "`lsmod | grep -o "nikal "`"
    echo -n "`lsmod | grep -o "nibds "`"
    echo -n "`lsmod | grep -o "nistreamk "`"
    echo -n "`lsmod | grep -o "NiRioSrv "`"
    echo -n "`lsmod | grep -o "niusrpriok "`"
    echo ""
    echo "Server: "`ps -a | grep -o niusrpriorpc`
}

check_root()
{
    if [ $(id -u) -ne 0 ]
    then
        echo "This script must be run as root." >&2
        exit 1
    fi
}

case "$1" in
  start)
    check_root
    do_start
    ;;
  stop)
    check_root
    do_stop
    ;;
  restart|condrestart)
    check_root
    do_stop
    do_start
    ;;
  status)
    get_status
    ;;
  *)
    echo "Usage: $N {start|stop|restart|condrestart|status}" >&2
    exit 1
    ;;
esac

exit 0
