#!/bin/sh

# Helper script for Simple Folder Gallery plugin. This accepts one or more directory names and processes the
# images and thumbnails for proper sizing and also generates the title.txt, date.txt & hd.txt files that the
# plugin expects. The user can also create a key.txt file containing the filename of the "album cover" otherwise
# the plugin will simply use the first file found.

# CHANGE obase TO THE DIRECTORY WHERE YOUR TOP LEVEL photos DIRECTORY IS. THAT MIGHT BE SOMETHING LIKE:
# /home1/c430947/public_html/wp/photos OR /home3/c212725/public_html/photos DEPENDING ON YOUR SERVER SETTINGS

obase="/storage/web/bery/wp/photos"

sdir=`pwd`

while [ "$1" != "" ] ; do
  if [ -d "$1" ] ; then
    echo Processing $1
    title="$1"
    dname=`echo $1 | sed 's/ /_/g' | tr '[A-Z]' '[a-z]'`
    target=$obase/$dname
    uniq=0
    while [ -d $target ] ; do
      uniq=`expr $uniq + 1`
      echo -n $target already exists,
      target=$obase/${dname}_${uniq}
      echo try $target ...
    done
    mkdir -p "$target/images" "$target/thumbnails"
    cd "$1"
    hasJPG=`ls *.JPG 2> /dev/null`
    if [ "$hasJPG" != "" ] ; then
      for i in *.JPG ; do
        echo -n .
        oname=`basename "$i" .JPG`.jpg
        djpeg "$i" | pnmscale -xysize 120 67 | cjpeg -optimize -quality 80 > "$target/thumbnails/$oname"
        djpeg "$i" | pnmscale -xysize 1920 1080 | cjpeg -optimize -quality 90 > "$target/images/$oname"
      done
    fi
    hasjpg=`ls *.jpg 2> /dev/null`
    if [ "$hasjpg" != "" ] ; then
      for i in *.jpg ; do
        echo -n .
        oname=`basename "$i" .jpg`.jpg
        djpeg "$i" | pnmscale -xysize 120 67 | cjpeg -optimize -quality 80 > "$target/thumbnails/$oname"
        djpeg "$i" | pnmscale -xysize 1920 1080 | cjpeg -optimize -quality 90 > "$target/images/$oname"
      done
    fi
    day=`/bin/ls -l --time-style=+%Y%m%d "$i" | awk '{ print $6 }'`
    echo $title > "$target/title.txt"
    echo $day > "$target/date.txt"
    echo "hd" > "$target/hd.txt"
    ddate=`echo $1 | grep "^2[0-9][0-9][0-9]-[0-9][0-9]"`
    if [ "$ddate" != "" ]; then
      echo $ddate | awk '{ printf("%s%s01\n",substr($1,1,4),substr($1,6,2)); }' > "$target/date.txt"
      #echo $ddate | awk '{ printf("%s\n",substr($1,9)); }' > "$target/title.txt"
    fi
    echo .
    cd "$sdir"
  else 
    echo "Error: $1 is not a directory"
  fi
  shift
done

