#!/bin/sh
#
# Internal ID & Revision:
# $Id: goscan.sh,v 1.3 2010/05/19 07:27:11 smurphy Exp smurphy $
# $Revision: 1.3 $
#
# Documentation: script that uses a scanner to scan various documents
# and combines these to show up as one only PDF file. Works with
# epson scanners that have a SCAN button on them
#
# Required packages.
# Ubuntu: sane, sane-utils, libtiff-tools

# Catch Programm Version
SVER="$Revision: 1.3 $"

PROGNAME=`basename $0 .sh`
LockFile=${HOME}/${PROGNAME}..LOCK

# Configurable section - adds informations to the PDF document.
Author="Author Name"
Title="" # Defaults to the filename if empty
Subject="Subject for the scan"
Keywords="Add keywords here" # Could be the address
dpi=180

##############################################################################
# Nothing to change below
##############################################################################
#
#
errors() {
##DOC: The errors Function is called to control the exit status.
#
: ${errlvl:=9}
: ${MSG:="No Error message - Probably user interruption"}
if [ $errlvl -gt 0 ] ;
    then
    if [ $errlvl = 15 ] ;
    then
        echo -e "WARNING: $MSG"
    else
        #Usage
        echo -e "\a"
        echo "FATAL:  An error occured in \"${PROGNAME}(${FUNCTION})\". Bailing out..."
        echo -e "ERRMSG: $MSG"
        echo
	Unlock $FLock
	rm -f $tmpIPList $tmpInfList
        exit $errlvl
    fi
fi
} # errors Function
#
#
##############################################################################
#
# Lockfile Generation
Lock() {
# Lockfile to create
tolock="$1"
Action="$2"
#
# Lock file if lockfile does not exist.
if [ -s $tolock ]
then
    # If we have provided a second Var, set Exit status using  it.
    if [ ! -n "$Action" ]
    then
	# Oops, we  found a lockfile. Loop while checking if still exists.
	while [ -s $tolock ]
	do
	    sleep 5 ;
	done
	# write PID into Lock-File.
	echo $$ > $tolock
    else
	Pid="`cat $tolock`"
	Exists="`ps auxw | grep \" $Pid \" | grep -c $PROGNAME`"
	if [ $Exists = 1 ]
	then
	    echo "\"$PROGNAME\" already running. Exiting..."
	    exit $Action
	else
	    echo "Found stale lockfile... Removing it..."
	    rm -f $tolock
	    errlvl=$?
	    errors
	    echo $$ > $tolock
	fi
    fi
else
    # Lock followup DB.
    echo $$ > $tolock
fi
} # Lock
#
##############################################################################
#
Unlock(){
# Name of Lockfile to unlock
unlock="$1"
# Unlock the file.
if [ -s $unlock ]
then
    PID=$$
    if [ "`cat $unlock`" != "$PID" ]
    then
        echo "Problem, Wrong lock-file PID. This shouldn't happen"
    else
        # Removing Lockfile
        rm -f $unlock
    fi
fi
#
} # Unlock
#
#
##############################################################################
#
WaitIfLock(){
### What file to chack against
iflock=$1

### Lock Sites File as long as it is used...
if [ -s ${iflock} ]
then
    Pid="`cat ${iflock}`"
    ### Not 100% sure, but should work most of the time 
    Exists="`ps auxw | grep -c \" $Pid \"`"
    if [ $Exists != 0 ]
	    then
		Testing="1"
		### As long as the Process is active
		while [ $Testing != 0 ]
		do
		    ### Sleep 5 Seconds
		    sleep 5 ;
		    ### Check if still active
		    Exists="`ps auxw | grep -c \" $Pid \"`"
		    let count="( $count + 1 )"
		    ### After 50secs, exit from loop. The Process 
		    ### seems to have died or does not know what to do.
		    [ $count -gt 10 ] && Testing=0
		    [ $Exists != 0 ] && Testing=0
		done
		if [ $Exists = 0 ]
		then
		    ###This is really bad ... The Process is still running. 
		    ### Exit the Program.
		    $MSG="Programm $PROGNAME ($Pid) ran for 50 more seconds. Emergency exit !"
		    errlvl=1
		    errors
		fi
    fi
fi
} # WaitIfLock
#
##############################################################################


# Lock the Process
Lock $LockFile 1

for prog in scanimage tiff2pdf tiffcp
do
  nprog=`which $prog`
  if [ -z $nprog ]
      then
      MSG="Missing programm \"$prog\" for $PROGNAME to run. Bailing out !"
      errlvl=1
      errors
  fi
done

# Extract the existing scanner
Scanner=`scanimage -f %d`
if [ -n "$Scanner" ]
then
    Scanname=`scanimage -f "Scanner number %i device %d is a %t, model %m, produced by %v "`
    ScannId=$Scanner
    echo ">>> Found $Scanname"
    export SANE_DEFAULT_DEVICE=$ScanId
else
    MSG="No Scanner detected - bailing out"
fi

DATE=`date +%Y%m%d`
echo
echo ">>> Enter a filename for the output document,"
echo -n "    Default [${DATE}_Scanned_Document]: "
read docname

# Set default
[ -z "$docname" ] && docname="${DATE}_Scanned_Document"
# Fallback to file-name.
[ -z $Title ] && Title=$docname

echo
echo ">>> Existing scanning modes"
echo "    1 Color (default)"
echo "    2 Grayscale"
echo "    3 Binary (Black/White)"
echo -n "    Plase enter your choice: "
read choice

[ -z "$choice" ] && choice=1

echo "Choice is: $choice"
echo
echo ">>> Activating scanner..."
echo ">>> Place the document to be scanned on the scanner "
echo "    and push the scanner button"
echo "    Hit Ctrl-C Twice to stop the process !"
echo

if [ $choice = 1 ]
then
    echo ">>> Scanmode: Color"
    # Color
    scanimage  -d $ScannId --batch=out%d.tif --batch-start=11 --format=tiff --mode=color --wait-for-button --resolution=$dpi
elif [ $choice = 2 ]
then
    echo ">>> Scanmode: Grayscale"
    # Grayscale
    scanimage  -d $ScannId -p --batch=out%d.tif --batch-start=11 --format=tiff --mode=gray --wait-for-button --resolution=$dpi
elif [ $choice = 3 ]
then
    echo ">>> Scanmode: Binary (Black & White)"
    # Black / White
    scanimage  --device-name=$ScannId --batch=out%d.tif --batch-start=11 --format=tiff --wait-for-button --resolution=$dpi
else 
    MSG="Invalid choice. Baling out."
    errlvl=1
    errors
fi

# Create one big TIFF
echo ">>> Combining TIFF images..."
MSG="Combining documents failed"
tiffcp -c lzw out*.tif document.tif
errlvl=$?
errors

# Create PDF
echo ">>> Creating PDF document..."
MSG="Creating PDF Document failed"
tiff2pdf -z document.tif -o document.pdf -a "$Author" -t "$Title" -s "$Sibject" -k "$Keywords"
errlvl=$?
errors

#echo "Optimizing PDF..."
#MSG="Optimizing PDF Document failed"
#pdfopt document.pdf ${docname}.pdf
#errlvl=$?
#errors

#echo "Renaming PDF..."
MSG="Renaming PDF Document failed"
cp document.pdf ${docname}.pdf
errlvl=$?
errors

MSG="Cleaning temporary tif files failed"
rm -f *.tif
errlvl=$?
errors

MSG="Cleaning temporary document.pdf files failed"
rm document.pdf
errlvl=$?
errors


### unlock this shell script.
Unlock $LockFile
