#!/bin/bash

# Configure inputs
INPUT_FOLDER='/home/media/pitch/6'
DELETE_ORIGINALS=true #set to true to delete original files

# Set $IFS variable to handle files whitespace in name
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

# Generate list of files to be processed
FILES=`find "$INPUT_FOLDER" -name "*.webm" | sort`

# Iterate over files in list
for FILE in $FILES
do  
  # Generate output file name
  OUTPUT_FILE=`echo $FILE | rev | cut -d. -f2- | rev`".mp4"

  # Analyse file params with ffprobe
  AUDIO_CH=`ffprobe "${FILE}" -show_streams -select_streams a:0 -loglevel quiet | sed -n '/channels=/s/channels=//p'`
  AUDIO_CODEC=`ffprobe "${FILE}" -show_streams -select_streams a:0 -loglevel quiet | sed -n '/codec_name=/s/codec_name=//p'`

  # Process with ffmpeg
  if [[ $AUDIO_CH == "6" ]]; then
    # Downmix 6ch audio to 2ch aac
    ffmpeg -i "${FILE}" -c:v copy -af aresample=matrix_encoding=dplii -ac 2 -c:a aac -strict -2 -b:a 128k "${OUTPUT_FILE}"
  elif [[ $AUDIO_CODEC == "ac3" ]]; then
    # Convert ac3 audio to aac for better compatibility
    ffmpeg -i "${FILE}" -c:v copy -c:a aac -strict -2 -b:a 128k "${OUTPUT_FILE}"
  elif [[ $AUDIO_CODEC == "dca" ]]; then
    # Convert dts audio to aac for better compatibility
    ffmpeg -i "${FILE}" -c:v copy -c:a aac -strict -2 -b:a 128k "${OUTPUT_FILE}"
  else
    # Simple container change for files that do not hit conditions above
    ffmpeg -i "${FILE}" -codec copy "${OUTPUT_FILE}"
  fi

  # Delete original file if configured to do so
  if $DELETE_ORIGINALS; then
    rm "${FILE}"
  fi

done
