#!/bin/sh
# Resize/Wartermarking/committing to repo
# Usage:
#	$0 [Options]
# Call this script on jpeg files directory

myname=`basename $0`
mybase=${myname%.*}
tmpdir=${TMPDIR:-/tmp}/$mybase
logodir=$tmpdir/logo
repodir=$tmpdir/photorepo
year=`gdate -d '3 months ago' +%Y`
sz=1280
pwd=$PWD
NL="
"
ulimit -c 0

# This should be obtained from some configuration file
imgurlbase=https://www.yatex.org/gitbucket/KoekiBrandingPJ/photorepo/raw/master/$year

finalize() {
  test -w "$pwd" && cd $pwd/.. && rm -rf $pwd
}
trap finalize INT QUIT TERM EXIT HUP

test -d $repodir || test -w $repodir || {
    echo "Please prepare repository directory before hand in $repodir"
    exit 2
  }

while getopts s:y:l: i; do
  case $i in
    s)	sz=$OPTARG ;;
    y)	year=$OPTARG ;;
    l)	lat=${OPTARG%,*}
	lon=${OPTARG#*[, ]}
	#if [ "$lat" -lt 20 -o "$lat" -gt 50 \
	#	    -o "$lon" -lt 120 -o "$lon" -gt 150 ]; then
	#  lon="" lat=""		#  Is not Japan, maybe
	#fi
  esac
done
shift $((OPTIND - 1))
imgdir=$repodir/$year

{			# Pipe to logger below
  urls=""
  echo `date`: Start job
  (cd $imgdir; git pull)
  logo=$logodir/watermark.png
  for f in *.jpg; do
    if [ -n "$lat" -a -n "$lon" ] && type exiftool >/dev/null 2>&1; then
      exiftool -gpslatitude="$lat" -gpslatitudeRef=N \
	       -gpslongitude="$lon" -gpslongitudeRef=E $f
    fi
    mogrify -resize ">${sz}x${sz}" $f
    if [ -s $logo ]; then
      composite -dissolve 50% -gravity SouthWest $logo $f $imgdir/$f
    else
      cp $f $imgdir
    fi && urls="$urls{{$imgurlbase/$f}}$NL"
  done && (
  cd $imgdir
  git add .
  git commit -m "AutoCommit via $myname at `date '+%F %T'`"
  git push
  echo URLs="$urls"
  echo `date`: Finish job
  )} >> $tmpdir/logfile 2>&1
echo "$urls" | tee -a $tmpdir/logfile
