#!/bin/bash
# Video and Audio merging script written by QuidsUp
# Depends on ffmpeg
# Takes input video and audio file then copies them together with ffmpeg,
#  outputting video-processed.mkv or video-processed.mp4
# Usage: vidmerge.sh video
# NOTE the lack of .extension

input_file=""
input_audio=""
input_video=""
output_file=""
folder=$(pwd)

echo "Vidmerge"

if [[ ! $1 ]]; then                                        #Check argument has been given
  echo "Error - No file specified"
  exit 2
fi

input_file=$1

if [[ $input_file =~ \.$ ]]; then                          #Check if trailing . is present
  input_file=${input_file::-1}                             #Trim trailing .
fi

if [ -e "${input_file}.mkv" ]; then                        #Look for .mkv video
  input_video="$input_file.mkv"
  output_file="$folder/$input_file-processed.mkv"
elif [ -e "${input_file}.mp4" ]; then                      #Look for .mp4 video
  input_video="$folder/$input_file.mp4"
  output_file="$folder/$input_file-processed.mp4"
elif [ -e "${input_file}.mts" ]; then                      #Look for .mp4 video
  input_video="$folder/$input_file.mts"
  output_file="$folder/$input_file-processed.mkv"
else                                                       #Video missing
  echo "Error - Missing Video file"
  exit 3
fi

if [ -e "${input_file}.ogg" ]; then
  input_audio="$input_file.ogg"
elif [ -e "${input_file}.flac" ]; then
  input_audio="$folder/$input_file.flac"
elif [ -e "${input_file}.mp3" ]; then
  input_audio="$folder/$input_file.mp3"
elif [ -e "${input_file}.wav" ]; then
  input_audio="$folder/$input_file.wav"
else
  echo "Error - Missing Audio file"
  exit 4
fi

echo "Input Video: $input_video"
echo "Input Audio: $input_audio"
echo "Output File: $output_file"
echo

ffmpeg -i "$input_audio" -i "$input_video" -c:v copy "$output_file"

echo "Complete"
