#!/bin/sh

#< Delete an entry from the address book

_ADDRESS_BOOK=$HOME/a_book/a_book
_TEMP_FILE=$HOME/tmp/a_book.tmp.$$
_ENTIRE_FILE=$HOME/tmp/a_full.tmp.$$

# As a : appears in every line, this has the effect
# of numbering the lines in the fashion we want.
grep -in ":" ${_ADDRESS_BOOK} > ${_ENTIRE_FILE}

echo "Enter a searchterm for your deletion:"
read _SEARCHTERM

grep -in "${_SEARCHTERM}" ${_ADDRESS_BOOK} > ${_TEMP_FILE}

_count=$(wc -l < ${_TEMP_FILE})
echo "${_count} match(es) found!"

while read line
do
  _record_number=$(echo $line | awk -F: '{print $1}')
  _records="${_records} ${_record_number}"
done < ${_TEMP_FILE}

echo ""

for record in ${_records}
do
   _current_rec=$(grep "^${record}:" ${_TEMP_FILE})
   _firstname=$(echo ${_current_rec} | awk -F: '{print $2}')
   _surname=$(echo ${_current_rec} | awk -F: '{print $3}')
   _address1=$(echo ${_current_rec} | awk -F: '{print $4}')
   echo "===================================================="
   echo "${_firstname} ${_surname} of"
   echo "${_address1}"
   echo "DO YOU WANT TO DELETE THIS RECORD? [y/n]"
   read response
   case $response in
     [yY]|[yY][eE][sS])  
	grep -v "^$record:" ${_ENTIRE_FILE} > ${_ENTIRE_FILE}_v
    cp -f ${_ENTIRE_FILE}_v ${_ENTIRE_FILE}
	cut -d':' -f 2-11 ${_ENTIRE_FILE}_v > ${_ADDRESS_BOOK}
	echo "ENTRY DELETED!"
	;;
     *) ;;
   esac
done

rm -rf ${_TEMP_FILE}
rm -rf ${_ENTIRE_FILE}
rm -rf ${_ENTIRE_FILE}_v