#! /bin/bash
#Find all snippets defined in snippets file
#TODO IF -f find only this snippet -v show snippet info
snipDir="$HOME/.vim/snippets/";
cd $snipDir
list_snippets_for() {
    fileNamePath="$snipDir/$1";
    fileName="$1";
    fileName="$(basename $fileName)"
    if [ ! -f "$fileNamePath" ]
        then
        echo "ERROR: FILE: $fileNamePath DOES NOT EXIST!!";
        exit 1;
    else
        egrep "^snippet|^#" ~/.vim/snippets/$fileName | awk '/^#/ {comment = comment $0} /^snippet/ {print $0 "\t\t" comment; comment=""}'
        #egrep "^snippet|^#" ~/.vim/snippets/$fileName ;
    fi
    return 0;
}
### HELP/USAGE ###
USAGE="$0 [s searchString]  snippetFileName/s";
helpFile="$HOME/lbin/$0help.txt";

### COMMAND LINE ###
# you should not use `getopt abo: "$@"` since that would parse
# the arguments differently from what the set command below does.
CMDLINE=$*;
argc="$#"
if [ $argc = 0 ] ;
then
	echo "ERROR: USAGE: $USAGE";
	if [ -f $helpFile ]
	then
		cat $helpFile
	fi
	exit 96;
fi
ARGS=`getopt s:  $@`
# c config d datafile j convert to json q convert to json display with jq
if [ $? != 0 ]
then
	echo "ERROR $USAGE ";
	if [ -f $helpFile ] 
	then 
		cat $helpFile;
	fi
	exit 98
fi
findVal="$*";
# You cannot use the set command with a backquoted getopt directly,
set -- "$ARGS"
# You cannot use the set command with a backquoted getopt directly,
# since the exit code from getopt would be shadowed by those of set,
# which is zero by definition.

cmdNum="-1"; #Used to show what cmd to run - Default Value
searchFor="";

for i
do
	case "$i"
	in
		 -a| -A)
			cmdText=" Add Info to file"
			id=`date '+%Y%m%d%H%M%S'`;
			lik="lnk";
			title="title";
			desc="desc";
			tags="tags,tags";
			comments="Add from shell";
			moreInfo="MOREINFO";
			subCat="SUBCAT";
			subSubCat="SUBSUBCAT";
			cat="CAT";
			read -p "Enter Title: " title;
			read -p "Enter Desc: " desc;
			read -p "Enter Link: " link;
			read -p "Enter Tags: " tags;
			addLine="$id<>$cat<>$subCat<>$subSubCat<>$title<>$desc<>$moreInfo<>$comments<>$link<>$tags";
			echo "Add Line: $addLine";
			read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
			echo -e "$addLine\n" >>$dataFile
			tail -2 $dataFile;
			exit 97;
			;;
		 -h| -H)
			cmdText=" Show Help Information "
			cat $helpFile
			exit 97;
			;;
		-c | -C )
			cmdNum=1;
			cmdText="  Convert CSV to JSON"
			csvToJson $dataFile $csvDelim
			shift;
			break;
			;;
		-d | -D )
			cmdNum=2;
			cmdText=" Debug Info "
			echo "$divLine Configuration Settings: "
			echo "dataFile=" . $dataFile ;
			shift;
			break;
			;;
		-s | -S )
			cmdNum=3;
			cmdText="Show Snippet Code from File: "
			echo "$divLine $cmdText: "
			#Change dataFile
			searchFor="$2";
			echo "******* SEARCHING FOR: $searchFor   ******"
			shift; #move to next arg
			break;
			;;
		-x | -X )
			cmdNum=4;
			cmdText=" Find files with EXACT MATCH ONLY! "
			shift;
			break;
			;;
		--)
			#Default no special options
			cmdNum=0;
			cmdText=" ERROR: Unknown command !! "
			if [ $cmdNum -ne 0 ]
			then
				echo "IN DEFAULT DO I SHIFT";
				shift;
			fi
			break; 
			;;
	esac
done

