#!/bin/bash

# script Andremamp. Convert what audio type to pcm_s16le 
# AAC audio not regognised by DaVinci Resolve Studio 20
# A simple script to convert MP4 files to a
# format compatible with DaVinci Resolve and
# save them to a new folder.

# Exit immediately if a command exits with a non-zero status.
set -e

# Define the name of the output directory.
OUTPUT_DIR="converted_files"

# Create the output directory if it doesn't already exist.
# The -p flag prevents an error if the directory exists.
mkdir -p "$OUTPUT_DIR"

# Get the highest existing numerical prefix from the converted files
# to determine the new prefix for this run.
last_number=0
for f in "$OUTPUT_DIR"/*_converted.mov; do
  if [ -f "$f" ]; then
    num=$(basename "$f" | cut -d'_' -f1)
    if [ "$num" -gt "$last_number" ]; then
      last_number=$num
    fi
  fi
done

# Increment the highest number to get the new prefix for this run.
run_number=$((last_number+1))
run_prefix=$(printf "%03d" "$run_number")

echo "New files will be created with the prefix: ${run_prefix}_"

# Loop through all MP4 files in the current directory.
for f in *.mp4; do
  # Check if the file exists before processing.
  if [ -f "$f" ]; then
    # Construct the output filename.
    # Check if a converted version of the file already exists.
    # We'll use a simple check based on the original filename.
    if ls "$OUTPUT_DIR"/*_$(basename "$f" .mp4)_converted.mov 1> /dev/null 2>&1; then
      echo "Skipping $f... Converted file already exists."
    else
      output_file="$OUTPUT_DIR/${run_prefix}_$(basename "$f" .mp4)_converted.mov"
      
      echo "Converting $f..."
      # Run the FFmpeg conversion.
      ffmpeg -i "$f" -c:v copy -c:a pcm_s16le "$output_file"
      echo "Done."
    fi
  fi
done

echo "All files converted and saved to the '$OUTPUT_DIR' folder."

# Pause the script and wait for user input.
read -p "Press any key to exit..."

