#!/bin/bash
### DEFAULTS BY HOST ###
divLine="\n###########################################\n";
dataDir="$HOME/lbin";
dataFile="$dataDir/tips.csv";
attachDir="$dataDir/tipsAttachments/";
. ~/lbin/sh.defaults

### HELP/USAGE ###
USAGE="$0 [ad] [directory] fileName";
helpFile="$HOME/lbin/$0Help.txt";

usage() {
cat << EOF
usage: $0 options

Search/Add/Change - tips information

OPTIONS:
   -d      Debug
   -h      Show this Help message
   -l			 List all all attacment records
   -m      Find all missing Records for the attachment (Attachment without tip/Record)
   -x      Tail last n records

   USAGE: 
	   $0  -l     - list all attachment records
	   $0 -m      - Find all Attachments missing Tips Records
	   $0 -m      - find attach1/2 Tips Records
EOF
	if [ -f "$helpFile" ]
	then
		cat $helpFile
	fi
} # /usage

### FUNCTIONS ###
. $HOME/lbin/sh.functions

### COMMAND LINE ###

while getopts "hl" OPTION
do
     case $OPTION in
			 l| L)
				#list all attachments
				allAttachments=`ls $attachDir/*`;
				#allAttachments=`ls /Users/rbutare/lbin/tipsAttachments/*`;
				
				for attachment in $allAttachments
				do
					attachId=`basename $attachment`;
					echo "Looking for: $attachId";
					data=`grep "$attachId$csvDelim" $dataFile`;
					echo "Data: $data";

					if [ -z "$data" ]
					then
						echo "1Looking for $attachId....";
						getInfo $data
						exit
					else
						echo "***** ERROR: NO RECORD FOUND FOR $attachId *****";
					fi
				done
				exit 0;
				;;
			 h| H)
        usage
				cmdText=" Show Help Information "
				echo "$divLine $cmdText: $divLine"
				cat $helpFile
				exit 97;
				;;
			?)
				#Default no special options
				#invalid options
				cmdNum=0;
				cmdText=" ERROR: Unknown command !! "
				echo "HERE: INVALID OPTION: $OPTION";
        usage
        exit
        ;;
     esac
done

### VALIDATE ARGUMENTS AFTER OPTIONS
#get Files Passed  shift passed options
shift $(($OPTIND - 1))
files="$@"
echo "FILES PASSED: $files";

### ERRORS ###

## if [ $# = 0 ] ;
## then
	## echo "Help";
	## usage;
	## exit 1;
## fi


if [ "$debugFlg" = "1" ] 
then
	echo "TEST=$TEST SERVER=$SERVER PASSWD=$PASSWD";
fi
### CODE ###
#find csv record attachment belongs to
for attachment in $*
do
	attachId=`basename $attachment`;
	echo "1Looking for: $attachId";
	data=`grep "$attachId$csvDelim" $dataFile`;
	#FUTURE _ MATCH ON LINKS FIELD ONLY
	#BUGS NOT WORKING ON -L GETS ALL FILES
	if [ -z "$data" ]
	then
		echo "***** ERROR: NO TIPS RECORD FOUND FOR ATTCHMENT:  $attachId *****";
	else
		getInfo $data
	fi
done
