#!/bin/bash

# adjust these :

if [ -e "/dev/video0" ]; then
    INPUT_PLUGIN="input_uvc.so";
    #DEVICE="-d /dev/video0";
    #FRAMES="-f 10";
    #RESOLUTION="-r 1280x720";
else
    INPUT_PLUGIN= "input_raspicam.so";
    #FRAMES="-f 10";
    #RESOLUTION="-r 1280x720";
fi

OUTPUT_PLUGIN="output_http.so";
#PORT="-p 8085";
#CREDENTIALS="-c user_name:user_password"

# the following are defaults and should not need to be changed
EXEC="/usr/local/bin/mjpg_streamer"
WEB_DIR="-w /usr/local/share/mjpg-streamer/www"
LIB_DIR="/usr/local/lib/mjpg-streamer/"

# mjgp_streamer often does not start on first try. Why ?
start_streamer(){
    for i in {1..5}    # try up to 5 times
    do
        # echo ${EXEC} -b -i "${LIB_DIR}${INPUT_PLUGIN} -n ${DEVICE} ${FRAMES} ${RESOLUTION}" -o "${LIB_DIR}${OUTPUT_PLUGIN} ${PORT} ${WEB_DIR} ${CREDENTIALS}"
        ${EXEC} -b -i "${LIB_DIR}${INPUT_PLUGIN} -n ${DEVICE} ${FRAMES} ${RESOLUTION}" -o "${LIB_DIR}${OUTPUT_PLUGIN} ${PORT} ${WEB_DIR} ${CREDENTIALS}"  > /dev/null 2>&1
        sleep $((1+i)) # waiting progressively longer
        if pgrep mjpg_streamer > /dev/null
        then
            echo "mjpg_streamer started"
            return
        fi  
    done
    echo "could not start mjpg_streamer"
}


# Carry out specific functions when asked to by the system
case "$1" in
        start)
                if pgrep mjpg_streamer > /dev/null
                then
                    echo "mjpg_streamer already running"
                else
                    start_streamer
                fi
                ;;
        stop)
                if pgrep mjpg_streamer > /dev/null
                then
                    killall mjpg_streamer
                    echo "mjpg_streamer stopped"
                else
                    echo "mjpg_streamer is not running"
                fi
                ;;
        restart)
                if pgrep mjpg_streamer > /dev/null
                then
                    killall mjpg_streamer
                    echo "mjpg_streamer stopped"
                else
                    echo "mjpg_streamer is not running"
                fi    
                start_streamer
                ;;
        status)
                pid=`ps -A | grep mjpg_streamer | grep -v "grep" | grep -v mjpg_streamer. | awk '{print $1}' | head -n 1`
                if [ -n "$pid" ];
                then
                        echo "mjpg_streamer is running with pid ${pid}"
                        echo "mjpg_streamer was started with the following command line"
                        cat /proc/${pid}/cmdline ; echo ""
                else
                        echo "mjpg_streamer is not running"
                fi
                ;;
        *)
                echo "Usage: $0 {start|stop|restart|status}"
                exit 1
                ;;
esac

exit 0  
