#!/bin/sh

# Set the custom cache directory for Whisper models
export XDG_CACHE_HOME="/backup/whisper"

# Create the cache directory if it does not exist
mkdir -p "$XDG_CACHE_HOME"

# Iterate through all MP4 files in the current directory and subdirectories
find . -type f -name "*.mp4" | while read -r file; do
    # Extract the directory and file name without the .mp4 extension
    dir=$(dirname "$file")
    filename=$(basename "$file" .mp4)
    srt_file="$dir/$filename.srt"

    # Check if the corresponding SRT file exists
    if [ ! -f "$srt_file" ]; then
        # Run Whisper to generate SRT subtitles with English as the source language
        echo "Generating subtitles for: $file"
        whisper "$file" --model medium --output_format srt --task transcribe --language en --output_dir "$dir"
        
        # Rename the generated subtitle file to match the required format
        if [ -f "$dir/$filename_en.srt" ]; then
            mv "$dir/$filename_en.srt" "$srt_file"
        else
            echo "Warning: Expected $dir/$filename_en.srt not found."
        fi
    else
        echo "Subtitle already exists for: $file"
    fi
done

echo "Process completed!"
