#!/bin/bash

# Check if the user provided a time argument
if [ -z "$1" ]; then
    echo "Usage: sort_extra {time(HH:MM:SS)}"
    exit 1
fi

# Convert the provided time into total seconds
IFS=: read -r hours minutes seconds <<< "$1"
target_time=$((hours * 3600 + minutes * 60 + seconds))

# Create the extra folder if it doesn’t exist
mkdir -p extra

# Iterate through all subdirectories except 'extra'
for dir in */; do
    if [ "$dir" != "extra/" ]; then
        find "$dir" -type f -name "*.mkv" | while read -r file; do
            # Get the duration of the mkv file in seconds
            duration=$(ffprobe -v error -select_streams v:0 -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file")
            duration=${duration%.*}  # Convert float to integer

            # Convert duration to HH:MM:SS format
            hh=$((duration / 3600))
            mm=$(((duration % 3600) / 60))
            ss=$((duration % 60))
            formatted_duration=$(printf "%02d:%02d:%02d" $hh $mm $ss)

            # Check if duration is less than the target time
            if [ "$duration" -lt "$target_time" ]; then
                base_name=$(basename -- "$file")
                target_file="extra/$base_name"
                
                # Ensure the file does not overwrite an existing file
                if [ -e "$target_file" ]; then
                    count=1
                    while [ -e "extra/${count}_$base_name" ]; do
                        ((count++))
                    done
                    target_file="extra/${count}_$base_name"
                fi
                
                mv "$file" "$target_file"
                echo "Moved: $file -> $target_file (Length: $formatted_duration)"
            fi
        done
    fi
done

/home/honney/.bin/tracker.py add filter_extra
