#!/bin/bash
# -*- coding: utf-8 -*-

# stamper [-w <width>] [-o <dest folder>] [-f <cmd file>] [<bild> <text> [<autor>|x [<jahr>|x]]]
#
# CmdFile-Zeile: [-w <width>] <bild> <text> [<autor>|x [<jahr>|x]]
#					  <jahr> ist mit dem aktuellen Jahr vorbesetzt
#					  Fehlende Parameter haben den letzten Wert
#					  x löscht den vorherigen Wert des Parameters

stamp='stempel'

destfolder='./'
JAHR="© $(date +%Y)"
AUTOR=""

function stamper() {
	# Parameter: [-w width] bild text [autor [jahr]]
	#                       $1   $2    $3     $4
	
	local src="$1"
	local tmpsrc=""
	local dest=""
	local OPTIND=1
	local rmSrc=true
	while getopts ":w:" option
	do
		case "${option}" in
			w )	src="/tmp/$(eval basename \"$3\").tmp"
					tmpsrc="${src}"
					dest="$ofolder/$(eval basename \"$3\")"
					convert "$3" -resize "${OPTARG}" "${src}"
					;;
			* )	echo "invalid option '${option}': $1 $2 $3 $4 $5 $6"
		esac
	done
	shift $((OPTIND-1))
	if [ -z "$dest" ]
	then
		dest="$ofolder/$(eval basename \"$1\")"
		rmSrc=false
	fi
	
	if [ -n "$3" ]
	then
		AUTOR="$3"
		if [ -n "$4" ]
		then
			JAHR="© $4"
		fi
	fi
	if [ "x$3" == 'xx' ]
	then
		AUTOR=
		JAHR=
	fi
	if [ "x$4" = 'xx' ]
	then
		JAHR=
	fi
	TEXT="$2"
	
	# Bildmaße abfragen und entsprechende Version des Stempels auswählen
	local w=$(eval identify -format %w \"${src}\")
	local h=$(eval identify -format %h \"${src}\")
	local tmpstamp
	if [ $w -gt $h ]
	then
		tmpstamp="${stamp}-q.svg"
	else
		tmpstamp="${stamp}-h.svg"
	fi

	# Bildparameter substituieren
	cat "${tmpstamp}" | sed -e "s/\${JAHR}/${JAHR}/g" -e "s/\${AUTOR}/${AUTOR}/g" -e "s/\${ART}/${TEXT}/g" >"/tmp/${tmpstamp}"

	# Stempel skalieren
	inkscape -z -e "/tmp/${tmpstamp}.png" -w $w "/tmp/${tmpstamp}"

	# stempeln
	composite -gravity South "/tmp/${tmpstamp}.png" "${src}" "${dest}"
	
	# aufräumen
	rm "/tmp/${tmpstamp}" "/tmp/${tmpstamp}.png"
	if [ rmSrc ] && [ -n "${tmpsrc}" ]
	then
		rm "${tmpsrc}"
	fi
}


while getopts ":f:w:o:" Option
do
  case $Option in
	 f ) 	while read line								# cmd file
			do
				eval "stamper $line"
			done < $OPTARG
			;;
	 w )	w="-w $OPTARG"									# width
			;;
	 o )	destfolder=$OPTARG							# destination folder
			;;
	 * ) 	echo "undefined option: $Option"
			;;
  esac
done
shift $(($OPTIND - 1))

if [ ! -z "$1" ]
then
	stamper $w "$1" "$2" "$3" "$4"
fi

