#!/bin/sh
#  $Id$

#  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

shalbum_website="https://github.com/sztokbant/shalbum/releases"
sw_version="1.22"
shalbumrec_revision_date='$Date::             $'
shalbumrec_revision="shalbumrec $shalbumrec_version - $shalbum_website - $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:c:hil:qvGIQ opt; do
  case $opt in
      # link to go back
      b)  cl_back_link="$OPTARG"
	  ;;

      # CSS file
      c)  cl_css="$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 " -c        specify CSS file path"
	  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

# CSS
css_file=""                          # default CSS file

# HTML layout (deprecated, use CSS instead)
color_text="#ffffff"
color_bgcolor="#000000"
color_link="#ffffff"
color_vlink="#888888"
color_alink="#ff0000"
font_face="Arial, Helvetica, Sans Serif"

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

css_content=""

# 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

if [ "$cl_css" != "" ]; then
    css_file="$cl_css"
fi

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

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

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

load_css()
{

    if [ "$css_file" != "" ] && [ -f "$css_file" ]; then
	css_content="`cat $css_file`"
    else
	css_content="a:link {
            text-decoration: none;
            color: $color_link;
          }
          a:visited {
            text-decoration: none;
            color: $color_vlink;
          }
          a:active {
            text-decoration: none;
            color: $color_alink;
          }
          body {
            margin: 0px;
            padding: 0px;
            background: $color_bgcolor;
            color: $color_text;
            font-family: $font_face;
            font-size: 14px;
          }
          img {
            border: 0px solid;
          }
          table
          {
              border-color: #888888;
              border-width: 0px 0px;
              border-style: dotted;
          }
          td
          {
            padding: 0px;
            vertical-align: top;
          }
          td.pagesIndex
          {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
          }
          td.footerLeft
          {
            text-align: left;
            width: 50%;
            font-size: 12px;
            font-weight: bold;
          }
          td.footerRight
          {
            text-align: right;
            width: 50%;
            font-size: 12px;
            font-weight: bold;
          }
          label.currentPage
          {
            color: #ff0000;
          }
          label.playButton
          {
            color: #00ff00;
            font-weight: bold;
          }
          label.stopButton
          {
            color: #ff0000;
            font-weight: bold;
          }
          label.title
          {
            font-size: 22px;
            font-weight: bold;
          }
          label.subtitle
          {
            font-size: 16px;
          }"

	css_file=""
    fi
}

print_css()
{
    echo "<style type='text/css'>"${css_content}"</style>"
}

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

	echo '  <td class="footerLeft">'
        # support shalbum!
	if [ "$support_shalbum" = "yes" ]; then
	    echo "   <div>page created with <a href='$shalbum_website' target='shalbum'><u>shalbum</u></a></div><br />"
	fi
	
        # W3C XHTML 1.0 compliant banner
	if [ "$w3c_ok_banner" = "yes" ]; then
	    echo '   <div><a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></div>'
	fi
	echo "  </td>"
	
        # Author
	if [ "$author" != "" ]; then
	    echo '  <td class="footerRight">'
	    echo "   <div>${credits_str}${author}</div>"
	    if [ "$e_mail" != "" ]; then
		echo "   <div><a href='mailto:$e_mail'>$e_mail</a></div>"
	    fi
	    echo '  </td>'
	fi
	
	echo ' </tr>'
	echo '</table>'
	echo "<!-- credits end -->"
    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='
'

# load CSS file
load_css

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"

	command_line=""

	if [ "${dirname_as_title}" = "yes" ]; then
	    newtitle=`basename "$dir"`
	    if [ "${dirname_underscores_as_spaces}" = "yes" ]; then
		newtitle=`echo "${newtitle}" | sed 's/_/ /g'`
	    fi
	    command_line="${command_line} -t '${newtitle}'"
	fi

	if [ "${back_link}" != "" ] && [ "${backlink_label}" != "" ]; then
	    command_line="${command_line} -b '${back_link}' -l '${backlink_label}'"
	fi

	if [ "${css_file}" != "" ]; then
	    command_line="${command_line} -c '${css_file}'"
	fi

	sh -c "${shalbum} ${dash_i} ${dash_q} ${command_line}"

   	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 XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' > index.html
echo "<html xmlns='http://www.w3.org/1999/xhtml'>" >> index.html
echo "<!-- head -->" >> index.html
echo "<head>" >> index.html
echo " <meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=ISO-8859-1\" />" >> index.html
printf " " >> index.html
print_css >> index.html
echo " <title>${global_title}</title>" >> index.html
echo "</head>" >> index.html
echo "<!-- body -->" >> index.html
echo "<body>" >> index.html
echo "<div align='center'>" >> index.html
echo "<!-- header -->" >> index.html
echo "<table width='$table_width'>" >> index.html
echo " <tr>" >> index.html
echo "  <td align='left'>" >> index.html
echo "   <label class='title'>${global_title}</label>" >> index.html
echo "  </td>" >> index.html
echo " </tr>" >> index.html
echo "</table>" >> index.html

col_percentage=`expr 100 \/ $n_columns`
col_counter="0"
echo "<!-- main -->" >> index.html
echo "<table width='$table_width'>" >> index.html
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 2 | cut -d \\\" -f 1`"
	fi

	TITLE="`grep '<!-- shalbumrec:title' index.html | head -1 | cut -d '^' -f 2`"
	DATE="`grep '<!-- shalbumrec:date' index.html | head -1 | 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 align='left' width='${col_percentage}%'>" >> ../index.html
	echo "   <table width='100%'>" >> ../index.html
	echo "    <tr>" >> ../index.html
	echo "     <td align='left' width='${th_res}'><a href='$dir/index.html'><img alt='$dir' src='${th_dirname}/th_${dir}.jpg' /></a></td>" >> ../index.html
	echo "     <td align='left'><a href='$dir/index.html'><label class='subtitle'><b>${TITLE}</b></label></a><br />${DATE}</td>"  >> ../index.html
	echo "    </tr>" >> ../index.html
	echo "   </table>" >> ../index.html
	echo "  </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
echo "<br />" >> index.html

add_credits_footer >> index.html

echo "</div></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
