#!/bin/sh

record () {
    ## Options
    frameRate=60 # FPS
    audioQuality=10 # Opus Qual - Bad 0 <> 10 Good
    videoQuality=15 # H264 QVal - Lower is better
    recordLocation=~/vids/yt

    [ ! -d "$recordLocation" ] && mkdir "$recordLocation"

    ## Auto-Config - Use the last render device which should be the Intel GPU
    currentRes=$(xdpyinfo | grep dimensions | awk '{print $2}')

    ffmpeg -loglevel 16 -threads 6 -probesize 10M -framerate ${frameRate} -vsync 1 \
        -thread_queue_size 512 -f x11grab -s ${currentRes} -r ${frameRate} -i :0.0 \
        -thread_queue_size 512 -f pulse -ac 2 -channel_layout stereo -i default -c:a libopus -vbr on -compression_level ${audioQuality} \
        -c:v h264_nvenc -qp ${videoQuality} "${recordLocation}/$(date +%y%m%d%H%M%S).mkv" > /tmp/recorder.log &
    printf '%s\n' "$!" > /tmp/recording.pid

    if [ "$?" -ne "0" ]; then
        quick-notify "Recorder" "Failed to start recording"
        quick-notify "Recorder" "Error: $(cat /tmp/recorder.log)"
    else
        touch /tmp/recording.lock
        quick-notify "Recorder" "Started recording"
    fi
}

stop () {
    pid=$(cat /tmp/recording.pid)

    kill $pid

    if [ "$?" -ne "0" ];then
        quick-notify "Recorder" "Failed to stop recording"
    else
        quick-notify "Recorder" "Stopped recording"
    fi

    rm /tmp/recording.pid /tmp/recording.lock /tmp/recorder.log
}

if [ -f "/tmp/recording.lock" ]; then
    stop
else
    record
fi