#!/bin/bash
#
# Skript, das Rohdaten aus einem Verzeichnis in
# Jpeg wandelt und es automatisch in Datumsverzeichnisse
# einsortiert
#
# Will archive camera RAW Files into an dir-tree (date based),
# and convert it to JPEG
#
# Reiko Kaps <rek@ct.de> 2010

##################################################
# Foo and Bar
##################################################

##
# externe Programme, please check the pathes!
RCONV=/usr/bin/dcraw
CONV=/usr/bin/convert
EXIF=/usr/bin/exiv2

LANG=C

##################################################
# Functions
##################################################

##
# get Group for File/Dir
# only usefull with mv
getGroup()
{
    local VAR0=$(stat "$1" | grep Gid:)
    local VAR1=${VAR0##*/}
    echo ${VAR1%*)}
}

##
# create date based dir
mkDateDir()
{
  local NewDIR="$1"
  if [ ! -d "${NewDIR}" ]
  then
      echo "Creating archive dir ${NewDIR}"
      mkdir -p "${NewDIR}"
      # Permissions!!
      chmod 775 "${NewDIR}"
  fi
  return 
}

##
# convert to JPEG (and resize)
conv2jpeg()
{
    local ORGINAL="$1"
    local BASENAME=$(basename ${ORGINAL} .${SEXT}) 

    ## convert parameter, resize and quality
    if [ ! -z ${JPEG_QUAL} ]
    then
	CONV_OPT="-quality "${JPEG_QUAL}
    fi

    if [ ! -z ${MAX_SIZE} ]
    then
	CONV_OPT=${CONV_OPT}" -resize "${MAX_SIZE}
    fi
    
    ## save old JPEG, if exist
    if [ -r "${OUTDIR_BASE}/${DATEDIR}/${BASENAME}.jpg"  ]
    then
	mv --backup=t "${OUTDIR_BASE}/${DATEDIR}/${BASENAME}.jpg" "${OUTDIR_BASE}/${DATEDIR}/${BASENAME}-old.jpg"
    fi

    # copy exif informations
    if [ -e "${ORGINAL}" ]
    then
	echo "Converting $ORGINAL to JPEG ($BASENAME)"
	${RCONV} -c "${ORGINAL}" | ${CONV} - ${CONV_OPT} "${OUTDIR_BASE}/${DATEDIR}/${BASENAME}.jpg" || exit 1
	# echo ${EXIF} insert -l"${ORGINAL%/*}" -S.${SEXT} "${OUTDIR_BASE}/${DATEDIR}/"*.jpg
	${EXIF} insert -l"${ORGINAL%/*}" -S.${SEXT} "${OUTDIR_BASE}/${DATEDIR}/"*.jpg 2> /dev/null
    else
	echo "File ${ORGINAL} does not exists!"
    fi

    ## setting permissions
    chmod 664 "${OUTDIR_BASE}/${DATEDIR}/${BASENAME}.jpg"
    return
}

##
# Copy original to archive $DEST
copy2arch()
{
    local SOURCE="${1}"
    local SFILE=$(basename ${SOURCE})
    local DEST="${OUTDIR_BASE}/${DATEDIR}/${SFILE}"
    
    echo "Copying ${SOURCE} to ${DEST}"
    # Attribute sichern, falls moeglich:
    # bei mv bleiben die orginalrechte erhalten
    # mv --backup=t "$SOURCE" "$DEST" || exit 1
    cp --backup=t "$SOURCE" "$DEST" || exit 1
    
    # Workaround für mv
    # fix group-settings on moved file
    # set it to the group of the Archiv-Base-Dir (OUTDIR_BASE)    
    # chgrp $(getGroup "${OUTDIR_BASE}") "${DEST}"
    
    ## setting permissions
    chmod 664 "${DEST}"
    rm "$SOURCE"
    return
}

##
# Write PID-File for this session

createPID()
{
    [ ! -e "${PIDDIR}" ] && mkdir -p "${PIDDIR}" 
    touch "${PIDDIR}/${pname}-$$.pid" || exit 1
    return
}

removePID()
{
    [ -e "${PIDDIR}/${pname}-$$.pid" ] && rm "${PIDDIR}/${pname}-$$.pid"
    return
}

##
# common help etc
hilfe()
{
    echo "usage: iRawConv2 -i INPUTFILE -d "
    echo "Options: -i ....  File to process"
    echo "         -o ....  Archive Base Dir"
    echo "         -d ....  dont delete source file"
    echo "         -q ....  JPEG Quality for converted images (Default: 100)"
    echo "         -s ....  Size for converted images (Default: 1200)"
    echo "         -h ....  this help"
    return
}

################################################
# MAIN
################################################

##
# Optionen und Parameter
while getopts ":hi:o:q:s:e:" opt; do
    case $opt in
	i)
	    INFILE="${OPTARG}"
	    ;;
	o)
	    OUTDIR_BASE="${OPTARG}"
	    ;;
	q)
	    JPEG_QUAL=${OPTARG}
	    ;;
	s)
	    MAX_SIZE=${OPTARG}
	    ;;
	e)
	    SEXT=${OPTARG}
	    ;;
	h)
	    hilfe
	    ;;
	\?)
	    hilfe
	    echo "Invalid option: -${OPTARG}" >&2
	    exit 1
	    ;;
	:)
	    echo "Option: -${OPTARG} requires an argument." >&2
	    exit 1
	    ;;
    esac
done


# check minimal requirements

if [ ! -z ${INFILE} -a -e "${INFILE}" ]
then
    if [ ! -z ${OUTDIR_BASE} -a -d "${OUTDIR_BASE}" ]
    then
	if [ "$SEXT" = "" ] 
	then
	    echo "You must set one File-Extensions via option -e"
	    exit 1
	fi
    else
	echo "Sorry, the base output directory (-o) is wrong or not set."
	exit 1
    fi
else
    echo "Sorry, neither the path of the input file (-i) is wrong or not set."
    exit 1
fi

##
# simple extension test
EXT=${INFILE##*.}
if [ "${EXT}" != "${SEXT}" ] 
then
  echo "Wrong File-Extension, leaving it untouched, exiting!"
  exit 1
fi

##
# wait until previous processes end, create PIDFile
# and register trap function
pname=$(basename $0)
PIDDIR=/var/tmp/$pname
createPID
trap 'removePID' EXIT INT TERM

##
# creating target directory
DATEDIR=$(${EXIF} pr "${INFILE}" | grep "^Image\ timestamp" | awk '{ print $4; }' | tr : -)
mkDateDir "${OUTDIR_BASE}/${DATEDIR}"

##
# converting source file to JPEG
conv2jpeg "${INFILE}"

##
# move source file to target 
copy2arch "${INFILE}" 


exit 0

