#!/usr/bin/env bash

# Log file for debugging
LogFile=/tmp/gif-record.log
exec 2>>$LogFile

# If an instance of wf-recorder is running under this user kill it with SIGINT and exit
pkill --euid "$USER" --signal SIGINT wf-recorder && notify-send "GIF Recording" "Recording stopped, processing..." && exit

# Define paths
DefaultSaveDir=$HOME'/Videos'
TmpPathPrefix='/tmp/gif-record'
TmpRecordPath=$TmpPathPrefix'-cap.mp4'
TmpPalettePath=$TmpPathPrefix'-palette.png'

# Trap for cleanup on exit
OnExit() {
	[[ -f $TmpRecordPath ]] && rm -f "$TmpRecordPath"
	[[ -f $TmpPalettePath ]] && rm -f "$TmpPalettePath"
}
trap OnExit EXIT

# Set umask so tmp files are only acessible to the user
umask 177

# Get selection and honor escape key
Coords=$(slurp) || exit

notify-send "GIF Recording" "Recording started. Press $mod+Shift+G to stop."

# Capture video using slup for screen area
# timeout and exit after 10 minutes as user has almost certainly forgotten it's running
timeout 600 wf-recorder -g "$Coords" -f "$TmpRecordPath" || { notify-send "GIF Recording" "Recording failed"; exit; }

# Get the filename from the user and honor cancel
SavePath=$( zenity \
	--file-selection \
	--save \
	--confirm-overwrite \
	--file-filter=*.gif \
	--filename="$DefaultSaveDir"'/.gif' \
) || exit

# Append .gif to the SavePath if it's missing
[[ $SavePath =~ \.gif$ ]] || SavePath+='.gif'

# Produce a pallete from the video file
ffmpeg -i "$TmpRecordPath" -filter_complex "palettegen=stats_mode=full" "$TmpPalettePath" -y || { notify-send "GIF Recording" "Palette generation failed"; exit; }

# Return umask to default
umask 022

# Use pallete to produce a gif from the video file
ffmpeg -i "$TmpRecordPath" -i "$TmpPalettePath" -filter_complex "paletteuse=dither=sierra2_4a" "$SavePath" -y || { notify-send "GIF Recording" "GIF conversion failed"; exit; }

notify-send "GIF Recording" "GIF saved to $SavePath"
