#! /bin/sh

# Copyright 2008 Giovanni Santostefano
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#AUTHOR: Giovanni Santostefano
#WEB: http://santostefanogiovanni.blogspot.com
#detectfile is a fast way to create archives that
#contains file trees and search through them.
#If you have many backup medium you can make
#archives for each one and search for a file into
#them.

#usage:
#Creating an archive
# $ detectfile -c directory_to_examinate arch_file_name
#
#Searching for file
# $ detectfile -f substring_in_file_name


ARC_DIRECTORY=$HOME/.detective

usage()
{
echo "detectfile is a fast way to create archives that"
echo "contains file trees and search through them. "
echo "If you have many backup medium you can make "
echo "archives for each one and search for a file into them."
echo " "
echo "usage: "
echo "Creating an archive "
echo " $ detectfile -c directory_to_examinate arch_file_name "
echo " "
echo "Searching for file "
echo " "
echo " $ detectfile -f substring_in_file_name "
echo " "
echo "developed by Giovanni Santostefano "
}

if [ "$#" -eq "0" ]; then
	usage
	exit
fi

#test if archive dir exists
ls -lah $ARC_DIRECTORY &> /dev/null

if [ "$?" -ne "0" ]; then
	mkdir $ARC_DIRECTORY
fi

if [ $1 = "-c" ]; then
	tree $2 > $ARC_DIRECTORY/$3
fi

if [ $1 = "-f" ]; then
	for file in $ARC_DIRECTORY/*
	do
		cat $file | grep -i $2
		if [ "$?" -eq "0" ]; then
			echo "IN ARCHIVE: " $file
		echo " "
	fi
	done
fi
