#!/bin/bash
#######################################################################
# thumbsup
#
# Finds all timthumb files that it can, then locates outdated ones from
# that list. It then makes backups of existing files, and replaces each
# with the current timthumb script. If a username is passed when the
# script is called, it will act on that user's directory. If no username
# is passed, it will gather the username from the current directory
# Presents user with a report of all found timthumb files, then asks
# if they should be updated.  If "-a" is passed as a parameter, the 
# script will go into automatic mode and will upgrade everything.
#
# http://git.toolbox.hostgator.com/thumbsup/pages/Home
# http://git.toolbox.hostgator.com/thumbsup
#
# Please submit all bug reports at bugs.hostgator.com
#
# VERSION 1.1.1
# by Thomas Johnson
#
# (C) 2012 - HostGator.com, LLC
#
#######################################################################

# Initialize some values

timestamp=`date +%s`
user=""
doupgrade=""
oldversion=""
goodthumb="0"
# Allow spaces in filenames and paths

LS_OPTIONS="";SAVEIFS=$IFS;IFS=$(echo -en "\n\b");
echo

# If a parameter is passed, it should be either the username or -a, -h, or -help

case "$1" in

        -[hH] | --[hH][Ee][lL][pP] )    echo "Usage:  thumbsup [OPTION...]"
                echo
                echo "-a or --automatic         Automatically upgrade all timthumb scripts in this account"
                echo "-h or --help              Display a friendly help message"
		echo "-n or --noupdate          No updates.  Just reports timthumb scripts and versions"
                exit
                ;;

	-[nN] )	echo "No update will be done.  Reports versions only"
		echo
		doupgrade="n"

		if [ -e "/var/cpanel/users/$2" ]
		then
			user=$2
			workdir="/home/$user"
			secdir="/home/$user/.security"
		else
			echo "$2 is not a valid parameter"
			echo "Game Over!"
			exi5t
		fi
		;;	

        -[aA] | --automatic )   echo "Automatic update mode engaged!"
                echo
                doupgrade="y"

                if [ -e "/var/cpanel/users/$2" ]
                then
                        user=$2
                        workdir="/home/$user"
                        secdir="/home/$user/.security"
                else 
                        echo "$2 is not a valid parameter"
                        echo "Game Over!"
                        exit
                fi
                ;;

        *)      if [ -e "/var/cpanel/users/$1" ]
                then
                        user=$1
                        workdir="/home/$user"
                        secdir="/home/$user/.security"
                else 
                        echo "$1 is not a valid parameter"
                        echo "Game Over!"
                        exit
                fi
                ;;
esac

# No username passed, so determine it from current working directory
if [ ! "$user" ]
then
        user=`pwd | cut -d / -f 3`
        workdir="/home/$user"
        secdir="/home/$user/.security"
fi

# Even backup files need a name
prefix="/home/$user/.security/timthumb-originals"
backupfile="$prefix-$timestamp.tar"

# Make sure that the .security directory exists

if [ ! -e $secdir ]
then 
        mkdir $secdir && echo "Creating Directory $secdir"  >/dev/null 2>&1
fi

# Make a pretty header

echo
echo "====================================="
echo "=    Upgrading timthumb scripts     ="
echo "====================================="
echo 

cd $secdir
curthumb="$secdir/timthumb.php"

# Back up any existing timthumb.php file in the .security directory
if [ -e $curthumb ]
then
	mv $curthumb $curthumb-backup-$timestamp
fi

# Download current version, whatever that may be
echo "Downloading the current version of timthumb"
echo
wget -q -O $curthumb http://timthumb.googlecode.com/svn/trunk/timthumb.php > /dev/null 2>&1


# Check to determine if the download was successful

export RC=$?
if [ "$RC" = "0" ]
then
	if grep -l by\ Tim\ McDaniels\ and\ Darren\ Hoyt $curthumb
	then 
		goodthumb="1"
	fi
else
	echo "Something went wrong with the download.  Upgrade aborted"
	#echo "Return Code is $RC"
	doupgrade="n"
fi

chown $user.$user $curthumb

# Determine the current version
currentversion=`grep \'VERSION\' $curthumb | cut -d \' -f 4`
echo
echo "The current version of timthumb.php is $currentversion"
echo

# Get a list of timthumb files in the account and put it into array "thumbarray".

unset thumbarray i

# Fill an array with the names of all the timthumb files in the account

echo "Searching $workdir/public_html"
for filename in `find $workdir/public_html -type f -size +6k -size -80k -name "*.php"`
do
        if grep -l by\ Tim\ McDaniels\ and\ Darren\ Hoyt $filename
        then
                thumbarray[i++]="$filename"
        fi
done

# How many timthumb files did we find?

numofthumbs=${#thumbarray[*]}

if [[ "$numofthumbs" = "0" ]]
then
	echo "I did not find any timthumb scripts in this account"
fi

# Present the user with a list of all timthumbs and their versions:

for file in "${thumbarray[@]}"
do
        version=`grep -P "^(define \('VERSION|define\('VERSION|define \(\"VERSION|define\(\"VERSION)" $file |cut -d \' -f 4 | cut -d \" -f 4`    
        newestfileversion=`echo -e "$version\n$currentversion" | sort -t'.' -n -k3 | tail -1`
        if [[ "$version" = "$currentversion" ]]
        then 
                # This timthumb file is up to date
                echo "$file is up to date, running Version $version"

        else 
                # File needs an update
                oldversion="1"
                echo "$file is at $version"
        fi
done

# If all is well, Ask the user for permission to perform the upgrades

if [[ "$oldversion" = "1" && "$doupgrade" = "" && "$numofthumbs" != "0" && "$goodthumb" = "1" ]]
then
        answer=""

        echo "Should these files be updated right now?"
        echo "[Y]es or [N]o"
        echo

        read answer

        case    "$answer" in 
                        "Y" | "y" | "Yes" | "yes") doupgrade="y";;
                        * )     doupgrade="n";;
        esac
fi

if [[ "$doupgrade" = "n" ]]
then 
        echo "Upgrade will not be performed."
fi

if [[ "$doupgrade" = "y" && "$numofthumbs" != "0" && "$goodthumb" = "1" ]]
then 
        echo "Performing updates"
        # Prepare a backup tarball
        if [ ! -e $backupfile.gz ]
        then echo "Creating backup file $backupfile.gz"
                tar -P --create --file=$backupfile $curthumb
             #create $backupfile
        else gunzip $backupfile.gz
        fi

        # Parse through the array, making backups as we go

        for file in "${thumbarray[@]}"
        do
                version=`grep -P "^(define \('VERSION|define\('VERSION|define \(\"VERSION|define\(\"VERSION)" $file |cut -d \' -f 4 | cut -d \" -f 4`    
                newestfileversion=`echo -e "$version\n$currentversion" | sort -t'.' -n -k3 | tail -1`
                if [[ "$version" != "$currentversion" ]]
                then 
                        echo "Upgrading $file from $version to $currentversion"
        
                        # File is outdated, so back it up first, then replace it!
                        tar -P --append --file=$backupfile $file
                        rm -f $file
                        cp -pr $curthumb $file
                else 
                # File is already current
                echo "$file is already at $version out of $currentversion"
                fi
        done

else
        #echo "No upgrade needed."
        echo "Game Over!"
fi

# Zip up that archive!
if [ -e $backupfile ]
then 
        gzip $backupfile >/dev/null 2>&1
fi
