#!/usr/pkg/bin/bash
#    dir2slideshow
#    Copyright 2004-2005 Scott Dylewski  <scott at dylewski.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

version='0.7.5'

changes () 
{
echo 'Changes:
0.7.5 	Allow spaces in filenames.
0.7.4 	No changes
0.7.3	
	Passing -c 0 does not create crossfades.
	Added option -notitle 
	Added option to specify background color or image -b image.jpg
	Fix output of "backgound:0:black" on first line. 
	It should read "background:0::black"
0.7.2	Added option to have all subtitles the same -s
0.7.1	Reads .jpg .JPG .jpeg .png .PNG files in the specified directory
0.1.0	Change version number
0.0.1	Initial release'
}

help ()
{
echo "dir2slideshow $version"
echo "dir2slideshow is part of the dvd-slideshow set of tools."
echo 'Copyright 2004-2005 Scott Dylewski <scott at dylewski.com>'
echo 'http://freshmeat.net/dvdslideshow'
echo  '
dir2slideshow description: 
 Generates a listing of the pictures in a given directory for easy
 input to dvd-slideshow.

Usage:
dir2slideshow [-o <output_directory>] [-t time_per_picture] [-c duration]
 -n slideshow_name [-T] [-M] [-s subtitle_text] [-notitle] <directory>
	
Options: 
 <directory>
	Input directory of pictures.

 -n slideshow_name
	Name of the slideshow.  This will be used in the title slide
	as well as for the output file name.
 
 [-o output_directory]
	Path to the directory where you want to output file written.
	No output directory chooses current directory.
 
 [-t time_per_picture]
	  Integer number of seconds that the picture will be visible
	  on the dvd movie. You can edit the output file to make
	  changes to specific lines. Default is 5 seconds.

 [-c duration]
	  Add a crossfade between every picture for duration seconds.
 		
 [-T]
	  Sort by the JPEG header picture taken date, then the file
	  modified date, and then the filename. Default sorts by 
	  name only

 [-M]
	  Sort by the the file modified date, and then the filename.
	  Default sorts by name only.
 		
 [-s subtitle_text]
	  Add default subtitle "subtitle_text" to every slide
 		
 [-b background.jpg]
	  Use background.jpg as background image. Default is black.
 		
 [-notitle]
	  Do not create a title slide.
 		
 -h or -help 
   Prints this help. 
'
}

if [ $# -lt 1 ]; then
	help
	exit 1
fi


## setup initial variables:
debug=0  # 1 or 0
crossfade=0
duration=5
output_dir="."
input_dir=""
name=''
sortmethod=''
title=1
background='black'

for arg
do
	case "$arg" in
	-i) shift; input_dir="$1" ; shift ;;
	-n) shift; name="$1" ; shift ;;
	-s) shift; subtitle="$1" ; shift ;;
	-b) shift; background="$1" ; shift ;;
	-notitle) title=0 ; shift ;;
	-o) shift; output_dir="$1"; shift ;;
        -t) shift; duration="$1"; shift ;; 
        -T) sortmethod="taken_date"; shift ;; 
        -M) sortmethod="modified_date"; shift ;; 
        -c) shift; crossfade=1; crossfade_duration="$1"; shift ;; 
	-h) help ; exit 0 ; shift ;;
	-?) help ; exit 0 ; shift ;;
	-help) help ; exit 0 ; shift ;;
	esac
done

echo "[dir2slideshow] dir2slideshow version $version"

if [ -z "$input_dir" ] ; then
	input_dir="$1"
fi
if [ -z "$input_dir" ] ; then
	echo '[dir2slideshow] Error: No input directory specified'
elif [ ! -d "$input_dir" ] ; then
	echo "[dir2slideshow] Error: Input directory is not a real directory: $input_dir"
fi

## check_rm checks to see if the file exists before it's deleted:
check_rm ()
{
	if [ -f "$1" ] ; then
		rm "$1"
	fi
}

## check for the necessary programs:
checkforprog ()
{
        it=`which "$1"`
        if [ -z "$it" ] ; then
                echo "[dir2slideshow] ERROR: $1 not found! "
                echo "[dir2slideshow] Check the dependencies and make sure everything is installed."
                exit 1
        fi
}

cleanup ()
{
	## clean up temporary files
	check_rm "$output_dir"/filelist.txt
	check_rm "$output_dir/filelist_sorted.txt"
	echo "[dir2slideshow] Done!"
}

forcequit () ## function gets run when we have some sort of forcequit...
{
	## clean up temporary files
	cleanup
	exit 1
}

trap 'forcequit' INT
trap 'forcequit' KILL
trap 'forcequit' TERM

# sanity checking 
# did the user give us a valid input file to work with?
if [ ! -d "$input_dir" ]; then
	# it's not a directory!
        echo "[dir2slideshow] ERROR: Bogus input directory (-i $input_dir)!"
        exit 1;
