#!/bin/sh
#  $Id: shalbumrec 174 2008-07-25 04:57:37Z sztokbant $

#  Copyright 2006 Eduardo Sztokbant <du at du.eti.br>
#
#  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

shalbumrec_version="1.13"
shalbumrec_revision_date='$Date:: 2008-07-25 #$'
shalbumrec_revision="shalbumrec $shalbumrec_version - http://shalbum.sf.net - $shalbumrec_revision_date"

uname=`uname`

epoch()
{
    if [ $uname != "SunOS" ]; then
	date +%s
    else
	/usr/bin/truss /usr/bin/date 2>&1 | grep '^time' | cut -d '=' -f 2 | cut -d ' ' -f 2
    fi
}

# time
start_time="`epoch`"

while getopts b:hil:qvGIQ opt; do
  case $opt in
      # link to go back
      b)  cl_back_link="$OPTARG"
	  ;;

      # index
      i)  cl_only_index="yes"
	  ;;

      # back link label for album list site
      l)  cl_backlink_label="$OPTARG"
	  ;;

      # quiet
      q)  cl_quiet="yes"
	  ;;

      # version
      v)  echo ${shalbumrec_revision}
	  exit 1
	  ;;

      # choses between ImageMagick and GraphicsMagick
      G)  cl_magick="GM"
	  ;;

      # choses between ImageMagick and GraphicsMagick
      I)  cl_magick="IM"
	  ;;

      # quiet shalbum
      Q)  cl_quiet_shalbum="yes"
	  ;;

      # help screen
      *)  echo ${shalbumrec_revision}
	  echo "Usage: from a directory containing sub-directories with image files run"
	  echo "    shalbumrec [options]"
	  echo ""
	  echo " -h        help screen"
	  echo " -v        show shalbum version and exit"
	  echo ""
	  echo " -b link   link to go back"
	  echo " -l label  back link label for album list site"
	  echo ""
	  echo " -G        use GraphicsMagick"
	  echo " -I        use ImageMagick"
	  echo ""
	  echo " -i        don't resize shalbum images, only rebuild the HTML files"
	  echo " -q        quiet mode, suppress output"
	  echo " -Q        suppress shalbum output"
	  echo ""
	  echo "More options can be customized by using a .shalbumrec file."
	  exit 1
	  ;;
  esac
done

# path of shalbum script
shalbum="`which shalbum | cut -d ' ' -f 1`"

dirname="master_album"               # dir name for master album
th_dirname="masterth"                # subdir for thumbnails
global_title="My Albums"             # title for master album

dirname_as_title="no"                # directory name replaces album title
dirname_underscores_as_spaces="yes"  # if above option is yes replace _ by ' '

table_width="800"                    # width of HTML tables
th_res="150"                         # thumbnail resolution
n_columns="1"                        # number of table columns

author=""                            # site author's name
e_mail=''                            # site author's e-mail
support_shalbum="yes"                # print link to shalbum site
w3c_ok_banner="yes"                  # print "W3C HTML 4.01 compliant" banner
uname_in_revision="full"             # print OS name in revision comment

back_link=""                         # link to go back
backlink_label=""                    # back link label for album list site

only_index="no"                      # only create HTML files

magick="AUTO"                        # default: GraphicsMagick, if found

# HTML layout
color_text="#ffffff"
color_bgcolor="#000000"
color_link="#ffffff"
color_vlink="#888888"
color_alink="#ff0000"
font_face="Arial, Helvetica"

quiet="no"                           # suppress output
quiet_shalbum="no"                   # suppress shalbum output

# System-wide default options
if [ -f /etc/shalbum/shalbumrec.conf ]; then
    . /etc/shalbum/shalbumrec.conf
fi

# User default options
if [ -f $HOME/.shalbum/shalbumrec.conf ]; then
    . $HOME/.shalbum/shalbumrec.conf
fi

# read user-defined options
if [ -f ./.shalbumrec ]; then
    . ./.shalbumrec
fi

if [ "$cl_back_link" != "" ]; then
    back_link="$cl_back_link"
fi

if [ "$cl_backlink_label" != "" ]; then
    backlink_label="$cl_backlink_label"
fi

if [ "$cl_quiet" != "" ]; then
    quiet="$cl_quiet"
fi

if [ "$cl_quiet_shalbum" != "" ]; then
    quiet_shalbum="$cl_quiet_shalbum"
fi

if [ "$cl_only_index" != "" ]; then
    only_index="$cl_only_index"
fi

if [ "$cl_magick" != "" ]; then
    magick="$cl_magick"
fi

###############
# Aux functions
###############

