#!/bin/bash
docroot=$(pwd)

#debug line
#echo $docroot
# !!! Need to idiot proof MWx pwd !!!

suspicious_files=$(find $docroot -maxdepth 1 -type f -executable -name "*.php")

echo -e "Making a backup of the following files before cleaning:"
for sus_file in $suspicious_files; do
# Begin safety checks 
#    To ensure we dont bork "legit" files / ensure there are obvious malware signatures
#    Basically saying if lines 2, 4, and 6 ALL match these malware signatures
	if [[ "$(sed '2!d' $sus_file | egrep "^\/\*[0-9a-zA-Z]{5}\*\/$")" \
	&& "$(sed '4!d' $sus_file | egrep ^\@include)" \
	&& "$(sed '6!d' $sus_file | egrep "^\/\*[0-9a-zA-Z]{5}\*\/$")" ]]
# End safety checks
	then
		echo -e "$sus_file" 
# make backup of file while removing the obvious malware 
		$(sed "-i.suspicious.malware.`date +%F_%R`.bak" '2,6d' $sus_file); \
# Now remove any extra empty lines before legit code 		
		$(sed -i 2,"$(grep -nv "^$" $sus_file | head -n2 | tail -n1 | cut -d: -f1 |  awk '{ SUM += $1-1} END { print SUM }')"d $sus_file); \

# correct permissions
		chmod 0 "$sus_file".suspicious.malware.$(date +%F_%R).bak;
		chmod 644 $sus_file;
# WARNING: If for any reason the chmod's dont work, then re-running the script will not work as intended
# stemming from the find command at the beginning
	fi
done

echo -e "\nLeftover executable files to investigate manually:"
echo "$(find $docroot -maxdepth 1 -type f -executable)"

