#!/bin/bash

# Script to convert all WebM files with alpha to ProRes 4444 MOV files
# Overwrites existing MOV files by default

# Check if directory parameter is provided
if [ $# -eq 0 ]; then
    echo "Usage: sh convert_webm_to_mov.sh <absolute_path_to_directory>"
    echo "Example: sh convert_webm_to_mov.sh /Users/charlesteh/Desktop/mag-group-1/"
    exit 1
fi

# Get the target directory from parameter
target_dir="$1"

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

echo "Converting all WebM files in '$target_dir' to ProRes 4444 MOV..."

# 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

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

# Count total WebM files
webm_count=$(ls *.webm 2>/dev/null | wc -l)

if [ $webm_count -eq 0 ]; then
    echo "No WebM files found in current directory"
    exit 0
fi

echo "Found $webm_count WebM file(s) to convert"

# Counter for progress
count=0

# Loop through all WebM files in current directory
for webm_file in *.webm; do
    # Check if file actually exists (in case glob doesn't match)
    if [ ! -f "$webm_file" ]; then
        continue
    fi

    # Increment counter
    count=$((count + 1))

    # Get filename without extension
    base_name=$(basename "$webm_file" .webm)

    # Output MOV filename
    mov_file="${base_name}.mov"

    echo "[$count/$webm_count] Converting: $webm_file -> $mov_file"

    # Convert with ffmpeg
    # -y: overwrite output files without asking
    # -vcodec libvpx-vp9: Force libvpx decoder (native VP9 decoder doesn't handle alpha)
    # -i: input file
    # -c:v prores_ks: ProRes encoder (much better compression than qtrle)
    # -profile:v 4444: ProRes 4444 profile (supports alpha)
    # -pix_fmt yuva444p10le: Pixel format with alpha channel support
    # -c:a aac: convert audio to AAC (MOV compatible, since Opus isn't supported in MOV)
    ffmpeg -y -vcodec libvpx-vp9 -i "$webm_file" -c:v prores_ks -profile:v 4444 -pix_fmt yuva444p10le -c:a aac "$mov_file"

    # Check if conversion was successful
    if [ $? -eq 0 ]; then
        echo "✓ Successfully converted: $mov_file"
    else
        echo "✗ Failed to convert: $webm_file"
    fi

    echo ""
done

echo "Conversion complete! Processed $count file(s)."
