#!/bin/bash

# *************************************************************************** #
# tgall-tag - tag images in a tgall managed photo gallery                     #
# Copyright (C) 2012 Elena Grandi                                             #
#                                                                             #
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.                   #
# *************************************************************************** #
# Usage:                                                                      #
#                                                                             #
# tgall-tag "<tag1> [<tag2> ...]" <img_1> [<img_2> ...]                       #
#                                                                             #
# If the environment variable $TGALL_TAGDIR is defined and points to          #
# a directory it is used as a basis dor link creation, otherwise              #
# ``../../../../tags`` is used (i.e. you are expected to be in the            #
# same directory as the images tagged).                                       #
# *************************************************************************** #

if [ -z $TGALL_TAGDIR ] || [ ! -d $TGALL_TAGDIR ]
then
    if [ -d ../../../../tags ]
    then
        TGALL_TAGDIR=$(readlink -e ../../../../tags)
    else
        echo "Could not find a valid tagdir."
        exit 1
    fi
else
    TGALL_TAGDIR=$(readlink -e $TGALL_TAGDIR)
fi

if [ $# -lt 2 ]
then
    echo "Usage: tgall-tag <tags> <files>"
    exit 1
fi

TAGS=$1
shift

for TG in $TAGS
do
    TAG=$TGALL_TAGDIR/$TG
    mkdir -p $TAG
    for FN in "$@"
    do
        IMG=$(readlink -e $(dirname $FN))/$(basename $FN)
        SRC=$(echo -e "import os.path\nprint(os.path.relpath(\"$IMG\",\"$TAG\"))" | python)
        DEST=$(basename $(dirname $IMG))-$(basename $FN)
        cd $TAG
        ln -s "$SRC" "$DEST"
        git add "$DEST"
        cd - > /dev/null
    done
done

