#!/bin/bash

# mp4-to-fli.sh
# Complete converter: MP4 → Autodesk Animator FLI (320x200)
# Optimized for MS-DOS / 386
# macOS version

set -e

# ====================== CONFIGURATION ======================
FPS=10                    # Frame rate (8-12 recommended for 386)
SPEED=7                   # ppm2fli speed in jiffies (≈10 fps)
OUTPUT_DIR="fli_frames"
LIST_FILE="frames.list"
FFMPEG="/opt/pkg/bin/ffmpeg4" 
# ===========================================================

# --- Check arguments ---
if [ $# -lt 1 ]; then
    echo "Usage: $0 input.mp4 [output_name]"
    echo "Example: $0 video.mp4 myanimation"
    exit 1
fi

INPUT="$1"
BASENAME="${2:-$(basename "$INPUT" | sed 's/\.[^.]*$//')}"
FLI_FILE="${BASENAME}.fli"

echo "=== MP4 → FLI Converter ==="
echo "Input       : $INPUT"
echo "Output FLI  : $FLI_FILE"
echo "FPS         : $FPS"
echo "Speed       : $SPEED jiffies"
echo ""

# --- Check required tools ---
check_tool() {
    if ! command -v "$1" &> /dev/null; then
        echo "Error: '$1' is not installed."
        case "$1" in
            ffmpeg)      echo "  → brew install ffmpeg" ;;
            convert)     echo "  → brew install imagemagick" ;;
            ppm2fli)     echo "  → You need to compile ppm2fli first" ;;
            pngtopnm)    echo "  → brew install netpbm" ;;
        esac
        exit 1
    fi
}

check_tool ffmpeg
check_tool ppm2fli

# Prefer ImageMagick, fall back to netpbm
if command -v convert &> /dev/null; then
    CONVERTER="imagemagick"
elif command -v pngtopnm &> /dev/null; then
    CONVERTER="netpbm"
else
    echo "Error: Need either ImageMagick or netpbm for PNG → PPM conversion."
    echo "  → brew install imagemagick"
    echo "  or"
    echo "  → brew install netpbm"
    exit 1
fi

# --- Clean previous run ---
rm -rf "$OUTPUT_DIR"
rm -f "$LIST_FILE" "$FLI_FILE"
mkdir -p "$OUTPUT_DIR"

# --- Step 1: Extract frames with FFmpeg ---
echo "→ [1/4] Extracting frames with FFmpeg..."
$FFMPEG -y -i "$INPUT" \
  -vf "fps=${FPS},scale=320:200:force_original_aspect_ratio=decrease,pad=320:200:(ow-iw)/2:(oh-ih)/2:black" \
  -pix_fmt rgb24 \
  "${OUTPUT_DIR}/frame_%04d.png" 2>/dev/null

FRAME_COUNT=$(ls -1 "$OUTPUT_DIR"/frame_*.png 2>/dev/null | wc -l | tr -d ' ')
if [ "$FRAME_COUNT" -eq 0 ]; then
    echo "Error: No frames were extracted."
    exit 1
fi
echo "   Extracted $FRAME_COUNT frames"

# --- Step 2: Convert PNG → PPM ---
echo "→ [2/4] Converting PNG → PPM..."

if [ "$CONVERTER" = "imagemagick" ]; then
    for f in "$OUTPUT_DIR"/frame_*.png; do
        /opt/pkg/bin/convert "$f" "${f%.png}.ppm"
    done
else
    for f in "$OUTPUT_DIR"/frame_*.png; do
        pngtopnm "$f" > "${f%.png}.ppm"
    done
fi

# Optional: remove the PNGs to save space
rm -f "$OUTPUT_DIR"/frame_*.png

# --- Step 3: Create list file ---
echo "→ [3/4] Creating frame list..."
ls -1 "$OUTPUT_DIR"/frame_*.ppm | sort > "$LIST_FILE"

# --- Step 4: Generate FLI ---
echo "→ [4/4] Generating FLI file with ppm2fli..."
ppm2fli -O -g 320x200 -s "$SPEED" "$LIST_FILE" "$FLI_FILE"

# --- Cleanup (optional) ---
# Uncomment the next line if you want to delete the intermediate frames
# rm -rf "$OUTPUT_DIR" "$LIST_FILE"

echo ""
echo "✓ Success!"
echo "  Created: $FLI_FILE"
echo "  Frames : $FRAME_COUNT"
echo "  Size   : $(du -h "$FLI_FILE" | cut -f1)"
echo ""
echo "You can now copy $FLI_FILE to your DOS machine / DOSBox."
