#!/usr/bin/env bash

## Copyright (C) 2020-2023 Aditya Shakya <adi1090x@gmail.com>
##
## Openbox Pipemenu to Record Screen with slop and ffmpeg

# Variables and functions
MENUS_LIBDIR='/usr/share/debiancraft/openbox/menulib'
if ! . "$MENUS_LIBDIR/debiancraft.cfg" 2> /dev/null; then
	echo "Error: Failed to locate debiancraft.cfg in $MENUS_LIBDIR" >&2
	exit 1
fi

# File
time=`date +%Y-%m-%d-%H-%M-%S`
screen=`xrandr | grep 'current' | head -n1 | cut -d',' -f2 | tr -d '[:blank:],current'`
dir="`xdg-user-dir VIDEOS`/Screenrecorder"
file="Capture_${time}.mp4"

# Directory
if [[ ! -d "$dir" ]]; then
	mkdir -p "$dir"
fi

# notify
notify_user () {
	notify_cmd="dunstify -u low -h string:x-dunst-stack-tag:obscreenrecord -i /usr/share/debiancraft/icons/dunst/video.png"
	if [[ -e "$dir/$file" ]]; then
		${notify_cmd} "Saved in $dir"
	else
		${notify_cmd} "Video Deleted."
	fi
}

# countdown
countdown () {
	for sec in `seq $1 -1 1`; do
		dunstify -t 1000 -h string:x-dunst-stack-tag:screenrecordtimer -i /usr/share/debiancraft/icons/dunst/timer.png "Starting in : $sec"
		sleep 1
	done
}

# capture
rec_screen() {
	countdown '3'
	sleep 1
	if [[ "$1" == "noaudio" ]]; then
		ffmpeg -video_size ${screen} -framerate 25 -f x11grab -i :0.0+0,0 ${dir}/${file}
	else
		ffmpeg -video_size ${screen} -framerate 25 -f x11grab -i :0.0+0,0 -f pulse -ac 2 -i default ${dir}/${file}
	fi
	notify_user
}

rec_area() {
	get_win_data=$(slop -f "%x %y %w %h %g %i") || exit 1
	read -r X Y W H G ID < <(echo $get_win_data)
	
	countdown '3'
	sleep 1
	if [[ "$1" == "noaudio" ]]; then
		ffmpeg -video_size ${W}x${H} -framerate 25 -f x11grab -i :0.0+${X},${Y} ${dir}/${file}
	else
		ffmpeg -video_size ${W}x${H} -framerate 25 -f x11grab -i :0.0+${X},${Y} -f pulse -ac 2 -i default ${dir}/${file}
	fi
	notify_user
}

if [[ "$1" == "--screen" ]]; then
	rec_screen
elif [[ "$1" == "--area" ]]; then
	rec_area
elif [[ "$1" == "--screen-na" ]]; then
	rec_screen noaudio
elif [[ "$1" == "--area-na" ]]; then
	rec_area noaudio
else
    menuStart
		if [[ `pidof ffmpeg` ]]; then
			menuItem 'Stop Screen Recorder' "pkill ffmpeg"
			menuSeparator
		fi
        menuItem 'Record Desktop (With Audio)' "$0 --screen"
        menuItem 'Record Desktop (No Audio)' "$0 --screen-na"
        menuItem 'Record Area (With Audio)' "$0 --area"
        menuItem 'Record Area (No Audio)' "$0 --area-na"
    menuEnd
fi

exit 0
