#!/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 mediainfo ---
if ! command -v mediainfo &> /dev/null; then
  echo "Error: mediainfo is not installed or not in PATH."
  exit 1
fi

echo "Using mediainfo to detect rotation..."

# Get raw value and display it for debugging
RAW_ROTATION=$(mediainfo --Output="Video;%Rotation%" "$INPUT" 2>/dev/null)
echo "Raw mediainfo rotation value: '${RAW_ROTATION}'"

# Also try the grep method as a fallback
GREP_ROTATION=$(mediainfo "$INPUT" | grep -i "Rotation" | awk -F': ' '{print $2}' | tr -d ' ')
echo "Grep mediainfo rotation value: '${GREP_ROTATION}'"

# Use whichever one returned a value
if [ -n "$RAW_ROTATION" ]; then
  ROTATION_RAW="$RAW_ROTATION"
elif [ -n "$GREP_ROTATION" ]; then
  ROTATION_RAW="$GREP_ROTATION"
else
  echo "No rotation metadata found, assuming 0."
  ROTATION_RAW="0"
fi

# Normalize to integer (handles values like "90.000")
ROTATION=$(printf "%.0f" "$ROTATION_RAW" 2>/dev/null || echo "0")
echo "Normalized rotation: ${ROTATION}°"

# --- Map rotation degrees to transpose filter ---
case "$ROTATION" in
  90)
    TRANSPOSE="transpose=2"
    ;;
  180)
    TRANSPOSE="transpose=1,transpose=1"
    ;;
  270|-90)
    TRANSPOSE="transpose=1"
    ;;
  *)
    TRANSPOSE=""
    echo "No rotation correction 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 \
  -movflags +faststart \
  "$OUTPUT"

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