#!/bin/bash

# Check if an argument is provided
if [ -z "$1" ]; then
  echo "Usage: $0 fullPathOfMP4File"
  exit 1
fi

# Get the full path of the provided MP4 file
fullPathOfMP4File="$1"

# Extract the directory and filename from the provided path
dirName=$(dirname "$fullPathOfMP4File")
fileName=$(basename "$fullPathOfMP4File")

# Extract the prefix (everything before the first dot)
prefix=${fileName%%.*}

# Find all MP4 files in the directory with the same prefix
mp4Files=()
for file in "$dirName"/"$prefix"*.mp4; do
  mp4Files+=("$file")
done

# Check if there are files to merge
if [ ${#mp4Files[@]} -eq 0 ]; then
  echo "No MP4 files found with prefix $prefix"
  exit 1
fi

# Create a temporary file list for ffmpeg
fileList=$(mktemp)
for file in "${mp4Files[@]}"; do
  echo "file '$file'" >> "$fileList"
done

# Define the output file name
outputFile="${dirName}/${prefix}_merged.mp4"

# Merge the videos using ffmpeg
ffmpeg -f concat -safe 0 -i "$fileList" -c copy "$outputFile"

# Remove the temporary file list
rm "$fileList"

echo "Merged file created at: $outputFile"