#!/bin/bash

# Usage: ./convert_video.sh <input_file>
# Automatically detects and corrects rotation, and downscales to 1280x720 if needed.

INPUT="$1"

# --- Validate input file ---
if [ -z "$INPUT" ]; then
  echo "Error: No input file specified."
  echo "Usage: $0 <input_file>"
  exit 1
fi

if [ ! -f "$INPUT" ]; then
  echo "Error: File '$INPUT' not found."
  exit 1
fi

# Check extension
EXT="${INPUT##*.}"
if [[ "${EXT,,}" != "mp4" && "${EXT,,}" != "mov" ]]; then
  echo "Error: Input file must be .mp4 or .mov"
  exit 1
fi

# --- Detect rotation using ffprobe or mediainfo ---
ROTATION=0

if command -v ffprobe &> /dev/null; then
  echo "Using ffprobe to detect rotation..."
  ROTATION=$(ffprobe -v error \
    -select_streams v:0 \
    -show_entries stream_tags=rotate \
    -of default=nw=1:nk=1 \
    "$INPUT" 2>/dev/null)
  ROTATION="${ROTATION:-0}"

elif command -v mediainfo &> /dev/null; then
  echo "Using mediainfo to detect rotation..."
  ROTATION=$(mediainfo --Output="Video;%Rotation%" "$INPUT" 2>/dev/null)
  ROTATION="${ROTATION:-0}"

else
  echo "Warning: Neither ffprobe nor mediainfo found. Assuming no rotation."
  ROTATION=0
fi

# Normalize to integer (mediainfo can return values like "90.000")
ROTATION=$(printf "%.0f" "$ROTATION" 2>/dev/null || echo "0")

echo "Detected rotation: ${ROTATION}°"

# --- Map rotation degrees to transpose filter ---
case "$ROTATION" in
  90)
    TRANSPOSE="transpose=1"          # 90° clockwise
    ;;
  180)
    TRANSPOSE="transpose=1,transpose=1"  # 180°
    ;;
  270|-90)
    TRANSPOSE="transpose=2"          # 90° counter-clockwise
    ;;
  *)
    TRANSPOSE=""                     # No rotation needed
    ;;
esac

# --- Build output filename ---
BASENAME="${INPUT%.*}"
OUTPUT="${BASENAME}_converted.mp4"

# --- Build the filter chain ---
SCALE="scale=1280:720:force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2"

if [ -z "$TRANSPOSE" ]; then
  VF="$SCALE"
else
  VF="${TRANSPOSE},${SCALE}"
fi

# --- Summary ---
echo "Input:     $INPUT"
echo "Output:    $OUTPUT"
echo "Rotation:  ${ROTATION}° -> corrected"
echo "Filter:    $VF"
echo ""

# --- Run FFmpeg ---
ffmpeg -i "$INPUT" \
  -vf "$VF" \
  -c:v libx264 \
  -crf 23 \
  -preset medium \
  -c:a aac \
  -b:a 128k \
  -metadata:s:v:0 rotate=0 \
  -movflags +faststart \
  "$OUTPUT"

if [ $? -eq 0 ]; then
  echo ""
  echo "Done! Output saved to: $OUTPUT"
else
  echo ""
  echo "Error: FFmpeg failed."
  exit 1
fi
