# NanoBlogger Picture Gallery plugin
#
# Copyright 2005, 2006 Niels Heirbaut <niels@heirbaut.nl>
# This program is released under the GPL v2.

# How it works:
# Place all pictures for the gallery in a subdir of $BLOG_DIR/images/galleries
# the plugin will pick up the pictures from there an create the gallery.
# An entry called intro.txt can be used as introduction to the gallery. Just
# generate it using nb --draft intro.txt in you gallery subdir.
#
# If you are using a version of NanoBlogger that does not have the --draft
# option (<3.3) you can also handcraft one. The simplest method is to copy one
# of your entries from $BLOG_DIR/data to the gallery directory, rename it to
# 'intro.txt' and replace ALL entries in there (especially the date!).
# Alternatively you can also consult the documentation. Here you will find an
# example of an empty entry.
#
# A file named annotations.txt can be used to put annotations with selected
# pictures. The format is:
#
#   <picture_file>,<annotation>

# sample code for templates, based off the default stylesheet
#
# <div class="side">
# $NB_GalleryLinks
# </div>

GALLERY_PLUGIN_OUTFILE="$BLOG_DIR/$PARTS_DIR/gallery_links.$NB_FILETYPE"
> "$GALLERY_PLUGIN_OUTFILE"

set_gallery_baseurl(){
    OLD_BASE_URL=$BASE_URL
    GALLERY_BASEDIR=${GALLERY_BASEDIR%/}
    BASE_URL="../"

    local ofs=$IFS; IFS='/'
    for d in $GALLERY_BASEDIR ; do
        BASE_URL="../$BASE_URL"
    done
    IFS=$ofs
}

set_galleryconf(){
    : ${GALLERY_BASEDIR:=images/galleries}
    : ${GALLERY_TEMPLATE:=$NB_TEMPLATE_DIR/makepage_gallery.htm}
    : ${GALLERY_IMG_TEMPLATE:=$NB_TEMPLATE_DIR/makepage_gallery_img.htm}
##$MAKEPAGE_TEMPLATE}
    : ${GALLERY_THUMBNAILCMD:=convert}
    : ${GALLERY_ANNOTATIONFILE:=annotations.txt}
    : ${GALLERY_THUMBNAILSUBDIR:=thumbs}
    : ${GALLERY_SLIDESUBDIR:=slides}
    : ${GALLERY_SLIDESIZE:=600}
    : ${GALLERY_THUMBNAILSIZE:=150}
    : ${GALLERY_INTROFILE:=intro.txt}
    : ${GALLERY_ROWITEMS:=3}

    set_gallery_baseurl
    NBVERSION="${VERSION%% *}"
}

reset_galleryconf(){
    GALLERY_TEMPLATE=
    set_galleryconf
}

