#!/bin/sh
# USB Camera Service
# Credit: destinal & Guilouz

case "$1" in
  start)
    echo "Starting USB Camera..."
    V4L_DEVS=$(v4l2-ctl --list-devices | grep -A1 usb | sed 's/^[[:space:]]*//g' | grep '^/dev')
    CREALITY_CAMS=$(v4l2-ctl --list-devices | grep -E 'CREALITY|CCX2F3298' | wc -l)
    if [ "x$V4L_DEVS" = "x" -o $CREALITY_CAMS -gt 0 ]; then
      echo "Error: No third party camera found or you use a Creality camera!"
      exit 1
    fi
    PORT=8080
    for V4L_DEV in $V4L_DEVS; do
      /opt/bin/mjpg_streamer -b -i "/opt/lib/mjpg-streamer/input_uvc.so -d $V4L_DEV -r 1280x720 -f 15" -o "/opt/lib/mjpg-streamer/output_http.so -p $PORT"
      PORT=`expr $PORT + 1` 
    done
    ;;
  stop)
    echo "Stopping USB Camera..."
    killall -q mjpg_streamer && killall -q cam_app && killall -q cx_ai_middleware
    ;;
  restart|reload)
    "$0" stop
    sleep 1
    "$0" start
    ;;
  *)
    echo "Usage: /etc/init.d/S50usb_camera {start|stop|restart}"
    exit 1
esac

exit $?
