#!/bin/bash
# Generate reports from dummy mp3 folder.
# Author: Francois Mazen <francois@mzf.fr>


echo "creating temporary folder for mp3 files..."
mp3_folder=$(mktemp -d -t mp3-XXXXXXXXXX)
echo $mp3_folder
trap "rm -rf $mp3_folder" 0 INT QUIT ABRT PIPE TERM
cd $mp3_folder

echo "generate mp3 files..."
ffmpeg -ar 48000 -t 30 -f s16le -acodec pcm_s16le -ac 2 -i /dev/urandom -metadata title="File 1 title" -acodec libmp3lame -aq 4 -loglevel error file1.mp3
ffmpeg -ar 48000 -t 60 -f s16le -acodec pcm_s16le -ac 2 -i /dev/urandom -metadata title="File 2 title" -acodec libmp3lame -aq 4 -loglevel error file2.mp3
ffmpeg -ar 48000 -t 90 -f s16le -acodec pcm_s16le -ac 2 -i /dev/urandom -metadata title="File 3 title" -acodec libmp3lame -aq 4 -loglevel error file3.mp3

echo "test built-in default template..."
mp3report --title="My Title" $mp3_folder 2>&1

if [ ! -f mp3report.html ]; then
    echo "mp3report.html file not found!"
    exit 1
fi

grep -i '<title>My Title</title>' mp3report.html
if [ $? -eq 0 ]
then
  echo "Custom title found."
else
  echo "Custom title not found" >&2
  exit 1
fi


echo "test custom template..."

cat <<EOF > template.html
<!-- %% START_TEMPLATE_HEADER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->
title: \$t_title
numdirs: \$t_numdirs
numfiles: \$t_numfiles
<!-- %% END_TEMPLATE_HEADER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->

<!-- %% START_TEMPLATE_ITEMHEADER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->
--- item start
<!-- %% END_TEMPLATE_ITEMHEADER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->

<!-- %% START_TEMPLATE_ITEMDATA %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->
item_filename: \$item_filename
item_len: \$item_len
<!-- %% END_TEMPLATE_ITEMDATA %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->

<!-- %% START_TEMPLATE_ITEMFOOTER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->
--- item end
<!-- %% END_TEMPLATE_ITEMFOOTER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->

<!-- %% START_TEMPLATE_FOOTER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->
This is the footer.
<!-- %% END_TEMPLATE_FOOTER %% - DO NOT TOUCH THIS LINE. IT MUST BE ON A LINE BY ITSELF. -->
EOF

mp3report --title="My Title" --template=template.html --outfile=testreport.html $mp3_folder 2>&1

if [ ! -f testreport.html ]; then
    echo "testreport.html file not found!"
    exit 1
fi

cat <<EOF > expectedreport.html

title: My Title
numdirs: 1
numfiles: 3

--- item start

item_filename: file1.mp3
item_len: 00:30

item_filename: file2.mp3
item_len: 01:00

item_filename: file3.mp3
item_len: 01:30

--- item end

This is the footer.
EOF

diff expectedreport.html testreport.html
if [ $? -eq 0 ]
then
  echo "Reports match."
else
  echo "Generated report does not match expected report." >&2
  exit 1
fi



