#!/bin/bash

in_file="${1}"
if [ -z "${in_file}" ] ; then
    echo "Argument required!"
    exit 1
fi
if [ ! -f "${in_file}" ] ; then
    echo "No such file: ${in_file}"
    exit 1
fi

function _cleanup() {
    [ ! -z "${tmp_in_file}" -a -f "${tmp_in_file}" ] && rm -vf "${tmp_in_file}" > /dev/null 2>&1
    [ ! -z "${tmp_in_file}" -a -f "${tmp_in_file}.filelist" ] && rm -vf "${tmp_in_file}.filelist" > /dev/null 2>&1
    [ -f "${in_file}" ] && rm -vf "${in_file}" > /dev/null 2>&1
}

tmp_in_file="${in_file}.tmp.$$"
rm -f "${tmp_in_file}" > /dev/null 2>&1

trap "_cleanup ; exit" SIGHUP SIGINT SIGTERM

while read s ; do
    cont=1
    # Check for illegal characters in filename pattern or empty pattern
    [ -z "${s}" ] && cont=0
    echo "${s}" | grep "/" > /dev/null
    [ $? -eq 0 ] && cont=0
    echo "${s}" | grep "*" > /dev/null
    [ $? -eq 0 ] && cont=0
    if [ ${cont} -eq 0 ] ; then
        echo "Will not process pattern: ${s}"
        continue
    fi
    # Sanitize input line
#    echo "Processing pattern: ${s}"
    s=`echo "${s}" | \
          sed -re 's#\[#\\\\[#g' | \
          sed -re 's#\]#\\\\]#g' | \
          sed -re 's#[(]#\\\\(#g' | \
          sed -re 's#[)]#\\\\)#g' | \
          sed -re 's#[$]#\\\\$#g'`
    echo "${s}" >> "${tmp_in_file}"
done < "${in_file}"

rm -f "${tmp_in_file}.filelist" > /dev/null 2>&1
while read -r s ; do
#    echo "Line: ${s}"
    # Find file(s) by name pattern
    find / -iwholename "*${s}*" >> "${tmp_in_file}.filelist"
done < "${tmp_in_file}"

if [ -s "${tmp_in_file}.filelist" ] ; then
    echo "File(s) found:"
    echo "------------------------------"
    cat "${tmp_in_file}.filelist"
    echo ""
    echo "Are you sure you want to delete them?"
    read -e -i "no" -p "Please enter your answer (yes/No): " input
    answer="${input:-no}"

    if [ "${answer}" = "yes" ] ; then
        echo "Will delete files..."
        while read -r s ; do
            # Find file(s) by name pattern and delete them
            find / -iwholename "*${s}*" -exec rm -rf {} \;
        done < "${tmp_in_file}"
    else
        echo "Will not delete files.."
    fi
else
    echo "Found nothing."
fi

_cleanup
