# ---------------------------------------------------------------------------------
#
# What version of dvdwizard are we running?
#
dvdwizard_ver="dvdwizard version 0.4.2"

#
# Set decimal delimiter to '.' instead of ',' - otherwise
# chapters will only be accurate to seconds and not to frames
#
export LC_NUMERIC="C"

#
# Determine version of Image-Magick
#
export IM_VERSION=$(convert -version | grep ^Version: | cut -d' ' -f 3 | cut -d. -f 1)

# ---------------------------------------------------------------------------------
#
# If something goes wrong....  Default Error-Handling
#
error_out()
{
 cat << EOF

Hey, something went wrong in this script! Check for error messages in the log.
The last command returned a Non-Zero Return-Code ($?)
So I guess it's better to stop here and let you analyze the situation
Hope you'll find the error. ;-)
EOF
if [ -e "$logFile" ]; then
	cat << EOF
Here are the last 10 lines of the log ($logFile):
-------------------------------------------------------
EOF
	tail -n 10 "$logFile"
fi

exit 1
}

# ---------------------------------------------------------------------------------
#
# Set default processing options - either from config-File or from built-in
#
set_defaults()
{
dfltconfFile="$HOME/.dvdwizard/dvdwizard.conf"
confFile=""

#
# Search CLI-Parms for Config-File Specification
#
i=0
while [  $i -lt $# ]; do
   	let i+=1
    eval passed_arg=\${$i}
    if [ "$passed_arg" == "-C" -o "$passed_arg" == "--config-file" ]; then
    	let i+=1
	    eval confFile=\${$i}
     	if [ -f "$confFile" -a -r "$confFile" ]; then
      		:
        else
        	echo "Specified Config-File $confFile not found or no read permission. Aborting" >2
         	exit 1
        fi
		break 2
  	fi
done

#
# Check, if config file parm is given
# If not, try, if default config-file exists
# If it doesn't exist, use built-in defaults
#
if [ -z "$confFile" ]; then
 	if [ -f "$dfltconfFile" -a -r "$dfltconfFile" ]; then
        confFile=$dfltconfFile
	fi
fi

#
# Ok, set process options
#
if [ ! -z "$confFile" ]; then
	. "$confFile"
else
	confFile="built-in"
	BASEDIR="."
	TMPDIR="."
	DESTDIR="$BASEDIR/dvd"
	XMLFILE="$BASEDIR/dvdwizard.xml"
	LOGFILE="$BASEDIR/dvdwizard.log"
    CMDFILE="$BASEDIR/dvdwizard.cmd"
	XMLONLY=0
	NOTITLE=0
	TVNORM="PAL"
	TVSIZE="635x535"
	DVDAUDIO="de,en"
	VMGMBG=""
    TFONTSIZE=48
    HFONTSIZE=24
    MFONTSIZE=20
	CHAPTERSPEC=300
	VTSMBG=""
	VTSTITLE="auto"
    CHAPTERSPERROW=3
	THUMBRATIO="16:9"
    DE=deutsch
    EN=englisch

fi

return 0
}

# ---------------------------------------------------------------------------------
#
# Check and create Directory if not already present and called with the "New"-Parm
#
mk_check_dir()
{
chkdir="$1"
chkmode=$2
if [ -e "$chkdir" ]; then
	if [ ! -d "$chkdir" ]; then
    	echo "Specified directory $chkdir isn't a directory. Aborting" >&2
        usage
 	fi
    if [ -r "$chkdir" -a -w "$chkdir" -a -x "$chkdir" ]; then
    	:
    else
    	echo "Insufficient access rights on directory $chkdir, must have rwx. Aborting" >&2
        usage
    fi
else
	if [ "$chkmode" == "NEW" ]; then
		if mkdir -p "$chkdir"; then
    		:
 		else
			echo "Could not create directory $chkdir. Aborting" >&2
        	usage
		fi
  	else
    	echo "Specified input directory $chkdir not found. Aborting" >&2
        usage
    fi
fi

return 0
}

# ---------------------------------------------------------------------------------
#
# Check and create file if not already present and called with "New"
#
mk_check_file()
{
chkfile="$1"
chkmode=$2
if [ -e "$chkfile" ]; then
	if [ -d "$chkfile" ]; then
    	echo "Specified file $chkfile is a directory. Aborting" >&2
        usage
 	fi
    if [ -r "$chkfile" -a -w "$chkfile" ]; then
    	:
    else
    	echo "Insufficient access rights on file $chkfile, must have rw. Aborting" >&2
        usage
    fi
else
	if [ "$chkmode" == "NEW" ]; then
		if touch "$chkfile"; then
    		:
 		else
			echo "Could not create file $chkfile. Aborting" >&2
        	usage
		fi
  	else
    	echo "Specified input file $chkfile not found. Aborting" >&2
        usage
    fi
fi

return 0
}

# ---------------------------------------------------------------------------------
#
#  Create empty audio track to mux together with the menu video
#
create_silence()
{
echo "Creating empty Audio-Track..."
#
#  Specification of samplerate has changed from 0.2l to 0.2m, so check
#  which version of toolame will be used
#
tlver=$(toolame -h 2>&1 | grep version | cut -d' ' -f3)
[ "$tlver" \> "0.2l" ] && srate=48000 || srate=48

#
# PAL and NTSC differ in samples per frame. Set the appropriate value
# Value is set for 10 video frames.
#
[ "$TVNORM" == "NTSC" ] && samples=16016 || samples=19200

audiotrack="$workDir"/silence.m2a
dd if=/dev/zero bs=4 count=$samples | toolame -b 128 -s $srate /dev/stdin "$audiotrack" 1>/dev/null || error_out

echo "done"

return 0
}

# ---------------------------------------------------------------------------------
#
# Now prepare the background picture for the menu
#
prepare_bg()
{
echo -n "Preparing Background-Picture..."
bgPic="$1"

#
# Ok, first set dimensions according to tv-norm PAL or NTSC
#
if [ "$TVNORM" == "NTSC" ]; then
	normX=720
    normY=480
    densityX=81
    densityY=72
else
	normX=720
    normY=576
    densityX=75
    densityY=80
fi
normSize="$normX"x"$normY"
normDensity="$densityX"x"$densityY"
tvX=`echo $TVSIZE | cut -dx -f 1`
tvY=`echo $TVSIZE | cut -dx -f 2`
let offsetX=($normX-$tvX)/2+1
let offsetY=($normY-$tvY)/2+1

#
# If no background picture specified, create one
#
if [ -z "$bgPic" ]; then
	bgPic="$workDir"/tmp_bg.ppm
	convert -size $normSize -depth 8 gradient:white-darkblue \
			-pointsize 22 -fill grey -draw 'gravity Southeast text '"$(( $offsetX + 15 )),$(( $offsetY + 50 ))"' "made with dvdwizard ;-)"' \
			-implode 3 -swirl 270 \
           	-fill white -draw 'gravity southeast text '"$(( $offsetX+16 )),$(( $offsetY + 51 ))"' "made with dvdwizard ;-)"' \
           	+shade 50x50 $bgPic
fi
workbg="$workDir"/tmp_work_bg.ppm
convert -scale "$normSize"! -density "$normDensity" -units PixelsPerInch "$bgPic" "$workbg"

echo "done"

return 0
}

# ---------------------------------------------------------------------------------
#
# mk_tmpdvd - Create a temporary DVD-structure without menus but with chapters
#
mk_tmpdvd()
{
#
# Do some file and directory preparation
#
[ -e "$DESTDIR" ] && rm -R "$DESTDIR"
mkdir -p "$DESTDIR"
tmpxml="$TMPDIR"/tmp_dvd.xml
cat "$XMLFILE" > "$tmpxml"
echo -e "\t<vmgm>\n\t</vmgm>" >> "$tmpxml"

#
# Create a Titleset for each defined title
#
for i in $(seq 1 $vts); do
	echo -e "\t<titleset>" >> "$tmpxml"
    echo -e "\t\t<titles>" >> "$tmpxml"
    echo -e "\t\t\t<pgc pause=\"0\">" >> "$tmpxml"
    eval files=\"\$VTSM_"$i"_FILES\"
    eval cspec=\"\$CHAPTERSPEC_$i\"
	echo "Checking chapter definition"
    chapters=$(chaptercheck -N $TVNORM $cspec) || error_out
    for j in $(seq 1 $files); do
		eval vtstitle=\"\$VTSM_"$i"_FILE_$j\"
        echo -e "\t\t\t\t<vob file=\"$vtstitle\"" >> "$tmpxml"
        echo -e "\t\t\t\t chapters=\"$chapters\"" >> "$tmpxml"
        echo -e "\t\t\t\t pause=\"0\" />" >> "$tmpxml"
  	done
    echo -e "\t\t\t</pgc>" >> "$tmpxml"
    echo -e "\t\t</titles>" >> "$tmpxml"
	echo -e "\t</titleset>" >> "$tmpxml"
done

echo "</dvdauthor>" >> "$tmpxml"

#
# Now author the temporary DVD
#
dvdauthor -x "$tmpxml" || error_out

rm "$tmpxml"

return 0
}
#
#  End of dvdwizard script functions
#
