#!/bin/sh
#nsdataexport
PGNAME="nsdataexport"
PGDESC="Data export process"
LOGFILE="/usr/ns/log/nsdataexport.log"
FILELIST="/tmp/"$PGNAME-$$-FILELIST".tmp"
DELETELIST="/tmp/"$PGNAME-$$-DELETELIST".tmp"
PSQLTIMEOUT=5
usage () {
	echo "$PGNAME: $PGDESC"
	echo
	echo "Usage: $PGNAME [options...] -G#"
	echo "where -G #          Data export group number"
	echo "and [options...] are:"
	echo " -d #               Debug display level."
	echo " -help|--help       Display this help."
	echo " -q|-quiet|--quiet  Do not display activity messages."
	echo " -s #[smhd]         Display interval (Default: 0)"
	echo " -te D-T            Stopping time for data filing (Default: now)"
	echo " -ts D-T            Starting time for data filing (Default: 01/01/1980)"
	echo "     D-T is         MM/DD/YYYY-HH:MM:SS where / can be [/+-., ] - or : are any non digit"
	echo "                    YYYY/MM/DD-HH:MM:SS where / can be [/+-., ] - or : are any non digit"
	echo "                    +#[smhd...] Time offset added to current time"
	echo "                    -#[smhd...] Time offset subtracted from current time"
	echo " -version|--version    Display program version."
}
if [ "$1" = "-help" -o "$1" = "--help" ]; then
	usage
	exit 0
fi

if [ "$1" = "-version" -o "$1" = "--version" ]; then
	echo $(nsversion)
	exit 0
fi

# Time stamp output and append to log file.
# Display on console if not quiet.
timestampLogFile() {
NotQuiet=${1:-false}
if [ $Quiet = "true" -a $NotQuiet = "false" ]; then
	sed -e "sz^z$(date '+%m/%d/%Y %H:%M:%S') z" >>$LOGFILE
else
	sed -e "sz^z$(date '+%m/%d/%Y %H:%M:%S') z" | tee -a $LOGFILE
fi
}

# Get command arguments.
COMMANDLINE="$0 $*"
GroupNumber=""
Debug=0
Quiet="false"
DisplayInterval=""
StartTime=""
StopTime=""
while test $# -gt 0; do
	arg="$1"
	if [ "$arg" = "-G" ]; then shift; GroupNumber="$1"
	elif [ "${arg#-G}" != "$arg" ]; then GroupNumber="${arg#-G}";
	elif [ "$arg" = "-d" ]; then shift; Debug=$1
	elif [ "${arg#-d}" != "$arg" ]; then Debug="${arg#-d}";
	elif [ "$arg" = "-q" -o "$arg" = "-quiet" -o "$arg" = "--quiet" ]; then Quiet="true";
	elif [ "$arg" = "-s" ]; then shift; DisplayInterval=$1
	elif [ "${arg#-s}" != "$arg" ]; then DisplayInterval="${arg#-s}";
	elif [ "$arg" = "-te" ]; then shift; StopTime=$1
	elif [ "${arg#-te}" != "$arg" ]; then StopTime="${arg#-te}";
	elif [ "$arg" = "-ts" ]; then shift; StartTime=$1
	elif [ "${arg#-ts}" != "$arg" ]; then StartTime="${arg#-ts}";
	else echo "Unknown argument: $arg"; fi
	shift
done
Debug=${Debug:-0}
Quiet=${Quiet:-false}

# Product data command arguments
ARGS=""
if [ -n "$DisplayInterval" ]; then ARGS=$ARGS"&displayInterval$DisplayInterval"; fi
if [ -n "$StartTime" ]; then ARGS=$ARGS"&startTime=$StartTime"; fi
if [ -n "$StopTime" ]; then ARGS=$ARGS"&endTime=$StopTime"; fi
if [ -n "$XslFilename" ]; then ARGS=$ARGS" -xsl$XslFilename"; fi

# Display starting line
echo "$COMMANDLINE started..." | timestampLogFile

# Quit if no group number provided
if [ -z "$GroupNumber" ]; then usage; fi

