#!/bin/bash

# costruisce una struttura di file .html per visualizzare 
# le foto contenute nella directory corrente
# bisogna mettere delle icone "up.png" "left.png" e "right.png" nella 
# directory .icons (o in ../[...]/.icons) o in /usr/local/lib/photoindex/ 

while [ $# -gt 0 ] ; do

if [ "$1" == "-c" -o "$1" == "-i" ] ; then
  ask_comment=1
  shift
  continue
fi

if [ "$1" == "-r" ] ; then
  recurse=1
  shift
  continue
fi

if [ "$1" != "" ] ; then
cat <<EOF
photoindex: manu-fatto (2003)

USAGE: photoindex [-c] 

DESCRIPTION:
    creates a file "index.html" with the list of all images found in
    the current directory. Subdirectories are also listed if they
    contain an "index.html" file.

    The index file contains a small copy of every image to make
    icons. Next to each icon it contains the description of the image
    which is taken either from a file "*.txt" with the same basename
    of the image file or from the description encoded in the image
    itself. Every image icon has a link to an HTML file which contains
    a bigger copy of the image and which contains a link to the
    original image.  

    The program is written to be fast if only a few images have been
    modified: this is achieved by checking modification times and by
    caching important properties of images.

    The program looks for buttons icons in the directories: .icons,
    ../.icons,... and /usr/local/lib/photoindex/. The name of the
    icons are: "up.png", "left.png" and "right.png".

    With the '-c' option the program ask for modifications to every image
    found. For every image you can:
    - write a comment;
    - rotate it;
    - delete it.
EOF
exit
fi

done

function comment {
    IFS=""
    file="$1"
    while true ; do
	echo "************************"
	echo file: $file
	echo comments:
	identify -format "%c" $file
	echo "Cosa faccio [$cosa]? (s)kip, (c)omment, (d)isplay, rotate (r)ight, (l)eft, (x)cancella"
	read 
	if [ "$REPLY" != "" ] ; then cosa="$REPLY" ; fi
	if [ "$cosa" = "d" ] ; then
	    display $file &
	elif [ "$cosa" = "c" ] ; then
	    echo "Luogo [$luogo]?"
	    read
	    luogo="${REPLY:-$luogo}"
#	    data=$( date +"%-d %b %Y, %H:%M" -d "$( stat --format "%y" "$file" | cut -c1-16 )" )
	    data=$date
	    echo "data [$data]?"
	    read
	    data=${REPLY:-$data}
	    echo "descrizione [$descrizione]: "
	    read
	    descrizione="${REPLY:-$descrizione}"

	    title="$luogo"
	    if [ "$data" ] ; then title="$title, $data"; fi
	    echo "titolo: $title"
	    echo "descrizione: $descrizione"
	    echo "salvo [s]? s/n"
	    read
	    if [ "$REPLY" == "s" -o "$REPLY" == "" ] ; then
		comment="$title\n$descrizione"
		mogrify -comment "$comment" "$file"
		touch -c .medium/"$file".jpg
		touch -c .small/"$file".png
		return
	    fi
	elif [ "$cosa" = "r" -o "$REPLY" = "l" ] ; then
	    if [ "$cosa" = "r" ] ; then degrees=90 ; fi
	    if [ "$cosa" = "l" ] ; then degrees="-90" ; fi
	    mogrify -rotate $degrees $file
	    rm .medium/"$file".jpg
	    rm .small/"$file".png
	elif [ "$cosa" = "x" ] ; then
	    echo "Sicuro di voler cancellare il file $file ? si/no"
	    read
	    if [ "$REPLY" = "si" ] ; then
		rm "$file"
		echo "$file cancellato"
		return
	    fi
	else 
	    return
	fi
    done 
}

allow_null_glob_expansion=1

REALOUT=index.html
OUT=$REALOUT.delete
TITLE=`basename "$PWD"`
SMALL=".small"
MEDIUM=".medium"
SMALL_GEOMETRY="80x60"
MEDIUM_GEOMETRY="640x480"

NUMCOLONNE="5"

SIGNATURE="photoindexsignature"

ICONS=""

BASEUP="INDIETRO"
UP="INDIETRO"
LEFT="PRECEDENTE"
RIGHT="SUCCESSIVO"

for dir in ./.icons ../.icons ../../.icons ../../../.icons ../../../../.icons ../../../../../.icons /usr/local/lib/photoindex/ ; do
  if [ -f $dir/up.png -a -f $dir/left.png -a -f $dir/right.png ] ; then
    echo Ho trovato le icone nella directory "$dir"
    BASEUP="<img src=\"$dir/up.png\" alt=\"$BASEUP\">"
    if [ "${dir:0:1}" != "/" ] ; then
      dir="../$dir"
    fi
    UP="<img src=\"$dir/up.png\" alt=\"$UP\">"
    LEFT="<img src=\"$dir/left.png\" alt=\"$LEFT\">"
    RIGHT="<img src=\"$dir/right.png\" alt=\"$RIGHT\">"
    break
  fi
done

if [ -f index.htm ] ; then 
  echo Esiste il file index.htm, meglio lasciar perdere $PWD
  exit
fi

if [ -f "$REALOUT" ] ; then
    if grep -q "$SIGNATURE" "$REALOUT" ; then
	true
    else
	echo il file $REALOUT non l\'ho firmato io... meglio lasciar perdere $PWD
	exit
    fi
fi


echo Creo il file $PWD/$OUT
echo > $OUT

if [ -f index.txt ] ; then
  TITLE=`head -1 index.txt`
fi

cat <<EOF >>$OUT
<html>
<!-- QUESTO FILE E'' STATO GENERATO AUTOMATICAMENTE con photoindex -->
<!-- ***NON MODIFICARE*** -->
<!-- $SIGNATURE -->
<body>
<h2>$TITLE</h2>

<table>

EOF

## eventuale link alla directory superiore

for file in ../index.html ../index.htm ; do
  if [ -f "$file" ] ; then
    echo "<a href=\"$file\">$BASEUP</a><br>" >> $OUT
    break
  fi
done


## links alle sottodirectory

for file in * ; do 
if [ -d "$file" ] ; then
  echo DIRECTORY "$file"
  if [ "$recurse" ] ; then
    pushd "$file"
    $0 $1
    popd
  fi
  title="$file"
  if [ -f "$file"/index.txt ] ; then
    title=`head -1 "$file"/index.txt`
  fi
  for try in "$REALOUT" "index.htm" ; do
    if [ -f "$file"/"$try" ] ; then
      echo "<a href=\"$file/$try\">$title</a><br>" >> $OUT
      break
    fi
  done
fi
done

## crea le directory .small e .medium e cancella i files che 
## non servono piu`

for dir in $SMALL $MEDIUM ; do
  if [ ! -d "$dir" ] ; then
    echo Creo la directory "$dir"
    mkdir "$dir"
  fi
  cd $dir || exit 1
  for file in * ; do
    if [ "$file" = "*" ] ; then
      continue
    fi
    if [ ! -f ../"${file%.*}" -a ! -f ../"$file" ] ; then
      echo "rimuovo $dir/$file"
      rm "$file"
    fi
  done
  cd ..
done

## crea le foto piccole, le icone e i files secondari per ogni foto

prev="";
file="";

contacolonne=1;


#for next in *.{jpg,png,gif,JPG,PNG,GIF} ""; do
for next in * ""; do

    if [ "${next:0:1}" == "*" ] ; then continue; fi


    descr=$(file "$next")
    nextfiletype=unknown
    if [ ! "${descr//image}" == "$descr" ] ; then 
	nextfiletype=image
    elif [ ! "${descr//video}" == "$descr" ] ; then
	nextfiletype=video
    elif [ ! "${descr//audio}" == "$descr" ] ; then
	nextfiletype=audio
    fi
    
    if [ "$next" -a "$nextfiletype" == unknown ] ; then continue; fi
    
    if [ "$file" ] ; then
	
	if [ -L "$file" ] ; then
	    realfile=`ls -l "$file" | cut -f2 -d">" | cut -c2-`
	    echo "($file -> $realfile) $filetype"
	else
	    realfile="$file"
	    echo "($file) $filetype"
	fi
	
	txt=""
	
	for try in "${file}.txt" "${file%.*}.txt" "${realfile}.txt" "${realfile%.*}.txt" ; do
	    if [ -e "$try" ] ; then
		txt="$try"
		break
	    fi
	done
	
	name="${file//.*}"
	
	title=""
	if [ "$file" -nt .medium/"$file".cache -o "$txt" -nt .medium/"$file".cache ] ; then 
	    if [ $filetype == image -o $filetype == video ] ; then
		TEMP="/tmp/photoindex-$$"
		
		identify -format "ZZSKIPZZSIZE=%wx%h\nZZSKIPZZTITLE= %c" "$file" > $TEMP
		date=$( identify -verbose "$file" | grep "Date Time:" | cut -f2- -d: )
		date=$( date -d "${date:1:4}/${date:6:2}/${date:9:2} ${date:12:5}" +"%-d %b %Y, %H:%M" )
		SIZE=$( grep SIZE= $TEMP | cut -f2- -d= )
		title=$( grep TITLE= $TEMP | cut -f2- -d= )
#		description=`grep -v ZZSKIPZZ $TEMP`
		description=$( tail -n +3 $TEMP )

#		echo DBG: title= $title
	    fi
#description=`(echo -n ZZSKIPZZ ; identify -format "%c" "$file" ) |grep -v ZZSKIPZZ`
#title=`identify -format "%c" "$file"|head -1`
	    
	    if [ "$title" = "" -o "$title" = " " ] ; then
		title=""
		if [ "$date" ] ; then title="$date ";
		    title="$title$name"
		fi
	    fi
	    
	    if [ "$txt" ] ; then
		title=`head -1 "$txt"`
		description=`(echo -n ZZSKIPZZ ; cat "$txt") | grep -v ZZSKIPZZ`
	    fi
	    
#	    echo title="\"$title\"" | replace "\`" "\\\`" > .medium/"$file".cache
	    echo title="\"$title\"" | sed -e 's/`/\\`/g' > .medium/"$file".cache
#	    echo description="\"$description\"" | replace "\`" "\\\`" >> .medium/"$file".cache
	    echo description="\"$description\"" | sed -e 's/`/\\`/g' >> .medium/"$file".cache
	    echo date="\"$date\"" >> .medium/"$file".cache
	    echo SIZE="$SIZE" >> .medium/"$file".cache
	else
	    . .medium/"$file".cache
	    echo '(cached)'
	fi

	[ "$ask_comment" ] && comment "$file"

	
	if [ $filetype == image -o $filetype == video ] ; then
	    medium=`dirname "$realfile"`/$MEDIUM/`basename "$realfile"`
	    
	    if [ "$realfile" != "$file" -a -e "$medium" ] ; then
		echo "$medium -> $MEDIUM/$file"
		if [ "${medium:0:1}" == '/' ] ; then
		    ln -sf "$medium" $MEDIUM/"$file"
		else
		    ln -sf ../"$medium" $MEDIUM/"$file"
		fi
	    elif [ "$file" -nt $MEDIUM/"$file".jpg ] ; then
		echo Creo il file $MEDIUM/"$file".jpg
		convert -geometry "$MEDIUM_GEOMETRY" $file "$MEDIUM/$file.jpg"
	    fi
	    
	    small=`dirname "$realfile"`/$SMALL/`basename "$realfile"`
	    
	    if [ "$realfile" != "$file" -a -e "$small" ] ; then
		echo "$small -> $SMALL/$file"
		if [ "${small:0:1}" == '/' ] ; then
		    ln -sf "$small" $SMALL/"$file"
		else
		    ln -sf ../"$small" $SMALL/"$file"
		fi
	    elif [ "$file" -nt $SMALL/"$file".png ] ; then
		echo Creo il file $SMALL/"$file".png
		convert -size "$SMALL_GEOMETRY" -geometry "$SMALL_GEOMETRY" $file $SMALL/"$file".png
	    fi
	fi
	
	OUTOUT="$MEDIUM"/"$file".html
	
	echo > "$OUTOUT"
	cat <<EOF >> "$OUTOUT"
<html>
<body>
<h1>$title</h1>
EOF
	
	echo "<p>" >> "$OUTOUT"
	echo "<a href=\"../$REALOUT\">$UP</a> " >> "$OUTOUT"
	if [ "$prev" ] ; then
	    echo "<a href=\"../$MEDIUM/${prev}.html\">$LEFT</a> " >> "$OUTOUT"
	else
	    echo "$LEFT" >> "$OUTOUT"
	fi
	
	if [ "$next" ] ; then
	    echo "<a href=\"../$MEDIUM/${next}.html\">$RIGHT</a> " >> "$OUTOUT"
	else
	    echo "$RIGHT" >> "$OUTOUT"
	fi
	
	echo "</p>" >> "$OUTOUT"
	
	if [ $filetype == image -o $filetype == video ] ; then
	    echo "<img src=\"../$MEDIUM/$file.jpg\"><br>" >> "$OUTOUT"
	fi
	
	echo "<pre> $description </pre>" >> $OUTOUT
	
	echo "<p>($filetype: <a href=\"../${realfile}\">$file</a>, dim=$SIZE, data: "$( stat "$realfile" | grep "^Modify:" | cut -f2- -d' ' | cut -f1 -d. )")</p>" >> $OUTOUT
	
	
	cat <<EOF >> "$OUTOUT"
</body>
</html>
EOF
	
#SIZE=`identify -format "%wx%h" "$SMALL/$file"`
#echo "<a href=\"$OUTOUT\"><img width=${SIZE//x*} height=${SIZE//*x} src=\"$SMALL/$file\"></a>&nbsp;<strong>$title</strong><br>" >> $OUT
	
	img="[$filetype]"
	if [ $filetype == image -o $filetype==video ] ; then
	    img="<img src=\"$SMALL/$file.png\" align='center'>"
	fi
	

	if [ "$contacolonne" -eq 1 ]
	    then
	      echo "<tr>"  >> $OUT
	fi


	echo "<td><div align='center'><a href=\"$OUTOUT\">$img<div></a>" >> $OUT
	
#	echo "&nbsp;<strong>$title</strong> (<a href='$file'>$file</a>)</td>" >> $OUT
	
	if [[("$contacolonne" -eq "$NUMCOLONNE") ||( -z $next) ]]
	 then   
	    echo "</tr>"  >> $OUT
	    contacolonne=1
	 else
	contacolonne=$(($contacolonne+1))
	fi
	
    fi
    
    prev="$file"
    file="$next"
    filetype="$nextfiletype"
    
done

if [ -f index.txt ] ; then
  echo "<pre>" >> $OUT
  (echo -n ZIZZUZ; cat index.txt) | grep -v ZIZZUZ >> $OUT
  echo "</pre>" >> $OUT
fi



cat <<EOF >>$OUT
</table>
<p>(directory: ${PWD##*/})</p>
</body>
</html>
EOF

mv $OUT $REALOUT
