#!/bin/bash

# Script to remove green screen and convert video files to WebM
# Usage: ./greenscreen_to_webm.sh [directory_path]

# Check if ffmpeg is installed
if ! command -v ffmpeg &> /dev/null; then
    echo "Error: ffmpeg is not installed or not in PATH"
    exit 1
fi

# Get target directory (default to current directory)
target_dir="${1:-.}"

# Check if directory exists
if [ ! -d "$target_dir" ]; then
    echo "Error: Directory '$target_dir' does not exist"
    exit 1
fi

# Change to target directory
cd "$target_dir" || {
    echo "Error: Cannot access directory '$target_dir'"
    exit 1
}

# Create webm directory if it doesn't exist
mkdir -p webm

# Counter for processed files
processed=0
failed=0

echo "Converting video files to WebM with green screen removal..."

# Process all common video files in current directory
for video_file in *.mp4 *.mov *.avi *.mkv *.m4v *.MP4 *.MOV *.AVI *.MKV *.M4V; do
    # Check if file actually exists (in case glob doesn't match)
    if [ ! -f "$video_file" ]; then
        continue
    fi

    # Get filename without extension
    base_name=$(basename "$video_file" | sed 's/\.[^.]*$//')

    # Output WebM filename
    webm_file="webm/${base_name}.webm"

    echo "Processing: $video_file -> $webm_file"

    # Convert with green screen removal
    if ffmpeg -i "$video_file" \
              -vf 'colorkey=0x00FF00:similarity=0.1:blend=0.1,despill=green' \
              -c:v libvpx-vp9 \
              -c:a libvorbis \
              -y \
              "$webm_file" \
              -v quiet -stats; then
        echo "✓ Successfully converted: $webm_file"
        ((processed++))
    else
        echo "✗ Failed to convert: $video_file"
        ((failed++))
    fi
    echo ""
done

# Summary
echo "Conversion complete!"
echo "Successfully processed: $processed files"
if [ $failed -gt 0 ]; then
    echo "Failed to process: $failed files"
fi
echo "Output directory: webm/"