# Get number of product for data export group
GID=0
eval $(timeout $PSQLTIMEOUT psql novastar novastar -AtF= <<_EOF_
SELECT 'GID',data_export_id FROM data_export_product WHERE data_export_id=$GroupNumber;
SELECT 'NumberOfProducts',product_order FROM data_export_product WHERE data_export_id=$GroupNumber ORDER BY product_order DESC LIMIT 1;
_EOF_
)
# Quit if unable to read data export group
if [ $GID -ne $GroupNumber ]; then
	echo "Unable to read data export group" | timestampLogFile true
	echo "$COMMANDLINE finished" | timestampLogFile
	exit 1
fi

# Quit if no products
if [ -z "$NumberOfProducts" ]; then usage; fi

# Make timestamp
TIMESTAMP=$(dispdate "+%y.%m.%d.%H.%M")

# Translate product filename for special parameters.
translateFilename() {
	ProductFile="$1"
	ProductId="$2"
	TableName="$3"
	ProductPointId="$4"	

	# Return product filename if no translate patterns.
	if [ "$ProductFile" =  ${ProductFile#*_} ]; then
		echo "$ProductFile"
		return
	fi

	# Translate product index, name, number.
	# Ignore tabular data request
	if [ "$TableName" != "tabular" ]; then
		eval $(timeout $PSQLTIMEOUT psql novastar novastar -AtF= <<_EOF_
SELECT 'PRODUCTINDEX',id FROM $TableName WHERE id=$ProductId;
SELECT 'PRODUCTNAME',quote_literal(name) FROM $TableName WHERE id=$ProductId;
SELECT 'PRODUCTNUMBER',number FROM $TableName WHERE id=$ProductId;
_EOF_
)
	fi

	# Translate product point and station parameters.
	if [ -n "$ProductPointId" ]; then
		eval $(timeout $PSQLTIMEOUT psql novastar novastar -AtF= <<_EOF_
SELECT 'POINTINDEX',id FROM point WHERE id=$ProductPointId;
SELECT 'POINTNAME',quote_literal(name) FROM point WHERE id=$ProductPointId;
SELECT 'POINTID',point_numid FROM point WHERE id=$ProductPointId;
SELECT 'POINTREMOTEID',remote_id FROM point WHERE id=$ProductPointId;
SELECT 'POINTSENSORID',sensor_id FROM point WHERE id=$ProductPointId;
SELECT 'POINTTAG',quote_literal(tag_name) FROM point WHERE id=$ProductPointId;
SELECT 'STATIONINDEX',id FROM station WHERE id=(SELECT station_id FROM point WHERE id=$ProductPointId);
SELECT 'STATIONNAME',quote_literal(name) FROM station WHERE id=(SELECT station_id FROM point WHERE id=$ProductPointId);
SELECT 'STATIONID',numid FROM station WHERE id=(SELECT station_id FROM point WHERE id=$ProductPointId);
SELECT 'STATIONREMOTETAG',quote_literal(remote_tag) FROM station WHERE id=(SELECT station_id FROM point WHERE id=$ProductPointId);
SELECT 'STATIONTTAG',quote_literal(tag_name) FROM station WHERE id=(SELECT station_id FROM point WHERE id=$ProductPointId);
_EOF_
)
	fi
	# Replace patterns in filename with produce, point or station parameters.
	echo "$ProductFile" | \
		sed \
		-e "s/_TIMESTAMP_/$TIMESTAMP/" \
		-e "s/_PRODUCTINDEX_/$PRODUCTINDEX/" \
		-e "s/_PRODUCTNAME_/$PRODUCTNAME/" \
		-e "s/_PRODUCTNUMBER_/$PRODUCTNUMBER/" \
		-e "s/_POINTINDEX_/$POINTINDEX/" \
		-e "s/_POINTNAME_/$POINTNAME/" \
		-e "s/_POINTID_/$POINTID/" \
		-e "s/_POINTREMOTEID_/$POINTREMOTEID/" \
		-e "s/_POINTSENSORID_/$POINTSENSORID/" \
		-e "s/_POINTTAG_/$POINTTAG/" \
		-e "s/_STATIONINDEX_/$STATIONINDEX/" \
		-e "s/_STATIONNAME_/$STATIONNAME/" \
		-e "s/_STATIONID_/$STATIONID/" \
		-e "s/_STATIONREMOTETAG_/$STATIONREMOTETAG/" \
		-e "s/_STATIONTAG_/$STATIONTAG/"
}

# Copy product file name to file list.
# Prepare product files for transfer
# Copy list of image files to transfer
# Rename image file names in product file
prepProductFile() {

	ProductType=$1
	ProductFile=$2
	ProductDelete=$3

	# Save file basename as destination file (remove folders).
	filename=$ProductFile
	filebase=${filename##*/}
	echo "ProductFile='$ProductFile' DestinationFile='$filebase'" >>$FILELIST

	# Add product file to delete list if delete enabled
	if [ "$ProductDelete" = "true" ]; then
		echo "ProductFile='$ProductFile'" >>$DELETELIST
	fi

	# Skip product file prep for binary files made by plotimage
	if [ "$ProductType" = "plotimage" ]; then return; fi

	# Remove file extension from destination file basename.
	filebase=${filebase%.*}

	# Translate plot image name to destination file name base.
	imageCount=0
	grep "src=./temp/jfreechart" $ProductFile | while read line; do
		tempimagename=$(echo $line | sed -e "s,^.*/temp/,," -e "s,.png.*$,.png,")
		if [ -n "$tempimagename" ]; then
			imageCount=$((imageCount+1))
			imagename="$filebase-$imageCount.png"
			sed -i $ProductFile -e "s,$tempimagename,$imagename,g" -e "s,/temp/,images/,"
			echo "ProductFile='/tomcat/temp/$tempimagename' DestinationFile='images/$imagename'" >>$FILELIST
			# Add product file to delete list if delete enabled
			if [ "$ProductDelete" = "true" ]; then
				echo "ProductFile='/tomcat/temp/$tempimagename'" >>$DELETELIST
			fi
		fi
	done
	# Change absolute NovaStar5 and local folder references to relative.
	sed -i $ProductFile -e "s,/NovaStar5/,NovaStar5/,g" -e "s,/local/,local/,g"
}

# Work in temporary folder
cd /tmp

# Make product files and copy file names to list.
rm -rf $FILELIST $DELETELIST

echo "Make data export products started..." | timestampLogFile

ProductOrder=1
while test $ProductOrder -le $NumberOfProducts; do

  ProductType=""
  ProductId=""
  ProductPointId=""
  ProductFilename=""
  ProductDelete=""
  ProductOptions=""
  ProductTimeout=""
	ProductFileDefault="/tmp/"$PGNAME-$$-PRODUCT-$ProductOrder".txt"

	# Get product to export
	eval $(timeout $PSQLTIMEOUT psql novastar novastar -AtF= <<_EOF_
SELECT 'ProductType',product_type FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder;
SELECT 'ProductId',product_id FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder; 
SELECT 'ProductPointId',product_point_id FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder; 
SELECT 'ProductFilename',quote_literal(product_filename) FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder;
SELECT 'ProductDelete',quote_literal(product_delete) FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder;
SELECT 'ProductOptions',quote_literal(product_options) FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder;
SELECT 'ProductTimeout',quote_literal(product_timeout) FROM data_export_product WHERE data_export_id=$GroupNumber AND product_order=$ProductOrder;
_EOF_
)
	if [ $Debug -gt 0 ]; then
		(
		echo ProductOrder=$ProductOrder 
		echo ProductType=$ProductType
		echo ProductId=$ProductId
		echo ProductPointId=$ProductPointId
		echo ProductFilename=$ProductFilename
		echo ProductDelete=$ProductDelete
		echo ProductOptions=$ProductOptions
		echo ProductTimeout=$ProductTimeout
		) 2>&1 | tee -a $LOGFILE
	fi
	# Set default values if not defined
	ProductType=${ProductType:-9999}
	ProductId=${ProductId:-0}
  ProductFile=${ProductFilename:-$ProductFileDefault}
  ProductDelete=${ProductDelete:-false}

	# Convert timeout interval to command syntax
	timeout=$(echo $ProductTimeout | sed -e "s/second.*/s/" -e "s/minute.*/m/" -e "s/hour.*/h/" -e "s/day.*/d/")
	timeout=${timeout:-60}

	# Skip if no product type defined.
	if [ -z "$ProductType" ]; then continue; fi

	# Make a map product.
	iret=1
	if [ "$ProductType" = "map" ]; then

		# Translate product filename
		ProductFile=$(translateFilename "$ProductFile" "$ProductId" "map" "$ProductPointId")

		# Set command URL
		URL="http://localhost:8180/NovaStar5/mapDataDisplay.do"

		# Set command arguments.
		CommandArguments="?mapId=$ProductId"

		# Append product options to request if not empty.
		CommandOptions="&exportPage=true&showDataLinks=false"
		if [ -n "$ProductOptions" ]; then CommandOptions="&$ProductOptions"; fi

		# Make product with timeout
		echo "timeout $timeout curl -s $URL$CommandArguments$CommandOptions -o $ProductFile" | timestampLogFile
		timeout $timeout curl -s "$URL$CommandArguments$CommandOptions" -o $ProductFile 2>&1 | timestampLogFile
		iret=$?
	fi #End of map type

	# Make a report product.
	if [ "$ProductType" = "report" ]; then

		# Translate product filename
		ProductFile=$(translateFilename "$ProductFile" "$ProductId" "report" "$ProductPointId")

		# Set command URL
		URL="http://localhost:8180/NovaStar5/reportDataDisplay.do"

		# Set command arguments.
		CommandArguments="?reportId=$ProductId"
		if [ -n "$ProductPointId" -a "$ProductPointId" != "0" ]; then
			CommandArguments=$CommandArguments"&pointId=$ProductPointId"
		fi

		# Set product make options with command arguments.
		CommandOptions="&exportPage=true&showDataLinks=false"$ARGS

		# Append product options to request if not empty.
		if [ -n "$ProductOptions" ]; then CommandOptions="$CommandOptions&$ProductOptions"; fi

		# Make product with timeout
		echo "timeout $timeout curl -s $URL$CommandArguments$CommandOptions -o $ProductFile" | timestampLogFile
		timeout $timeout curl -s "$URL$CommandArguments$CommandOptions" -o $ProductFile 2>&1 | timestampLogFile
		iret=$?
	fi #End of report type

	# Make a plot product.
	if [ "$ProductType" = "plot" -o "$ProductType" = "plotimage" ]; then

		# Translate product filename
		ProductFile=$(translateFilename "$ProductFile" "$ProductId" "plot" "$ProductPointId")

		# Set command URL
		if [ "$ProductType" = "plot" ]; then
			URL="http://localhost:8180/NovaStar5/plotDataDisplay.do"
		else
			URL="http://localhost:8180/NovaStar5/plotDataImage.do"
		fi

		# Set command arguments.
		CommandArguments="?plotId=$ProductId"
		if [ -n "$ProductPointId" -a "$ProductPointId" != "0" ]; then
			CommandArguments=$CommandArguments"&pointId=$ProductPointId"
		fi

		# Append product options to request if not empty.
		CommandOptions="&exportPage=true&showDataLinks=false"
		if [ -n "$ProductOptions" ]; then CommandOptions="&$ProductOptions"; fi

		# Make product with timeout
		echo "timeout $timeout curl -s $URL$CommandArguments$CommandOptions -o $ProductFile" | timestampLogFile
		timeout $timeout curl -s "$URL$CommandArguments$CommandOptions" -o $ProductFile 2>&1 | timestampLogFile
		iret=$?
	fi #End of plot type

	# Make a tabular product.
	if [ "$ProductType" = "tabular" ]; then

		# Translate product filename
		ProductFile=$(translateFilename "$ProductFile" "$ProductId" "tabular" "$ProductPointId")

		# Set command URL
		URL="http://localhost:8180/NovaStar5/tabularDataDisplay.do"

		# Set command arguments.
		CommandArguments="?pointId=$ProductPointId"

		# Set product make options with command arguments.
		CommandOptions="&exportPage=true&showDataLinks=false&listDetail=dateandtime,datareport,datarating1"$ARGS

		# Append product options to request if not empty.
		if [ -n "$ProductOptions" ]; then CommandOptions="$CommandOptions&$ProductOptions"; fi

		# Make product with timeout
		echo "timeout $timeout curl -s $URL$CommandArguments$CommandOptions -o $ProductFile" | timestampLogFile
		timeout $timeout curl -s "$URL$CommandArguments$CommandOptions" -o $ProductFile 2>&1 | timestampLogFile
		iret=$?
	fi #End of tabular type

	# Set action success by completion code
	if [ $iret -eq 124 ]; then
		result="timeout"
		echo "Make data export product $result" | timestampLogFile
	elif [ "$iret" -ne 0 ]; then 
		result="failed"
		echo "Make data export product $result" | timestampLogFile
	elif [ ! -f $ProductFile ]; then
		echo "Make data export product file does not exist" | timestampLogFile
	else
		result="success"
		echo "Make data export product $result" | timestampLogFile

		# Prepare product file for action transfer
		prepProductFile $ProductType $ProductFile $ProductDelete
	fi

	# Increment product order count then make next product.
	ProductOrder=$((ProductOrder+1))

done # End of product loop

echo "Make data export products finished" | timestampLogFile

# Product file names are in FILELIST
if [ $Debug -gt 0 ]; then
	echo "Data export products file list:" | timestampLogFile
	cat $FILELIST | timestampLogFile
fi

# Do actions if filenames in FILELIST
if [ -s $FILELIST ]; then

	# Get number of actions for data export
	eval $(timeout $PSQLTIMEOUT psql novastar novastar -AtF= <<_EOF_
SELECT 'NumberOfActions',action_order FROM data_export_action WHERE data_export_id=$GroupNumber ORDER BY action_order DESC LIMIT 1;
_EOF_
)
	NumberOfActions=${NumberOfActions:-0}
	if [ $Debug -gt 0 ]; then
		echo "NumberOfActions=$NumberOfActions" 2>&1 | tee -a $LOGFILE
	fi

	# Take actions for product
	ActionOrder=1
	while test $ActionOrder -le $NumberOfActions; do

		# Clear action parameters for next action.
		type=""
		hostName=""
		loginName=""
		password=""
		folder=""
		timeout=""

		# Get product action
		eval $(timeout $PSQLTIMEOUT psql novastar novastar -AtF= <<_EOF_
SELECT 'ActionOptions',quote_literal(action_options) FROM data_export_action WHERE data_export_id=$GroupNumber AND action_order=$ActionOrder;
_EOF_
)
		# Extract export action options
		if [ $Debug -gt 0 ]; then
			(
			echo "ActionOptions=$ActionOptions"
			echo "$ActionOptions" | sed -e "s/=/='/g" -e "s/$/'/g" -e "s/;/';/g" | tr ';' '\n'
			) 2>&1 | tee -a $LOGFILE
		fi
		eval $(echo "$ActionOptions" | sed -e "s/=/='/g" -e "s/$/'/g" -e "s/;/';/g" | tr ';' '\n')

		# Make action type upper case
		ActionType=$(echo $type | tr 'a-z' 'A-Z')

		# Set default destination folder to current folder
		folder=${folder:-./}

		# Convert timeout interval to command syntax
		timeout=$(echo $timeout | sed -e "s/second.*/s/" -e "s/minute.*/m/" -e "s/hour.*/h/" -e "s/day.*/d/")
		timeout=${timeout:-60}

		# Define action script file
		ACTIONSCRIPT="/tmp/$PGNAME.$$.ACTIONSCRIPT"

		# Execute action and log to file
		(

		# Display action started
		iret=1
		result="failed";
		echo "$ActionType export started..."

		# Copy export action
		if [ $ActionType = "COPY" ]; then
			if [ -n "$folder" ]; then
				cat >$ACTIONSCRIPT <<_EOF_
cd $folder
_EOF_
			fi

			# Do all files in FILELIST
			cat $FILELIST | while read line; do
				# Line contains:
				# ProductFile='filename' DestinationFile='filename'
				ProductFile=""
				DestinationFile=""
				eval $(echo $line | tr ' ' '\n')

				# Append cp command to action script file.
				echo "cp '$ProductFile' '$DestinationFile'" >>$ACTIONSCRIPT
			done

			# Execute action with timeout.
			echo "timeout $timeout sh $ACTIONSCRIPT"
			cat $ACTIONSCRIPT
			timeout $timeout sh $ACTIONSCRIPT
			iret=$?
			rm -f $ACTIONSCRIPT
		fi		

		# FTP export action
		if [ $ActionType = "FTP" ]; then
			if [ -z "$hostName" ]; then
				echo "Error - $ActionType export missing host name"
			else
				ACTIONCOMMAND="ftp -i -v"
				if [ -n "$loginName" ]; then
					ACTIONCOMMAND="$ACTIONCOMMAND -n"
					cat >>$ACTIONSCRIPT <<_EOF_
user $loginName $password
_EOF_
				fi
				if [ -n "$folder" ]; then
					cat >>$ACTIONSCRIPT <<_EOF_
cd $folder
_EOF_
				fi

				# Do all files in FILELIST
				cat $FILELIST | while read line; do
					# Line contains:
					# ProductFile='filename' DestinationFile='filename'
					ProductFile=""
					DestinationFile=""
					eval $(echo $line)

					# Append put command to action script file.
					echo "put $ProductFile $DestinationFile" >>$ACTIONSCRIPT
				done

				# Finish script.
				echo "bye" >>$ACTIONSCRIPT

				# Execute action with timeout.
				echo "timeout $timeout $ACTIONCOMMAND $hostName"
				cat $ACTIONSCRIPT
				timeout $timeout $ACTIONCOMMAND $hostName <$ACTIONSCRIPT
				iret=$?
				rm -f $ACTIONSCRIPT
			fi
		fi

		# LFTP export action
		if [ $ActionType = "LFTP"  ]; then
			if [ -z "$hostName" ]; then
				echo "Error - $ActionType import missing host name"
			else
				cat >>$ACTIONSCRIPT <<_EOF_
open $hostName
_EOF_
				if [ -n "$loginName" ]; then
					cat >>$ACTIONSCRIPT <<_EOF_
user $loginName $password
_EOF_
				fi
				# Insert ftps parameters if needed.
				NOTFTPShostName=${hostName#ftps://}
				if [ "$NOTFTPShostName" != "$hostName" ]; then
					cat >>$ACTIONSCRIPT <<_EOF_
set ftps:initial-prot ""
set ftp:ssl-force true
set ftp:ssl-protect-data true
_EOF_
				fi
				if [ -n "$folder" ]; then
					cat >>$ACTIONSCRIPT <<_EOF_
cd $folder
_EOF_
				fi

				# Do all files in FILELIST
				cat $FILELIST | while read line; do
					# Line contains:
					# ProductFile='filename' DestinationFile='filename'
					ProductFile=""
					DestinationFile=""
					eval $(echo $line)

					# Append put command to action script file.
					echo "put $ProductFile -o $DestinationFile" >>$ACTIONSCRIPT
				done

				# Execute action with timeout.
				rm -f ~/.lftp/transfer_log
				echo "timeout $timeout lftp -f $ACTIONSCRIPT"
				cat $ACTIONSCRIPT
				timeout $timeout lftp -f $ACTIONSCRIPT
				iret=$?
				if [ -s "~/.lftp/transfer_log" ]; then
					cat ~/.lftp/transfer_log
				fi
				rm -f $ACTIONSCRIPT
				rm -f ~/.lftp/transfer_log
			fi
		fi

		# PFTP export action
		if [ $ActionType = "PFTP" ]; then
			if [ -z "$hostName" ]; then
				echo "Error - $ActionType export missing host name"
			else
				ACTIONCOMMAND="pftp -i -v"
				if [ -n "$loginName" ]; then
					ACTIONCOMMAND="$ACTIONCOMMAND -n"
					cat >>$ACTIONSCRIPT <<_EOF_
user $loginName $password
_EOF_
				fi
				if [ -n "$folder" ]; then
					cat >>$ACTIONSCRIPT <<_EOF_
cd $folder
_EOF_
				fi

				# Do all files in FILELIST
				cat $FILELIST | while read line; do
					# Line contains:
					# ProductFile='filename' DestinationFile='filename'
					ProductFile=""
					DestinationFile=""
					eval $(echo $line)

					# Append put command to action script file.
					echo "put $ProductFile $DestinationFile" >>$ACTIONSCRIPT
				done

				# Finish script.
				echo "bye" >>$ACTIONSCRIPT

				# Execute action with timeout.
				echo "timeout $timeout $ACTIONCOMMAND $hostName"
				cat $ACTIONSCRIPT
				timeout $timeout $ACTIONCOMMAND $hostName <$ACTIONSCRIPT
				iret=$?
				rm -f $ACTIONSCRIPT
			fi
		fi

		# SFTP export action
		if [ $ActionType  = "SFTP" ]; then
			if [ -z "$hostName" ]; then
				echo "Error - $ActionType import missing host name"
			else
				if [ -n "$folder" ]; then
					cat >$ACTIONSCRIPT <<_EOF_
cd $folder
_EOF_
				fi

				# Do all files in FILELIST
				cat $FILELIST | while read line; do
					# Line contains:
					# ProductFile='filename' DestinationFile='filename'
					ProductFile=""
					DestinationFile=""
					eval $(echo $line)

					# Append put command to action script file.
					echo "put $ProductFile $DestinationFile" >>$ACTIONSCRIPT
				done

				# Finish script.
				echo "bye" >>$ACTIONSCRIPT

				# Prepare login host name.
				loginNameHostName=""
				if [ -n "$loginName" ]; then
					loginNameHostName="$loginName@"
				fi
				loginNameHostName="$loginNameHostName$hostName"

				# Execute action with timeout.
				echo "timeout $timeout sftp -b $ACTIONSCRIPT $loginNameHostName"
				cat $ACTIONSCRIPT
				timeout $timeout sftp -b $ACTIONSCRIPT $loginNameHostName
				iret=$?
				rm -f $ACTIONSCRIPT
			fi
		fi

		# SMB action
		if [ $ActionType  = "SMB" ]; then
			if [ -z "$hostName" ]; then
				echo "Error - $ActionType import missing host name"
			else

				# Make SMB share name
				SMBShare=$(echo $hostName | sed -e "s,//,,g" -e "s,^,//,")
				if [ -n "$folder" ]; then
					cat >$ACTIONSCRIPT <<_EOF_
cd $folder
_EOF_
				fi

				# Do all files in FILELIST
				cat $FILELIST | while read line; do
					# Line contains:
					# ProductFile='filename' DestinationFile='filename'
					ProductFile=""
					DestinationFile=""
					eval $(echo $line)

					# Append put command to action script file.
					echo "put $ProductFile $DestinationFile" >>$ACTIONSCRIPT
				done

				# Finish script.
				echo "quit" >>$ACTIONSCRIPT

				# Create password and login name smbclient command arguments
				loginNamePassword=""
				if [ -n "$password" ]; then
					loginNamePassword=" $password"
				fi
				if [ -n "$loginName" ]; then
					loginNamePassword="$loginNamePassword -U $loginName"
				fi

				# Execute action with timeout.
				echo "timeout $timeout smbclient $SMBShare$loginNamePassword"
				cat $ACTIONSCRIPT
				timeout $timeout smbclient "$SMBShare" $loginNamePassword <$ACTIONSCRIPT
				iret=$?
				rm -f $ACTIONSCRIPT
			fi
		fi

		# Set action success by completion code
		if [ "$iret" -eq 0 ]; then 
			result="success"
		elif [ $iret -eq 124 ]; then
			result="timeout"
		else
			result="failed"
		fi

		# Display action result
		echo "$ActionType export $result"

		) 2>&1 | timestampLogFile

		# Increment action order count then execute next action.
		ActionOrder=$((ActionOrder+1))

	done #End of action loop
fi

# Product file names to delete are in DELETELIST
if [ $Debug -gt 0 ]; then
	echo "Delete data export product file name list:" | timestampLogFile
	cat $DELETELIST | timestampLogFile
fi

# Remove product files if any in list.
if [ -s $DELETELIST ]; then

	result="success"
	echo "Delete data export products started..." | timestampLogFile

	# Do all files in DELETELIST
	cat $DELETELIST | while read line; do
		# Line contains:
		# ProductFile='filename'
		ProductFile=""
		eval $(echo $line)

		# Append put command to action script file.
		timeout 1m rm -vf "$ProductFile" 2>&1 | timestampLogFile
		iret=$?

		# Set action success by completion code
		if [ "$iret" -eq 0 ]; then 
			result="success"
		elif [ $iret -eq 124 ]; then
			result="timeout"
			echo "Delete data export product: $ProductFile $result" | timestampLogFile
		else
			result="failed"
			echo "Delete data export product: $ProductFile $result" | timestampLogFile
		fi
	done
	echo "Delete data export products $result" | timestampLogFile
fi

# Cleanup
rm -rf "/tmp/"$PGNAME-$$-*

# Display finish line
echo "$COMMANDLINE finished" 2>&1 | timestampLogFile