echo "ORG CMDLINE=$CMDLINE";
echo "AAA = cmdNum = $cmdNum";
if [ "$cmdNum" -ge "0" ]
then
	shift; #shift past -- to get to fileName/snippetNames
	echo "XXXX cmdNum = $cmdNum GOT TO SHIFT PASSED ---! 0=$0 *=$* 1=$1";
fi
###for i in $*
###do
###	if [ "$i" = "--" ]
###	then
###		### 	Make sure -- of getopts is gone
###		echo "SHIFT IN FOR";
###		shift
###	fi
###done
fileNames=$*;

args="$@";
echo "YYYY= 1= $1";

if [ "$1" == "" ]
then
    echo "====================================================================================";
		echo "ERROR: USAGE: $USAGE";
    echo "====================================================================================";
    echo "You must specify at least one file type as an argument to $0"
    echo "Available Snippets: ";
    echo "	$snippets"
    echo "	USAGE: $USAGE";
    echo "====================================================================================";
    exit
elif [ "$1" == "all" ] 
then
		snippets=`ls -x *.snippets `;
  #  snippets=$snippets;
else
	#Append .snippets to fileName passed
	snippets="";
	echo "FILES IN ELSE: $*";
	for fileNameArg in $*
	do
		snippets="$snippets $fileNameArg.snippets";
	done
	echo "SNIP=$snippets"
fi
shift
echo "* = $*";
echo "0=$0 1=$1 2=$2"
echo "FILES TO SEARCH: $snippets";

#snippets="_.snippets jq.snippets";
#snippets="jq.snippets";
banLine="============================";

argc=$#;
found=0;
#echo " *** SEARCHING FOR: searchFor=$searchFor ***";
if [ ! -z $searchFor ]
then
	echo "*** SEARCHING FOR SNIPPET: $searchFor  IN FILE: $snippets ***";
else
	echo "*** SEARCHING FOR ALL SNIPPETS IN FILES: $snippets ***";
fi
for filetype in $snippets
do
    #echo `echo $filetype | awk '{print toupper($0)}'`
    #echo "$banLine Snippets for".`echo $filetype | awk '{print $0}'`.$banLine;
    #fileName="$banLine "`echo $filetype | awk '{print $0}' `$banLine;
    fileName=`echo $filetype | awk '{print $0}' `;
    #echo "$banLine "`echo $filetype | awk '{print $0}' `$banLine;
		if [ $filetype = "all.snippets" ]
		then
			#skip over all
			if [ -f $snipDir/$filetype ]
			then
				#File Exists use to search
				echo "***** FOUND FILE: ALLL *****";
			else
				continue
			fi
		else
			echo "$banLine START -" $fileName $banLine;
		fi
    #echo "filetype=$filetype";
		if [ $cmdNum = 3 ];
		then
			#found=` grep -q "^snippet $searchFor" $fileName `;
			found=` grep -c "^snippet $searchFor" $fileName `;
			rc=$?;
			#echo "found=$found - rc = $?";
			if [ $? = 0 ] ;
			then
				#if found more than 1 must loop to get them all
				if [ "$found" -eq "0" ] ;
				then
					echo "NOT FOUND";
				elif [ "$found" -ne "1" ] ;
				then
					echo "*** WARNING: FOUND MULTIPLE DEFINITIONS: $found !! *** ";
				fi
				#awk "/snippet $searchFor/,/^endsnippet/" $fileName
				awk "/^snippet.*$searchFor/,/^endsnippet/" $fileName
				#awk '/snippet.*sh1/,/^endsnippet/' snip
			fi
		else
	    list_snippets_for $filetype
			echo "$banLine " $fileName - END $banLine;
			echo "";
		fi

	done
	if [ $cmdNum = 3 ];
		then
				if [ "$found" -eq "0" ] ;
				then
					echo "NOT FOUND";
				elif [ "$found" -ne "1" ] ;
				then
					echo "*** WARNING: FOUND MULTIPLE DEFINITIONS: $found !! *** ";
				fi
	fi	
