#!/bin/bash

function checkdirectory {
    if [ ! -d "$1" ]; then
        mkdir $1
        if [ $? -ne 0 ]; then
            echo "Can't create directory $1"
            exit 1
        fi
    fi
}

function checkfreespace {
    avail=$(df --output=avail -B 1 "$1" | tail -n 1)
    if [ "$avail" -lt "$FREESPACELIMIT" ]; then
        echo "Too little free space left"
        exit 1
    fi

}

# ~5Gb
FREESPACELIMIT=5000000000
avail1=$(df --output=avail -B 1 /videostorage | tail -n 1 )

if [ "$avail1" -lt "$FREESPACELIMIT" ]; then
    STORAGE=/home/smartix/videostorage/
    if [ ! -d "/home/smartix/videostorage" ]; then
        mkdir /home/smartix/videostorage/
    fi
else
    STORAGE=/videostorage
fi

STORAGE_SCREEN=$STORAGE/screen
DIR=$(date +%Y-%m-%d)
PREFIX=$(date +%H%M%S)

RESOLUTION="1024x768"
resolution=$(xrandr | grep -v "disconnected" | awk '/connected/{print $3}' | cut -d '+' -f1)
if [[ ${resolution} == "primary" ]]; then
    resolution=$(xrandr | grep -v "disconnected" | awk '/connected/{print $4}' | cut -d '+' -f1)
fi
OUTCODEC="h264"
FRAMERATE="15"

checkdirectory $STORAGE
checkfreespace $STORAGE
checkdirectory $STORAGE/$DIR

checkdirectory $STORAGE_SCREEN
checkfreespace $STORAGE_SCREEN
checkdirectory $STORAGE_SCREEN/$DIR


for dev in `ls /dev/video* 2> /dev/null | sort -n`; do
    name=${dev:5}
    ffmpeg -y -f v4l2 -framerate $FRAMERATE -video_size $RESOLUTION -i $dev -c:v $OUTCODEC -preset faster -strftime 1  $STORAGE/$DIR/$PREFIX-$name.mp4 > /dev/null 2> /dev/null &
done

if [ -f "/home/smartix/machine/conf/webcams.list" ]; then
    WLIST=/home/smartix/machine/conf/webcams.list
else
    WLIST=/home/smartix/postamat/conf/webcams.list
fi


if [[ -f "$WLIST" ]]; then
    i=0
    for dev in `cat $WLIST | grep -v "^x11grab.*$"`; do
        [  -z "$line" ] && ffmpeg -y -i $dev -c:v $OUTCODEC  -framerate $FRAMERATE -video_size $RESOLUTION  -c:v $OUTCODEC -preset faster -strftime 1  $STORAGE/$DIR/$PREFIX-ip$i.mp4 > /dev/null 2> /dev/null &
        i=$((i+1))
    done

    if [[ -n `grep "^x11grab.*$" $WLIST` ]]; then
        key-mon --noshift --noctrl --noalt --scale=0.01 --visible-click-timeout=0.066 --visible_click &
        ffmpeg -f x11grab  -y -rtbufsize 100M -s $resolution -i :0.0 -framerate 30 -probesize 10M -draw_mouse 1 -c:v libx264 -r 30 -preset ultrafast -tune zerolatency -crf 35 -pix_fmt yuv420p  $STORAGE_SCREEN/$DIR/$PREFIX-screen.mp4

    fi
fi



