#!/bin/bash
# exploitdb CLI search tool
# Version 2
# Written by Unix-Ninja

csvpath=/usr/share/exploitdb/files.csv
progname=`basename $0`
VERBOSE=0

# if files.csv is in the searchsploit path, use that
if [ -f "$( dirname $0 )/files.csv" ]; then
	csvpath="$( dirname $0 )/files.csv"
fi

# usage info
function usage()
{
	echo "Usage: $progname [options] term1 [term2] ... [termN]"
	echo "Example: $progname oracle windows local"
	echo 
	echo "======="
	echo "Options"
	echo "======="
	echo
	echo "  -h, --help   Show help screen" 
	echo "  -v           By setting verbose output, description lines are allowed to"
	echo "               overflow their columns"
	echo
	echo "*NOTES*"
	echo "Use any number of search terms you would like (minimum of one)."
	echo "Search terms are not case sensitive, and order is irrelevant."
	exit 1
}
if [ $# -eq 0 -o "$1" == "-h" -o "$1" == "--help" ]; then
	usage >&2
fi

# dynamically set column widths
COL2=35
COL1=$(( `tput cols` - $COL2 - 1 ))

if [ "$1" == "-v" ]; then
	VERBOSE=1
	shift
fi

# print header
printf "%-${COL1}s %s" " Description"
echo "  Path"
printf "%0.s-" `eval echo {1..$(( $COL1 + 1 ))}`
echo -n " "
printf "%0.s-" `eval echo {1..$(( $COL2 - 1 ))}`
echo

# create search command
SEARCH="fgrep -i \"$1\" $csvpath"
shift
while (( "$#" )); do
  SEARCH="$SEARCH | fgrep -i \"$1\""
  shift
done

# set LANG variable to avoid illegal byte sequence errors in sed
LANG=C

# search, format, and print results
if [ "$VERBOSE" -eq 0 ]; then
	eval $SEARCH \
	| awk -F "\"*,\"*" '{ printf "%-'$COL1'.'$COL1's | %s\n", $3, $2}' \
	| sed "	s/| platforms/| /"
else
	eval $SEARCH \
	| awk -F "\"*,\"*" '{ printf "%-'$COL1's | %s\n", $3, $2}' \
	| sed "	s/| platforms/| /"
fi
exit 0