# Compares version numbers of the format "x[.y]*", where x and y are integer
# numbers.
# Returns  0 if n1 == n2
#          1 if n1 < n2
#          2 if n1 > n2
compare_versions(){
    [ "x$1" == "x$2" ] && return 0

    # Split the version number elements. Strip everything from the version
    # number that is not conforming to the "x[.y]*" pattern
    local ofs=$IFS
    IFS='.'
    local -a v1
    local -a v2
    eval "v1=( \${1%%[^0-9\.]*} )"
    eval "v2=( \${2%%[^0-9\.]*} )"
    IFS=$ofs

    # Determine the maximum number of elements
    local n=${#v1[@]}
    [ $n -lt ${#v2[@]} ] && n=${#v2[@]}

    # Compare all possible elements
    for ((i=0; i < n; i++)); do
        [ -z "${v1[i]}" ] && v1[$i]=0
        [ -z "${v2[i]}" ] && v2[$i]=0
        [ ${v1[i]} -lt ${v2[i]} ] && return 1
        [ ${v1[i]} -gt ${v2[i]} ] && return 2
    done

    return 0
}

add_gallerylink(){
    # miek make ref absolute
    echo '<a href="/blog/'$GALLERY_BASEDIR/`basename $GALLERY_DIR`/index.html'">'$GALLERY_TITLE'</a><br />' >> "$GALLERY_PLUGIN_OUTFILE"
}

create_slide() {
    [ ! -d "$GALLERY_SLIDEDIR" ] && mkdir "$GALLERY_SLIDEDIR"

    if [ ! -f $GALLERY_SLIDEDIR/$PICTURE ] ; then
        nb_msg "generating slide for $PICTURE ..."
        $GALLERY_THUMBNAILCMD "$GALLERY_DIR/$PICTURE" -resize $GALLERY_SLIDESIZE "$GALLERY_SLIDEDIR/$PICTURE"
    fi
}

create_thumbnail(){
    [ ! -d "$GALLERY_THUMBNAILDIR" ] && mkdir "$GALLERY_THUMBNAILDIR"

    if [ ! -f $GALLERY_THUMBNAILDIR/$PICTURE ] ; then
        nb_msg "generating thumbnail for $PICTURE ..."
        $GALLERY_THUMBNAILCMD "$GALLERY_DIR/$PICTURE" -resize $GALLERY_THUMBNAILSIZE "$GALLERY_THUMBNAILDIR/$PICTURE"
    fi
}

set_pagetitle(){
    METADATA=
    read_metadata TITLE "$GALLERY_DIR/$GALLERY_INTROFILE"

    if [ -z "$METADATA" ] ; then
        # Check for the versions because the return variable set by
        # read_metadata has changed several times.
        #
        # 3.0 <= $VERSION < 3.2 : sets $NB_Metadata
        # 3.2 <= $VERSION < 3.3 : sets $META_DATA
        # 3.3 <= $VERSION       : sets $METADATA
        compare_versions "$VERSION" "3.2"
        local rc=$?

        local major_version=
        [ $rc -eq 0 -o $rc -eq 2 ] && major_version="3.2"

        if [ -z $major_version ] ; then
            # The version is < 3.2
            METADATA="$NB_Metadata"
        elif [ "$major_version" = "3.2" ] ; then
            # The version is >= 3.2 and < 3.3
            METADATA="$META_DATA"
        fi
    fi

    if [ -z "$METADATA" ]; then
        GALLERY_TITLE="`basename $GALLERY_DIR`"
    else
        GALLERY_TITLE="$METADATA"
    fi
}

put_annotation(){
    annotation=
    if [ -f $GALLERY_DIR/$GALLERY_ANNOTATIONFILE ] ; then
        annotation=$(grep $PICTURE $GALLERY_DIR/$GALLERY_ANNOTATIONFILE | sed -e "s/^$PICTURE,\(.*\)$/\1/")
        if [ ! -z "$annotation" ] ; then
            echo "<p><div class=\"annotation\">$annotation</div></p>" >> $GALLERY_OUTFILE
        fi
    fi
}

put_introtext(){
    if [ -f $GALLERY_DIR/$GALLERY_INTROFILE ] ; then

        # Check for the versions because the return variable set by
        # read_metadata has changed several times.
        #
        # 3.0 <= $VERSION < 3.2 : sets $NB_Metadata
        # 3.2 <= $VERSION < 3.3 : sets $META_DATA
        # 3.3 <= $VERSION       : sets $METADATA
        compare_versions "$VERSION" "3.3"
        local vercompare=$?

        if [ $vercompare -eq 0 -o $vercompare -eq 2 ] ; then
            # Version >= 3.3
            read_metadata "BODY,$METADATA_CLOSETAG" $GALLERY_DIR/$GALLERY_INTROFILE
            NB_EntryBody=$METADATA
        else
            # Version < 3.3
            read_metadata BODY "$GALLERY_DIR/$GALLERY_INTROFILE"

            compare_versions "$VERSION" "3.2"
            vercompare=$?

            if [ $vercompare -eq 0 -o $vercompare -eq 2 ] ; then
                # Version >= 3.2
                NB_EntryBody=$META_DATA
            else
                # Version < 3.2
                NB_EntryBody=$NB_Metadata
            fi
        fi

        # For version >= 3.3 a format plugin can be called. This means that
        # i.e. Markdown markup can be used.
        if [ $vercompare -eq 2 ] ; then
            read_metadata FORMAT $GALLERY_DIR/$GALLERY_INTROFILE
            load_plugins entry/format "$METADATA"
        fi

        if [ ! -z "$NB_EntryBody" ] ; then
            cat >> "$GALLERY_OUTFILE" <<-EOF
                <td colspan=$GALLERY_ROWITEMS><div id="introtext">$NB_EntryBody</div></td>
                </tr><tr>
EOF
        fi
    fi
}

put_thumbnail()
{
    create_slide
    create_thumbnail
    cat >> "$GALLERY_OUTFILE" <<-EOF
        <td width=$CELLWIDTH%><div class="picture"><p>
        <a href="$GALLERY_URL/html/$PICTURE.html">
            <img alt="$PICTURE" src="$GALLERY_URL/$GALLERY_THUMBNAILSUBDIR/$PICTURE" />
        </a></p></div>
EOF
}

gallery_remove_macmeta(){
    for metapicture in `find $GALLERY_DIR -maxdepth 1 -name ._\*.jpg -o -name ._\*.JPG -o -name ._\*.png -o -name ._\*.PNG`
    do
        rm -f $metapicture
    done
}

# rescalen kan altijd nog
create_prevnext_thumbnail(){
    GALLERY_IMG_OUTFILE_TMP="$GALLERY_DIR/html/tmp.html"
    GALLERY_IMG_OUTFILE="$GALLERY_DIR/html/$PICTURE.html"
    ((prev=$count - 1))
    ((next=$count + 1))
    if [ -f $GALLERY_DIR/html/$PICTURE.html ]; then
	return
    fi

    if [ -f $GALLERY_DIR/$GALLERY_ANNOTATIONFILE ] ; then
        annotation=$(grep $PICTURE $GALLERY_DIR/$GALLERY_ANNOTATIONFILE | sed -e "s/^$PICTURE,\(.*\)$/\1/")
        if [ ! -z "$annotation" ] ; then
            annotation=$(cat <<-EOF
    <p class="center"><div class="annotation">$annotation</div></p>
EOF
)
        fi
    fi

    if [ $count -eq 0 ]; then
	IMG_LINK=$(cat <<-EOF
	<p class="center">
	<a href="$GALLERY_URL/index.html">Index</A> &nbsp; &nbsp; &nbsp;
        <a href="$GALLERY_URL/html/${pnlist[$pnlast]}.html">&lt;&lt; Prev</A>&nbsp; &nbsp;
	<a href="$GALLERY_URL/html/${pnlist[1]}.html">Next &gt;&gt;</a>
	</p>
EOF
)
    else
	if [ -z ${pnlist[$next]} ]; then
#	    cat >> $GALLERY_IMG_OUTFILE_TMP <<-EOF
            IMG_LINK=$(cat <<-EOF
	    <P class="center">
	    <a href="$GALLERY_URL/index.html">Index</A> &nbsp; &nbsp; &nbsp;
            <A href="$GALLERY_URL/html/${pnlist[$prev]}.html">&lt;&lt; Prev</A>&nbsp; &nbsp;
	    <a href="$GALLERY_URL/html/${pnlist[0]}.html">Next &gt;&gt;</a>
	    </P>
EOF
)
	else
            IMG_LINK=$(cat <<-EOF
	    <P class="center">
	    <a href="$GALLERY_URL/index.html">Index</A> &nbsp; &nbsp; &nbsp;
            <A href="$GALLERY_URL/html/${pnlist[$prev]}.html">&lt;&lt; Prev</A>&nbsp; &nbsp;
	    <a href="$GALLERY_URL/html/${pnlist[$next]}.html">Next &gt;&gt;</a>
	    </P>
EOF
)
	fi
    fi
    cat >> $GALLERY_IMG_OUTFILE_TMP <<-EOF
	$IMG_LINK
	$annotation
	<div class="center">
        <a href="$GALLERY_URL/$PICTURE">
            <img alt="$PICTURE" title="$PICTURE" src="$GALLERY_URL/$GALLERYDIR/$GALLERY_SLIDESUBDIR/$PICTURE" />
        </a>
	</div>
	$IMG_LINK
EOF
    if [ -e $GALLERY_IMG_OUTFILE_TMP ]; then
	MKPAGE_TITLE="$GALLERY_TITLE"
	make_page "$GALLERY_IMG_OUTFILE_TMP" "$GALLERY_IMG_TEMPLATE" "$GALLERY_IMG_OUTFILE"
	rm -f $GALLERY_IMG_OUTFILE_TMP
    fi
}

# for prev and next links; put this in a hash
# they are
create_prevnext_hash(){
    j=0
    pnlist=()
    for PICTURE in `find $GALLERY_DIR -maxdepth 1 -name \*.jpg -o -name \*.JPG -o -name \*.png -o -name \*.PNG`
    do
	pnlist[$j]=`basename $PICTURE`
	((j=$j + 1))
    done
    ((pnlast=$j - 1))
}

create_gallery(){
    GALLERY_OUTFILE="$GALLERY_DIR/tmp.html"
    GALLERY_PAGEFILE="$GALLERY_DIR/index.html"
    GALLERY_URL="${BASE_URL}$GALLERY_BASEDIR/`basename $GALLERY_DIR`"
    GALLERY_THUMBNAILDIR="$GALLERY_DIR/$GALLERY_THUMBNAILSUBDIR"
    GALLERY_SLIDEDIR="$GALLERY_DIR/$GALLERY_SLIDESUBDIR"
    CELLWIDTH=$((100 / $GALLERY_ROWITEMS))

    cat > "$GALLERY_OUTFILE" <<-EOF
        <div class="gallery">
        <table summary="NanoBlogger gallery">
        <tr>
EOF

    put_introtext
    create_prevnext_hash

    count=0
    for PICTURE in `find $GALLERY_DIR -maxdepth 1 -name \*.jpg -o -name \*.JPG -o -name \*.png -o -name \*.PNG`
    do
        PICTURE=`basename $PICTURE`
        if [ $((count % $GALLERY_ROWITEMS )) -eq 0 ]; then
            if [ $count -ne 0 ] ; then
                echo "</tr><tr>" >> $GALLERY_OUTFILE
            fi
        fi
	create_prevnext_thumbnail
        put_thumbnail
        put_annotation
        echo "</td>" >> $GALLERY_OUTFILE
        count=$((count+1))
    done

    cat >> "$GALLERY_OUTFILE" <<-EOF
        </tr>
        </table>
        </div>
EOF
}


set_galleryconf

# do this to get the links in the photo page
. /usr/share/nanoblogger/plugins/recent_entries.sh
. /usr/share/nanoblogger/plugins/weblog_links.sh
. /usr/share/nanoblogger/plugins/z001_articles_meta.sh
. /usr/share/nanoblogger/plugins/entry/category_links.sh
. ~/miek.nl/blog/plugins/tagcloud.sh

if [ -d "$BLOG_DIR/$GALLERY_BASEDIR" ]; then
    nb_msg "generating picture galleries ..."
    for GALLERY_DIR in `find $BLOG_DIR/$GALLERY_BASEDIR -mindepth 1 -maxdepth 1 -type d`; do
    # test test
#    for GALLERY_DIR in /home/miekg/miek.nl/blog/images/galleries/2007-kl; do
        nb_msg $GALLERY_DIR
	[ ! -d "$GALLERY_DIR/html" ] && mkdir "$GALLERY_DIR/html"
        GALLERY_TITLE=
        create_gallery
        set_pagetitle
        if [ -e $GALLERY_OUTFILE ]; then
            MKPAGE_TITLE="$GALLERY_TITLE"
            make_page "$GALLERY_OUTFILE" "$GALLERY_TEMPLATE" "$GALLERY_PAGEFILE"
            rm -f $GALLERY_OUTFILE
        fi
        add_gallerylink

        [ $(uname) = 'Darwin' ] && gallery_remove_macmeta

    done
fi

NB_GalleryLinks=$(< "$GALLERY_PLUGIN_OUTFILE")

reset_galleryconf

BASE_URL=$OLD_BASE_URL