println_info()
{
    if [ "$quiet" != "yes" ]; then
	echo "$*"
    fi
}

print_info()
{
    if [ "$quiet" != "yes" ]; then
	printf "$*"
    fi
}

add_credits_footer()
{
    if  [ "$author" != "" ] ||
	[ "$support_shalbum" = "yes" ] ||
	[ "$w3c_ok_banner" = "yes" ]; then
	
	echo "<!-- credits begin -->" >> $1
	echo '<table width="'$table_width'"><tr>' >> $1

	echo '<td width="50%" align="left" valign="top">' >> $1
        # support shalbum!
	if [ "$support_shalbum" = "yes" ]; then
	    echo "<p><font size='1' face='${font_face}'><b>page created with <a href='http://shalbum.sf.net' target='shalbum'><u>shalbum</u></a></b></font></p>" >> $1
	fi
	
        # W3C HTML 4.01 compliant banner
	if [ "$w3c_ok_banner" = "yes" ]; then
	    echo '<p><a href="http://validator.w3.org/check?uri=referer"><img border="0" src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Transitional" height="31" width="88"></a></p>' >> $1
	fi
	echo "</td>" >> $1
	
	echo '<td width="50%" align="right" valign="top">' >> $1
        # Author
	if [ "$author" != "" ]; then
	    echo "<p><font size='1' face='${font_face}'><b>$credits_str $author</b></font><br />" >> $1
	    if [ "$e_mail" != "" ]; then
		echo "<a href='mailto:$e_mail'><font size='1' face='${font_face}'><b>$e_mail</b></font></a></p>" >> $1
	    fi
	fi
	
	echo '</tr></table>' >> $1
	echo "<!-- credits end -->" >> $1
    fi
}


println_info $shalbumrec_revision

if [ "$shalbum" = "" ] || [ "$shalbum" = "no" ]; then
    echo "shalbum not found. Exiting."
    exit 1
fi

if [ "$quiet_shalbum" = "yes" ] || [ "$quiet" = "yes" ]; then
    dash_q="-q"
fi

if [ "$only_index" = "yes" ]; then
    dash_i="-i"
fi

# check for GraphicsMagick or ImageMagick's binaries (Default: GM)
if [ "$magick" = "GM" ] || [ "$magick" = "AUTO" ]; then
    WHICH_GM=`which gm | cut -d ' ' -f 1`
    if [ "$WHICH_GM" != "" ] && [ "$WHICH_GM" != "no" ]; then
	gm="gm"
	magick="GM"
    elif [ "$magick" = "GM" ]; then
	echo "GraphicsMagick not found. Exiting."
	exit 1
    fi
fi

if [ "$magick" = "IM" ] || [ "$magick" = "AUTO" ]; then
    gm=""
    magick="IM"

    WHICH_CONVERT=`which convert | cut -d ' ' -f 1`
    if [ "$WHICH_CONVERT" = "" ] || [ "$WHICH_CONVERT" = "no" ]; then
	echo "ImageMagick's 'convert' not found. Exiting."
	exit 1
    fi
fi

if [ "$magick" = "IM" ]; then
    println_info "  magick:   ImageMagick"
elif [ "$magick" = "GM" ]; then
    println_info "  magick:   GraphicsMagick"
fi


IFS='
'

dirname_bak="${dirname}.bak"
if [ -d "${dirname}" ] && [ "${only_index}" != "yes" ]; then
    # remove previous backup and backup current $dirname
    if [ -d "${dirname_bak}" ]; then
	print_info "Cleaning up previous backup directory..."
	rm -rf "${dirname_bak}"
	println_info "done!"
    fi
    mv "${dirname}" "${dirname_bak}"
fi

mkdir -p "${dirname}"

# create albums
start_pwd=`pwd`
for dir in `ls`; do
    if [ -d "$dir" ] && [ "$dir" != "$dirname" ] && [ "$dir" != "$dirname_bak" ]; then
	println_info "- Running shalbum in '$dir' directory"

	cd "$dir"
	if [ "${back_link}" != "" ] && [ "${backlink_label}" != "" ]; then
	    if [ "${dirname_as_title}" = "yes" ]; then
		newtitle=`basename "$dir"`
		if [ "${dirname_underscores_as_spaces}" = "yes" ]; then
		    newtitle=`echo "${newtitle}" | sed 's/_/ /g'`
		fi
		${shalbum} -b "${back_link}" -l "${backlink_label}" ${dash_i} ${dash_q} -t "${newtitle}"
	    else
		${shalbum} -b "${back_link}" -l "${backlink_label}" ${dash_i} ${dash_q}
	    fi
	else
	    if [ "${dirname_as_title}" = "yes" ]; then
                newtitle=`basename "$dir"`
                if [ "${dirname_underscores_as_spaces}" = "yes" ]; then
                    newtitle=`echo "${newtitle}" | sed 's/_/ /g'` 
		fi
		${shalbum} ${dash_i} ${dash_q} -t "${newtitle}"
	    else
		${shalbum} ${dash_i} ${dash_q}
	    fi
	fi
   	cd ${start_pwd} 1>/dev/null
	mkdir -p "${dirname}/$dir"
   	mv "$dir/album/"* "${dirname}/$dir"
	rmdir "$dir/album"
    fi
