#!/bin/bash
#
# Add a title sequence to a video, with fade in and out
# (C) Roberto Di Cosmo, 2020-
# Licensed under GNU General Public License v3.0 or later
# SPDX-License-Identifier: GPL-3.0-or-later

output="output.mp4"

while getopts "ht:i:o:" opt; do
  case ${opt} in
    h ) # process option a
	echo "Usage: $0 [-h] [-t <title>] -i <input file> [-o <outputfile>]"
	echo "       without -t, title is read from the title.txt file"
	echo "       without -o, output is writtent to output.mp4"
      exit 0
      ;;
    t ) 
	title=${OPTARG}
      ;;
    i ) 
	input=${OPTARG}
      ;;
    o ) 
	output=${OPTARG}
      ;;
    \? ) echo "Usage: $0 [-h] -t <title> -i <input file> [-o <outputfile>]"
      exit 0
      ;;
  esac
done

#
# Create custom prelude with text
#

DS=6 # display start
DE=9.9 # display end
FID=2 # fade in duration
FOD=2 # fade out duration
if [ ! -z "${title}" ]; then
   echo "${title}" > title.txt
fi
if [ ! -f title.txt ]; then
    echo "Please provide a title: either use the -t option or create the title.txt file"
    exit 1
fi
ffmpeg -i SoftwareHeritage_Color_2_1080p.mp4 -i "$input" -filter_complex "[0:v][0:a][1:v][1:a]concat=n=2:v=1:a=1[out1v][outa];[out1v]drawtext=textfile=title.txt:x=800:y=650:fontsize=50:fontfile=/home/dicosmo/.fonts/Alegreya-Regular.otf:fontcolor_expr=ec1c28%{eif\\\\: clip(255*(1*between(t\\, $DS + $FID\\, $DE - $FOD) + ((t - $DS)/$FID)*between(t\\, $DS\\, $DS + $FID) + (-(t - $DE)/$FOD)*between(t\\, $DE - $FOD\\, $DE) )\\, 0\\, 255) \\\\: x\\\\: 2 }[outv]" -map "[outv]" -map "[outa]" $output

