#!/bin/bash

wf-recorder_check() {
	if pgrep -x "wf-recorder" > /dev/null; then
		pkill -INT -x wf-recorder
		pkill -RTMIN+11 waybar
		exit 0
	fi

	record
}

record() {
	pkill -RTMIN+11 waybar

	screencast_dir="$HOME/Screenrecord"
	mkdir -p "$screencast_dir"

	timestamp=$(date +"%Y-%m-%d-%H-%M-%S")
	screencast_file="$screencast_dir/screencast_$timestamp.mkv"
	webm_file="${screencast_file%.*}.webm"

	# Grabación de región con slurp
	wf-recorder -c h264_vaapi -d /dev/dri/by-path/pci-0000:65:00.0-render -g "$(slurp)" -f "$screencast_file"
	pkill -RTMIN+11 waybar

	# Conversión sin pérdida a webm
	ffmpeg -i "$screencast_file" -c:v libvpx-vp9 -lossless 1 "$webm_file"

	if [ ! -s "$webm_file" ]; then
		notify-send "❌ Error: conversión fallida"
		rm -f "$screencast_file"
		exit 1
	fi

	notify-send "✅ Video postprocesado" "Convirtiendo a WebM completado"

	# Subida a GitLab Snippet
	link=$(~/.local/bin/gitlab-paste "$webm_file" | grep -o 'https://gitlab.com/-/snippets/[^ ]*')

	# Notificación y clipboard
	if [ -n "$link" ]; then
		notify-send "📤 Video subido" "Link copiado al portapapeles"
	else
		notify-send "⚠️ Subida fallida" "No se obtuvo enlace"
	fi

	# Limpieza
	rm -f "$screencast_file"
}

wf-recorder_check