done

##############################################
# create thumbnails and master index.html file
##############################################

# time
idx_start_time="`epoch`"

cd "${dirname}"

echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">' > index.html
echo "<html>" >> index.html
echo "<head>" >> index.html
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">" >> index.html
echo "<style TYPE=\"text/css\"> A:link, A:visited { text-decoration: none; } </style>" >> index.html
echo "<title>${global_title}</title>" >> index.html
echo "</head>" >> index.html
echo "<body text='$color_text' bgcolor='$color_bgcolor' link='$color_link' vlink='$color_vlink' alink='$color_alink'><center>" >> index.html
echo "<table width='$table_width'><tr><td>" >> index.html
echo "<font size='5' face='${font_face}'><b>${global_title}</b></font>" >> index.html
echo "</td></tr></table>" >> index.html
echo "<table width='$table_width'>" >> index.html

col_percentage=`expr 100 \/ $n_columns`
col_counter="0"

m_albums_pwd=`pwd`
for dir in `ls`; do
    if [ -d "$dir" ] && [ "$dir" != "${th_dirname}" ]; then
	# attempt to get index pic specified by user
	FIRST=""
	if [ -f ../$dir/.shalbum ]; then
	    FIRST="`grep ^shalbumrec_index_pic= ../$dir/.shalbum | cut -d '=' -f 2`"
	elif [ -f ../$dir/_options ]; then
	    FIRST="`grep ^shalbumrec_index_pic= ../$dir/_options | cut -d '=' -f 2`"
	fi

	cd "$dir"
	if [ "$FIRST" = "" ]; then
	    FIRST="`grep img index.html | head -1 | cut -d \\\" -f 6`"
	fi

	TITLE="`grep '<!-- shalbumrec:title' index.html | cut -d  -f 2`"
	DATE="`grep '<!-- shalbumrec:date' index.html | cut -d  -f 2`"

	println_info "Generating thumbnail for '$dir'"
	$gm convert "vga/vga_${FIRST}" -resize ${th_res}x${th_res} ../th_"${dir}".jpg

	if [ $col_counter -eq 0 ]; then
	    echo "<tr>" >> ../index.html
	fi

	echo "<td valign='top' width='${col_percentage}%'><table width='100%'><tr><td width='${th_res}' valign='top'><a href='$dir/index.html'><img border='0' alt='$dir' src='${th_dirname}/th_${dir}.jpg'></a></td><td valign='top' align='left'><a href='$dir/index.html'><font size='3' face='${font_face}'><b>${TITLE}</b></font></a><br /><font size='2' face='${font_face}'>${DATE}</font></td></tr></table></td>" >> ../index.html

	col_counter=`expr $col_counter + 1`
	if [ $col_counter -eq $n_columns ]; then
	    echo "</tr>" >> ../index.html
	    col_counter="0"
	fi

	cd ${m_albums_pwd} 1>/dev/null
    fi
done

if [ ! $col_counter -eq 0 ]; then
    echo "</tr>" >> index.html
fi

echo "</table>" >> index.html

add_credits_footer index.html

echo "</center></body></html>" >> index.html

if [ "$uname_in_revision" = "full" ]; then
    shalbumrec_revision="${shalbumrec_revision} (`uname -srm`)"
elif [ "$uname_in_revision" = "short" ]; then
    shalbumrec_revision="${shalbumrec_revision} (${uname})"
fi

echo "<!-- created with $shalbumrec_revision -->" >> index.html

# time
idx_end_time="`epoch`"

mkdir -p "${th_dirname}"
mv th_*.jpg "${th_dirname}"
cd ..

println_info "Done!"

# time
end_time="`epoch`"

total_time=`expr $end_time - $start_time`
idx_time=`expr $idx_end_time - $idx_start_time`

print_info "Elapsed:  "
print_info "idx/img ${idx_time}s, "
println_info "total ${total_time}s"

exit 0
