#!/bin/bash

videoFolder="$HOME/records"
ffmpegPath="/usr/bin/ffmpeg"
rtspUrl="rtsp://192.168.7.7/h265/ch1/main/av_stream"

mkdir -p "$videoFolder"

trap 'echo "Stopping..."; exit 0' SIGINT SIGTERM

while true; do
    date=$(date +"%Y-%m-%d_%H-%M-%S")
    fileName="$videoFolder/record-$date.mkv"
    now=$(date +%s)
    nextMidnight=$(date -d "tomorrow 00:00:00" +%s)
    remainingTime=$((nextMidnight - now))

    TZ='Europe/Moscow' "$ffmpegPath" -rtsp_transport tcp -t "$remainingTime" -i "$rtspUrl" \
        -vf "scale=480:480,drawtext=fontfile=/usr/share/fonts/truetype/msttcorefonts/segoeui.ttf:text='%{localtime}':x=10:y=10:fontsize=24:fontcolor=white:borderw=2:bordercolor=black" \
        -vcodec libx264 -preset slower -crf 28 -b:v 1000k -g 50 -bf 2 -an -vsync vfr -loglevel error "$fileName"


    if [ $? -ne 0 ]; then
        echo "ffmpeg terminated, exiting loop."
        break
    fi
done

