#!/bin/bash
# Video Conversion Script for Raspberry Pi Signage Player
# Converts videos to optimal settings: 1080p @ 30fps, H.264 codec

if [ $# -eq 0 ]; then
    echo "Usage: $0 <input_video> [output_video]"
    echo "Example: $0 input.mp4 output.mp4"
    echo ""
    echo "This script converts videos to Raspberry Pi-friendly settings:"
    echo "  - Resolution: Max 1920x1080"
    echo "  - Frame rate: 30 fps"
    echo "  - Codec: H.264"
    echo "  - Bitrate: ~5-8 Mbps"
    exit 1
fi

INPUT_VIDEO="$1"
OUTPUT_VIDEO="${2:-converted_$(basename "$INPUT_VIDEO")}"

if [ ! -f "$INPUT_VIDEO" ]; then
    echo "Error: Input file '$INPUT_VIDEO' not found!"
    exit 1
fi

echo "Converting video for Raspberry Pi playback..."
echo "Input:  $INPUT_VIDEO"
echo "Output: $OUTPUT_VIDEO"
echo ""

# Convert video with optimal settings for Raspberry Pi
ffmpeg -i "$INPUT_VIDEO" \
    -c:v libx264 \
    -preset medium \
    -crf 23 \
    -maxrate 8M \
    -bufsize 12M \
    -vf "scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease,fps=30" \
    -r 30 \
    -c:a aac \
    -b:a 128k \
    -movflags +faststart \
    -y \
    "$OUTPUT_VIDEO"

if [ $? -eq 0 ]; then
    echo ""
    echo "✓ Conversion completed successfully!"
    echo "Original: $(du -h "$INPUT_VIDEO" | cut -f1)"
    echo "Converted: $(du -h "$OUTPUT_VIDEO" | cut -f1)"
    echo ""
    echo "You can now use '$OUTPUT_VIDEO' in your signage player."
else
    echo ""
    echo "✗ Conversion failed! Make sure ffmpeg is installed:"
    echo "  sudo apt-get install ffmpeg"
    exit 1
fi