fi
if [ -z "$name" ]; then
        echo "[dir2slideshow] ERROR: You must enter a name for the slideshow using -n <name>"
        exit 1;
fi

# make sure $input_dir has no trailing slash
input_dir=`echo "$input_dir" | sed -e 's/\/$//'`;

## check to make sure the "album" name is ok?
if [ -z "$output_dir" ]; then
        # no output directory specified!
        echo "[dir2slideshow] WARNING: Invalid output destination (-o $output_dir)!";
        echo "[dir2slideshow]          Using `pwd` instead.";
        output_dir="`pwd`";
fi
if [ ! -d "$output_dir" ]; then
        # I'm sure it was a simple typo.
        echo "[dir2slideshow] WARNING: Invalid output destination (-o $output_dir)!";
        echo "[dir2slideshow]          Using $input_dir instead.";
        output_dir="$input_dir";
fi
                                                                                
# make sure $output_dir has no trailing slash
output_dir=`echo "$output_dir" | sed -e 's/\/$//'`;

outfile="$output_dir"/"`echo "$name" | sed -e 's/ /_/g'`.txt"

echo "[dir2slideshow] Input directory = $input_dir"
echo "[dir2slideshow] Slideshow name = $name"
echo "[dir2slideshow] Output file = $outfile"

echo "background:0::$background" > "$outfile"

## if title is wanted:
if [ "$title" -eq 1 ] ; then
	echo "title:$duration:$name" >> "$outfile"
	echo "fadeout:1" >> "$outfile"
	echo "background:1" >> "$outfile"
fi

echo "fadein:1" >> "$outfile"

## get the total number of pictures:
ls -1 "$input_dir"/*.jpg "$input_dir"/*.JPG "$input_dir"/*.jpeg "$input_dir"/*.png "$input_dir"/*.PNG > "$output_dir"/filelist.txt 2>/dev/null
pictures=`wc -l "$output_dir"/filelist.txt | awk '{print $1}'`
#pictures="$(( $pictures + 1))"

echo "[dir2slideshow] Total pictures found = $pictures"

## sort the pictures:

if [ "$sortmethod" == 'taken_date' ] ; then
	## sort by taken date:
	checkforprog jhead
	check_rm "$output_dir"/filelist_date.txt
	for i in `seq $pictures`; do
		file=`sed -n "$i"p "$output_dir"/filelist.txt`
		taken=`jhead "$file" | grep 'Date/Time' | awk -F': ' '{print $2}'`
		modified=`jhead "$file" | grep 'File date' | awk -F': ' '{print $2}'`
		if [ -n "$taken" ] ; then
			echo "$file: $taken" >> "$output_dir"/filelist_date.txt
		else
			echo "[dir2slideshow] No picture taken date in $file."
#			echo "[dir2slideshow] Using modification date!"
			echo "$file: $modified" >> "$output_dir"/filelist_date.txt
		fi
	done	
	## sort:
	sort -k 2,3 -d "$output_dir"/filelist_date.txt > "$output_dir"/filelist_sorted.txt

elif [ "$sortmethod" == 'modified_date' ] ; then
	## sort by modified date
	check_rm "$output_dir"/filelist_date.txt
	for i in `seq $pictures`; do
		file=`sed -n "$i"p "$output_dir"/filelist.txt`
		modified_day=`ls -l --full-time "$file" | awk '{print $6}'`
		modified_time=`ls -l --full-time "$file" | awk '{print $7}'`
#		echo "modified_day=$modified_day"
#		echo "modified_time=$modified_time"
		echo "$file: $modified_day $modified_time" >> "$output_dir"/filelist_date.txt
	done	
	## sort:
	sort -k 2,3 -d "$output_dir"/filelist_date.txt > "$output_dir"/filelist_sorted.txt
else
	## sort by name (should be done by ls -l)
	mv "$output_dir"/filelist.txt "$output_dir"/filelist_sorted.txt	
fi
check_rm "$output_dir"/filelist_date.txt

echo "[dir2slideshow] Sorting pictures..."
j=0
for i in `seq $pictures`; do
	file=`sed -n "$i"p "$output_dir"/filelist_sorted.txt | awk -F: '{print $1}'`
	## write to file:
	if [ -n "$subtitle" ] ; then
		echo "$file:$duration:$subtitle" >> "$outfile"
	else
		echo "$file:$duration" >> "$outfile"
	fi
	if [ "$crossfade" -eq 1 ] && [ "$crossfade_duration" -ne 0 ] && [ "$i" -lt "$pictures" ] ; then
		echo "crossfade:$crossfade_duration" >> "$outfile"
	fi
	let j=$j+1
done

## fade out at end
echo "fadeout:1" >> "$outfile"
echo "background:1" >> "$outfile"

cleanup

echo
