#!/bin/bash

SYS_CONF="/etc/motioneye.conf"
BOOT_CONF="/boot/motioneye.conf"
CONF="/data/etc/motioneye.conf"
MOTION_CONF="/data/etc/motion.conf"
WATCH_CONF="/data/etc/watch.conf"

MEYEWATCH_TIMEOUT=120
MEYEWATCH_DISABLE="false"
DEV_V4L_BY_ID="/dev/v4l/by-id/"
MEDIA_DIR="/data/output"

test -n "${OS_VERSION}" || source /etc/init.d/base

prepare_conf ${CONF} ${SYS_CONF} ${BOOT_CONF}

test -f "${CONF}" || exit 0

test -r ${WATCH_CONF} && source ${WATCH_CONF}


opts=$(cat "${CONF}" | while read line; do echo "--${line}"; done)
port=$(echo "${opts}" | grep -oE 'port [[:digit:]]+' | cut -d ' ' -f 2)

responsive() {
    curl -m 2 --head http://127.0.0.1:${port} &>/dev/null && return 0 || return 1
}

watch() {
    count=0
    while true; do
        sleep 5
        if responsive; then
            count=0
        else
            if [ ${count} -lt ${MEYEWATCH_TIMEOUT} ]; then
                count=$((${count} + 5))
            else
                logger -t motioneye -s "not responding for ${MEYEWATCH_TIMEOUT} seconds, rebooting"
                reboot
            fi
        fi
    done
}

find_persistent_device() {
    device=$1

    if ! [ -d ${DEV_V4L_BY_ID} ]; then
        echo ${device}
        return
    fi

    for p in ${DEV_V4L_BY_ID}/*; do
        if [ $(realpath "${p}") == ${device} ]; then
            echo ${p} | sed 's#//*#/#g'
            return
        fi
    done
    
    echo ${device}
}

add_mmal_cameras() {
    vcgencmd=$(which vcgencmd)
    if [ -z "${vcgencmd}" ]; then
        return 1
    fi
    
    camera=$(${vcgencmd} get_camera 2>/dev/null)
    if [ "${camera}" != "supported=1 detected=1" ]; then
        return 1
    fi
    
    output_dir="/data/output/camera1/"
    loc="/config/add/?_username=admin"
    device="vc.ril.camera"
    body="{\"path\": \"${device}\", \"proto\": \"mmal\"}"
    signature=$(echo -n "POST:${loc}:${body}:" | sha1sum | cut -d ' ' -f 1)

    curl -s -m 60 --data "${body}" "http://127.0.0.1:${port}${loc}&_signature=${signature}" > /dev/null
    
    return 0
}

add_v4l2_cameras() {
    index=1
    for device in $(ls /dev/video? 2>/dev/null); do
        # filter out devices that don't look like cameras
        if ! v4l2-ctl -d ${device} --list-formats-ext 2>/dev/null | grep -oE '[[:digit:]]+x[[:digit:]]+' &>/dev/null; then
            continue
        fi
        output_dir="/data/output/camera${index}/"
        loc="/config/add/?_username=admin"
        device=$(find_persistent_device ${device})
        body="{\"path\": \"${device}\", \"proto\": \"v4l2\"}"
        signature=$(echo -n "POST:${loc}:${body}:" | sha1sum | cut -d ' ' -f 1)

        curl -s -m 60 --data "${body}" "http://127.0.0.1:${port}${loc}&_signature=${signature}" > /dev/null
        index=$((${index} + 1))
    done
    
    if [ ${index} -gt 1 ]; then
        return 0
    else
        return 1
    fi
}

start() {
    msg_begin "Starting motioneye"

    mkdir -p ${MEDIA_DIR}
    meyectl startserver -b -c ${CONF} -l

    count=0
    while true; do
        sleep 1

        if responsive; then
            break
        fi

        if [ ${count} -gt ${MEYEWATCH_TIMEOUT} ]; then
            msg_fail
            test "${MEYEWATCH_DISABLE}" == "false" && reboot
            return 1
        fi

        count=$((${count} + 1))
    done

    # add connected camera(s) with default settings
    if responsive && ! [ -f ${MOTION_CONF} ]; then
        add_mmal_cameras || add_v4l2_cameras
        sync
    fi

    if [ "${MEYEWATCH_DISABLE}" == "false" ]; then
        watch &
    fi

    msg_done
}

stop() {
    msg_begin "Stopping motioneye"
    meyectl stopserver -c ${CONF} &>/dev/null
    test $? == 0 && msg_done || msg_fail
    ps | grep motioneye | grep -v $$ | grep -v grep | tr -s ' ' | sed -e 's/^\s//' | cut -d ' ' -f 1 | xargs -r kill
}

case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        stop
        start
        ;;

    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?

