#!/usr/bin/env bash
#
# DESCRIPTION:
#   Simple recording tool and wrapper around giph (ffmpeg).
#
# NOTE:
#
#   $1 : <gif>, <mkv>  : Type.
#   $2 : <size, <full> : Scope.
#
# DEPENDENCIES:
#   ffmpeg
#   notify-send.sh
#   pkill (coreutils)
#
# 2021-2022 : João F. © BeyondMagic <koetemagie@gmail.com>
# 2024-     : Ismo Vuorinen <https://github.com/ivuorinen>

# Enable verbosity with VERBOSE=1
VERBOSE="${VERBOSE:-0}"

# Variables
frame_rate=30
name='camera'
path_recordings="$HOME/.cache/recording"
replace_id="$HOME/.cache/recording.id"

# Function to print messages if VERBOSE is enabled
# $1 - message (string)
msg()
{
  [ "$VERBOSE" -eq 1 ] && echo "$1"
}

# Notify function
notify()
{
  notify-call --replace-file "$replace_id" "$@"
}

# Stop recording function
stop()
{
  giph --stop
  eww update record_menu=false
}

# Function to check for required applications
check_dependencies()
{
  for cmd in ffmpeg notify-send.sh pkill eww giph slop; do
    if ! command -v "$cmd" &> /dev/null; then
      echo "Required command '$cmd' not found. Please install it before running this script."
      exit 1
    fi
  done
}

# Function to kill previous giph process if running
kill_previous_process()
{
  if pgrep -f 'bash.+giph' > /dev/null; then
    next=$(notify -d 'echo yes' "$name" 'Do you want to stop current recording?')
    [ "$next" = 'yes' ] && stop
    exit 0
  fi
}

# Function to check if the current file type is supported
check_file_type()
{
  case "$1" in
    'mkv' | 'gif' | 'webm' | 'mp4') ;;
    *)
      format=$(
        notify \
          -o 'echo mkv:MKV' \
          -o 'echo webm:WEBM' \
          -o 'echo mp4:MP4' \
          -o 'echo gif:GIF' \
          "$name" \
          'What is the filetype you want to record?'
      )
      exec "$0" "$format" "$2"
      ;;
  esac
}

# Function to determine recording scope
determine_scope()
{
  if [ "$2" = 'fullscreen' ]; then
    geometry=$(xrandr | awk '/ primary/{print $4}')
  elif [ "$2" = 'set' ]; then
    geometry=$(slop -f "%wx%h+%x+%y")
  else
    next=$(notify -o 'echo fullscreen:The whole_screen!' -o 'echo set:Let me set.' "$name" 'How exactly do you want to record?')
    exec "$0" "$1" "$next"
  fi
}

# Function to start recording
start_recording()
{
  mkdir -p "$path_recordings"
  name_file="$path_recordings/$2-$(date +'%a_%b_%d_%H:%M:%S').$1"

  eww update record_menu=true

  giph -g "$geometry" -f "$frame_rate" "$name_file"

  stop

  responder=$(notify -o 'echo open:See file?' -o 'echo none:Hell no' "$name" 'Recording has finished.')

  if [ "$responder" = 'open' ]; then
    nohup gtk-launch "$(xdg-mime query default inode/directory)" "$path_recordings/" > /dev/null 2>&1 &
  fi

  rm -f "$replace_id"
}

main()
{
  check_dependencies
  kill_previous_process "$@"
  check_file_type "$@"
  determine_scope "$@"
  start_recording "$@"
}

main "$@"
