#!/bin/bash

# Usage: ./convert_video.sh <input_file> <transpose_mode>
# Transpose modes:
#   0 = 90° counter-clockwise + vertical flip
#   1 = 90° clockwise
#   2 = 90° counter-clockwise
#   3 = 90° clockwise + vertical flip
#   4 = 180°
#   none = no rotation

INPUT="$1"
TRANSPOSE="$2"

# --- Validate input file ---
if [ -z "$INPUT" ]; then
  echo "Error: No input file specified."
  echo "Usage: $0 <input_file> <transpose_mode>"
  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

# --- Validate transpose mode ---
if [ -z "$TRANSPOSE" ]; then
  echo "Error: No transpose mode specified."
  echo "Usage: $0 <input_file> <transpose_mode>"
  echo "Transpose modes: 0, 1, 2, 3, 4 (180°), or 'none'"
  exit 1
fi

if [[ "$TRANSPOSE" != "none" && "$TRANSPOSE" != "0" && "$TRANSPOSE" != "1" && "$TRANSPOSE" != "2" && "$TRANSPOSE" != "3" && "$TRANSPOSE" != "4" ]]; then
  echo "Error: Invalid transpose mode '$TRANSPOSE'. Must be 0, 1, 2, 3, 4, or 'none'."
  exit 1
fi

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

# --- Build the filter ---
SCALE="scale='if(gt(iw,1280),1280,iw)':'if(gt(ih,720),720,ih)':force_original_aspect_ratio=decrease"

if [ "$TRANSPOSE" == "none" ]; then
  VF="$SCALE"
elif [ "$TRANSPOSE" == "4" ]; then
  VF="transpose=1,transpose=1,${SCALE}"
else
  VF="transpose=${TRANSPOSE},${SCALE}"
fi

# --- Run FFmpeg ---
echo "Input:     $INPUT"
echo "Output:    $OUTPUT"
echo "Transpose: $TRANSPOSE"
echo "Filter:    $VF"
echo ""

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
