#!/bin/bash

# Originally created by Robin Voetter (https://github.com/Snektron),
# then modified by me (https://github.com/SijmenSchoon).

if [ -f /tmp/screenrecord.pid ]; then
 pkill -P $(cat "/tmp/screenrecord.pid")
 exit 0
fi

read -r x y w h < <(slop -f "%x %y %w %h" -q)
if [ -z "$x" ]; then
    echo "Cancelled"
    exit 0
fi

id=$(notify-send.sh -p -u low "Starting recording in 3 seconds"); sleep 1
notify-send.sh -r "$id" -u low "Starting recording in 2 seconds"; sleep 1
notify-send.sh -r "$id" -u low -t 500 "Starting recording in 1 seconds"; sleep 1

{
    date=$(date '+%Y%M%d-%H%M%S')
    ffmpeg -video_size "$w"x"$h"                   \
           -framerate 30                           \
           -f x11grab                              \
           -i :0.0+"$x","$y"                       \
           -vf "scale=trunc(iw/4)*2:trunc(ih/4)*2" \
           -pix_fmt yuv420p                        \
           "$HOME/Videos/sr-$date.mp4"

    rm /tmp/screenrecord.pid
    notify-send.sh -u low "Stopped recording" "Saved recording to ~/Videos/sr-$date.mp4"
    xclip -sel clip <<< "$HOME/Videos/sr-$date.mp4"
} &

echo "$!" > /tmp/screenrecord.pid