#!/bin/bash

#: mb-screenrec - very simple screen recorder
CNF_FILE="$HOME"/.config/mabox/mb-screenrec.conf
. "$CNF_FILE"

DATE=$(date +%Y%m%d_%H-%M-%S)
FRAMERATE=${framerate:-30}
EXT=${container:-webm}
AUDIO=${record_audio:-no}
SCREEN_SIZE=$(xdpyinfo | awk '/^ +dimensions/ {print $2}')
# Alternative: xrandr | grep 'current' | head -n1 | cut -d',' -f2 | tr -d '[:blank:],current'
RECDIR="$(xdg-user-dir VIDEOS)/Recordings"

mkdir -p $RECDIR

if [ "$AUDIO" == "yes" ];then
AUDIOCMD="-f pulse -ac 2 -i default"
else
AUDIOCMD=""
fi

show_stop_icon () {
    case "$LANG" in 
        pl*) STOP_INFO="Zatrzymaj nagrywanie";;
        *) STOP_INFO="Click to stop recording";;
    esac
    yad --notification --image media-playback-stop --text "${STOP_INFO}"
    kill $FFMPEG_PID
    wait $FFMPEG_PID
    
    xdg-open $RECDIR 
}

rec_full () {
    ffmpeg -f x11grab \
    -video_size $SCREEN_SIZE \
    -framerate $FRAMERATE \
    -i :0.0+0,0 ${AUDIOCMD} \
    ${RECDIR}/rec_${DATE}.${EXT} &
    FFMPEG_PID=$!
    
    show_stop_icon
    }


get_area () {
    read X Y W H <<<"$(slop -l -b 3 --color=0.3,0.4,0.6,0.4 -f '%x %y %w %h')"
}
sel_cancelled () {
    notify-send.sh -i mbcc "Error" "Selection was cancelled by keystroke or right-click."
}

rec_area () {
    get_area
    if [ "$X" != "" ];then
    ffmpeg -f x11grab \
    -video_size ${W}x${H} \
    -framerate $FRAMERATE \
    -i :0.0+${X},${Y} ${AUDIOCMD} \
    ${RECDIR}/rec_${DATE}.${EXT} &
    FFMPEG_PID=$!
    
    show_stop_icon
    else
    sel_cancelled
    fi
}




case "$1" in
    -f|--fullscreen) rec_full;;
    -a|--area) rec_area;;
    *) ;;
esac