All pastes #584691 Raw Edit

printestimate v3

public shellscript v1 · immutable
·published 2007-06-22 21:47 UTC
rendered paste body
#!/bin/bash -x# Simple script to convert a specified postscript file into a PDF document# and place it in a location that is shared by the Samba server.# # Arguments:#   1st - The name of the spool file#   2nd - $HOME directory of the submitting SAMBA user	#   3rd - the destination print queue#   4th - 9th = the print job name### John Bright, 2001, jbright@winfordeng.com# Modification for GWI estimate print processing on 2/23/2006## This particular iteration of the printpdf script is used to take the modified# Imaginera report (the .QRP file) that prints the estimate report with a header # page with database fields and values and atrips that first page from the print job.# Pages two through the end of the document are then converted to a PDF file and also# sent to a print queue for printing with the information from the "cover/header" sheet# sent to a control file that will be used by other processes to file the PDF and # parsed data from the header page into an SQL database.## This allows GWI to maintain a record/copy of all estimates that are printed without# losing previous itterations.## [update the following paragraph to document the eventual methodology]# We will create the pdf into a temporary file based upon the current date and time.# After we are finished, we"ll rename it to a file with the same date, but ending# in .pdf.  We do this because if a user tries to open a PDF that is still being written,# they will get a message that it is corrupt, when it is actually just not done yet.### added 6/30/2006 ####Before we decide to process this file, let"s make sure that it is an estimate.# we do this by checking the printjob name for the title of the appropriate report.# The report file that was modified is: fcce1248.qrp so we will look for that.#First we will need to assemble the jobname variable from the parameters 4 through 9.# The reason why we have to assemble the variable is because some job names will have spaces# in them and will appear as MULTIPLE variables.##Disableing the JOBNAME section because we KNOW that Imaginera uses the QRP name as it"s ## print job description.### - ##go ahead and assign the fourth paramter "$4" to the JOBNAME variable### - #JOBNAME=$4### - #### - ##check to see if we have more than four variables by checking to see if### - ## the total number of variables ( $# ) is greather than 4.### - #if [ "$#" -gt 4 ] ; then### - #  #Start a loopy sequence (man seq) and start with the fifth variable and go until### - #  #you reach the total number of variables as listed by "$#"### - #  for PART in $(seq 5 "$#") ; do### - #    #I don"t understand the eval line...but it works.  SO until I need to change it, I"ll just use it.### - #    eval PART=\$${PART}### - #    #tack on the next paramater onto JOBNAME### - #    JOBNAME="$JOBNAME ${PART}"### - #  done### - #fi### - #### - ##echo the printjob name and grep for the desired string and if the string is NOT found### - ## then let"s just send this job straight to the printer because it"s not an estimate.### - #if ! echo "$JOBNAME" | grep -iq "fcce1248" ; thenfunction createdest ()  {# Be sure the Directory in which to place the output# exists and is writable by the user if [ ! -e "$DESTDIR" ] ; then  mkdir -pm 770 "$DESTDIR"	#create the directoryfi	# end of the loop that creates the destination directory if it doesn"t exist}function errorMail ()  {          # mail to admin on error conditions  SUBJECT="GWI: print estimate/quote error:"  TO=(netadmin@gwiinc.com)  # sending the message#  echo -e "$ERRTEXT | mail -s $SUBJECT "  echo -e "$ERRTEXT" | smtp=mail mail -s "$SUBJECT"  $TO  echo "sent, mail exitcode $?"}function print () {	# Issue the print command to the originally intended printer and use	#  the original unprocessed filename.	lpr -P $3 $1	#now exit this script because we are done.	exit}function quote () {#Start by making sure that the destination directory exists by running the # createdest (create destination) functioncreatedest#convert the job to a temporary text file/usr/bin/ps2ascii $1 $1-$DATE.ascii#extract the estimate number from the temporary text fileESTNUM=`grep "Specification Number" $1-$DATE.ascii  | cut -f2 -d: |sed s#\ ##g | cut -b 1-5`#Check to see if there is more than one spec number found on the quote by checking the# length of the ESTNUM variable.  If it is, then reset ESTNUM to equal "combo"if [ "`expr length \"$ESTNUM\"`" -gt "7" ] ; then 	ESTNUM="combo"fi#delete the temporary text filerm $1-$DATE.ascii#convert the spool job to a PDFps2pdf $1 $OUTDIR/$1-$DATE.temp########################################################################## save the pdf to the estimate directory but use the estimate number 	## retrieved from the temporary text file				###########################################################################Assign a variable we can use to manipulate should the destination file already existsQUOTENUM=$ESTNUM-quote#Build the name of the destination fileFILE="$FPREFIX$QUOTENUM.pdf"#set some checking variables to be used should the name exist or in case of a problemUNIQUE=2RUNAWAY=1#Check to see if the spool file has been deleted yet. If not, continue the do loop# This prevents us from overwriting an existing file -- we are looking for a unique namewhile [ -f $OUTDIR/$1 ] ; do 	if [ -f "$DESTDIR$FILE" ] ; then			QUOTENUM=${ESTNUM}-quote-$UNIQUE ; UNIQUE=$(( $UNIQUE + 1 ))		#update the filename			FILE="$FPREFIX$QUOTENUM.pdf"		#close this if loop and return to the begining of the do loop		#otherwise	else		#if an error occurs that keeps the original file from being moved or deleted		# then this printestimate script will run in an infinite loop causing the log		# files to fill up the disk space and causing runaway CPU usage.		# We have runaway set to 10 itterations		if [ $RUNAWAY -gt 10 ] ; then			#possible Critical error..			echo "Print job terminated - can't remove original spool file" > $2/$DESTDIR/CRITICAL-STOP-$DATE.TXT			exit		else			RUNAWAY=$(( $RUNAWAY + 1 ))		fi 		#move the temporary PDF  file to the destination folder using the now 		# verified unique name		echo "PREPARING TO MOVE THE FILE...MOVING MOVING MOVING!"		mv "$OUTDIR/$1-$DATE.temp" "$DESTDIR$FILE"		#change the permissions		chmod 444 "$DESTDIR$FILE"		#Send the PDF to the printer ONLY if we know it got to its 		# destination directory properly.  This will help clue us into trouble		if [ -f $DESTDIR$FILE ] ; then			lpr -P $3 $1		else				#exit if it didn"t get there properly.			#set the text for errorMail			ERRTEXT="unable to put $DESTDIR$FILE in its place. Printing aborted"			#then run the errorMail function			errorMail			exit		fi		# Now remove the spool file thus ending the do loop from runing again.#		rm $1 #$OUTDIR/$1		mv $1 $1.keeper-quote	fi	#end the "If spool file exists" do loopdoneexit}function estimate  {##########################################################################  Star the printestimate processing now that we have determined that	##              this print job is indeed an estimate			###########################################################################Start by making sure that the destination directory exists by running the # createdest (create destination) functioncreatedest################################################## Begin the routine that parces the source file ## into an estimate pdf and its header PS page	##################################################	#extract the first "header" sheet	/usr/bin/psselect -q -p1 $1 $1-$DATE.ascii	#convert the entire PS to a PDF	ps2pdf $1 $OUTDIR/$1-$DATE.pdf	# then remove the first "header" page	ps2pdf -dFirstPage=2 $OUTDIR/$1-$DATE.pdf $OUTDIR/$1-$DATE.temp	#clean up after ourselves	rm $OUTDIR/$1-$DATE.pdf        #convert the header to a temporary ascii file        #a not-so-clean way to do it-> #ps2ascii $1-header $OUTDIR/$1-$DATE.ascii        /usr/local/bin/pstotext $1-$DATE.ascii > $OUTDIR/$1-$DATE.header        #remove the control characters from the extracted header sheet        sed s/[[:cntrl:]]//g < $OUTDIR/$1-$DATE.header > $1-$DATE.ascii	#clean up the temporary file created        rm $OUTDIR/$1-$DATE.header################################################## extract the information from the header page  ## and build an array..assign variables that we  ## will need					###################################################read in the header file and process each line into an Arraywhile read EACHLINEINFILE; do        #Assign each line into an array        VAR[$COUNT]="$EACHLINEINFILE"	COUNT=$(( $COUNT + 1 ))done < $1-$DATE.ascii#Clean up the header filerm $1-$DATE.ascii#let"s grab the spec_combo number from the header file.SPEC_COMBO=${VAR[1]} 	#the record"s spec_combo number#Variables that we don"t need but are left in/commented out for# documentation purposes##assign variables using our array -AND- while we are## at it...let"s strip out any single quotes so that they don"t accidently## get interpreted later on and close an echo early.##"SPEC_DESCR=`echo ${VAR[2]} | tr -d \'`  #the spec description"##"CUSTOMER=`echo ${VAR[3]} | tr -d \'`   #the customer name"##"PROD_DESCR=`echo ${VAR[4]} | tr -d \'` #the product description"#Set the PRINTUSER variable to equal the name of the user"s HOMEDIRECTORY# without the complete path.  I could have attempted to use %u for unix user, but#this ensures the data I wantPRINTUSER=`basename $2`			################################################## Move the PDF into the proper location, send 	## it to the printer and file the information 	## into the sql database.			###################################################bob#Assign a variable we can use to manipulate should the destination file existsCHKSPEC_COMBO=$SPEC_COMBO#Build the name of the destination fileFILE="$FPREFIX$CHKSPEC_COMBO.pdf"#set some checking variables to be used should the name exist or in case of a problemUNIQUE=2RUNAWAY=1#Check to see if the spool file has been deleted yet. If not, continue the do loop# This prevents us from overwriting an existing file -- we are looking for a unique namewhile [ -f $OUTDIR/$1 ] ; do 	if [ -f "$DESTDIR$FILE" ] ; then			CHKSPEC_COMBO=${SPEC_COMBO}-$UNIQUE ; UNIQUE=$(( $UNIQUE + 1 ))		#update the filename			FILE="$FPREFIX$CHKSPEC_COMBO.pdf"		#close this if loop and return to the begining of the do loop		#otherwise	else		#if an error occurs that keeps the original file from being moved or deleted		# then this printestimate script will run in an infinite loop causing the log		# files to fill up the disk space and causing runaway CPU usage.		# We have runaway set to 10 itterations		if [ $RUNAWAY -gt 10 ] ; then			#possible Critical error..			echo "Print job terminated - can't remove original spool file" > $2/$DESTDIR/CRITICAL-STOP-$DATE.TXT			exit		else			RUNAWAY=$(( $RUNAWAY + 1 ))		fi 		#move the temporary PDF  file to the destination folder using the now 		# verified unique name		echo "PREPARING TO MOVE THE FILE...MOVING MOVING MOVING!"		mv "$OUTDIR/$1-$DATE.temp" "$DESTDIR$FILE"		#change the permissions		chmod 444 "$DESTDIR$FILE"		#Send the PDF to the printer ONLY if we know it got to its 		# destination directory properly.  This will help clue us into trouble		if [ -f $DESTDIR$FILE ] ; then			lpr -P $3 $DESTDIR$FILE		else				#if it didn"t get there properly, don"t bother running the			# SQL command			ERRTEXT="Unable to add an estimate to the SQL database for $DESTDIR$FILE"			errorMail			exit		fi		#Let"s prepare the UNC path to the file so that user can open the file		# when the search page shows the link.  Using the UNC path		# (\\server\path\to\file.pdf) prevents the hard coding of a physical		# drive mapping which COULD potentially be changed or not mapped.		#Strip off the /home part of the path so that we can replace it		FILELINK=`echo $DESTDIR$FILE | cut -b  6-`		#Add in the server name where the PDF is stored		FILE_LINK="//gwifs$FILELINK"		# Now remove the spool file thus ending the do loop from runing again.		rm $1 #$OUTDIR/$1		mv $1 $1.keeper-estimate			#########################################################		# Now the that PDF file is nicely stored away, let"s 	#		# call the SQL statement that will file the information #		# about this estimate into the sql database		#		#########################################################				#The ORIGINAL "go to the MS SQL database" ISQL ROUTINE#		#TODO check for successful ISQL entry and notify if it doesn"t succeed.#		#save missed submissions into a file somewhere#		echo "INSERT INTO esttable (date,time,spec_combo,spec_descr,customer,prod_descr,file_link,printuser) VALUES ('$DBDATE','$DBTIME','$SPEC_COMBO','$SPEC_DESCR','$CUSTOMER','$PROD_DESCR','$FILE_LINK','$PRINTUSER')" | /usr/local/bin/sqlprompt		#** PERL routine **		# The NEW method is to use the local postgres database on gwifs along		# with a PERL script				# calling the estimate pl with three parameters		# 1. the absolute path to the header page		# 2. the UNC pathname where the file is stored		# 3. the name of the user who printed the estimate		perl /usr/local/bin/estimates.pl $1-$DATE.ascii $FILE_LINK $PRINTUSER	fi	#end the "If spool file exists" do loopdone}#Let"s start setting some variables.DATE=`date +%b%d-%H%M` #seconds were removed...that kind of granularity isn"t neededYEAR=`date +%Y`MON=`date +%m`#Set the file prefix variable. This will be prepended to the spec_numberFPREFIX=`date +%d-%H.%M-`#set the destination directory name DESTDIR=/home/sys/data/estimates/$YEAR/$MON/#Assign the OUTDIR variable to equal where the print job will goOUTDIR=/tmp#Test the $4 variable to see if it equals FCCE1248.QRP (an estimate)if [ "$4" == "FCCE1248.QRP" ] ; then	#run the estimate function	estimate $1 $2 $3 $4	exitelif [ "$4" == "FQUO1248.QRP" ] ; then	#run the quote function	echo "IT IS A QUOTE...preparing to run the QUOTE function"	quote $1 $2 $3	exitelse	#run the print function	print $1 $2 $3	exitfi