#!/bin/bash
#
# images.sh - script to look through files in latest that have not yet
#             been copied to their individual scans folder and link them
#             there, then go through the individual scans folder and make
#             low-resolution jpeg image files for any tiff images that
#             do not already have them. These image files are useful
#             for visually scanning data quickly using "animate".
#
# author: richard.t.jones at uconn.edu
# version: may 28, 2014
#
# notes:
# 1. The code current recognizes as a scan log any file in the "latest"
#    folder that does not have an extension. A directory with this
#    name is created alongside latest, and files from latest that 
#    have this name as a base are linked from latest to their
#    scan folder.
# 2. The latest folder is set up to be purged of old files from time
#    to time, so that the images directory on the CHESS Andor1 machine
#    does not get overfilled.  Make sure before deleting any files on
#    Andor1 that they have been linked to their scan directories, or
#    the rsync process will delete them from latest.

for scanlog in `ls latest | grep -v tiff$`; do
    if echo $scanlog | grep -q '\.'; then
        continue
    elif [[ "$scanlog" == "agent" ]]; then
        continue
    fi
    if [[ ! -d $scanlog ]]; then
        echo creating new scan diretory $scanlog
        mkdir $scanlog
    else
        echo checking existing scan directory $scanlog
    fi
    rm -f $scanlog/$scanlog
    find latest -type f -links 1 -name "$scanlog*" -exec ln {} $scanlog/ \;
    for tiff in `ls $scanlog/*.tiff`; do
        jpg=`echo $tiff | sed 's/tiff$/jpg/'`
        if [[ ! -r $jpg ]]; then
            convert -resize 25%x25% -normalize $tiff $jpg
        fi
    done
done
