#!/bin/bash

#Copyright 2008 Mike Doty <kingtaco@gentoo.org>
#License: as-is.  NO WARRANTY OF ANY KIND!!! YOU HAVE BEEN WARNED!!!

#revdep-rebuild binary full path
REVDEP_REBUILD="/usr/bin/revdep-rebuild"

#space seperated list of places to look for libraries in order 
#of likelyness.  no trailing / 
LIBRARY_SEARCH_PATH="/usr/lib /lib /usr/kde /opt"

function find_full_lib_path() {
    local libfull=""
    local libname=${1}
    if [ -z ${libname} ]; then
	echo "Error: Library not specified..." > /dev/stderr
	return 1
    fi

    for F in ${LIBRARY_SEARCH_PATH}; do
	libfull=$(find "${F}/" -name ${libname})
	if [ -n "${libfull}" ]; then
	    echo "Found library ${libname} at ${libfull}" > /dev/stderr
	    break
	fi
    done
    if [ -z "${libfull}" ]; then
	echo "Warning: Couldn't find path for ${libname}..." > /dev/stderr
	return 1
    fi
    echo ${libfull}
    return 0
}
	

function do_revdep() {
    local lib=${1}
    local libfull=""
    local ret=1

    if [ -z "${lib}" ]; then
	echo "Error: Library not specified..." > /dev/stderr
	return 1
    fi

    ${REVDEP_REBUILD} --library ${lib}
    ret=$?

    if [ ${ret} -ne 0 ]; then
	echo "Warning: revdep-rebuild failed to complete sucessfully, skipping old library removal." > /dev/stderr
	return ret
    else
	libfull=$(find_full_lib_path ${lib})
	if [ -e "${libfull}" ]; then
	    echo "Removing ${libfull}" > /dev/stderr
	    rm "${libfull}"
	else
	    echo "Couldn't find path to ${lib} to remove" > /dev/stderr
	fi
    fi
    return 0
}


if [ ${EUID} -ne 0 ]; then
    echo "Error: you must be root to run this program." > /dev/stderr
    exit 9
fi

LIBS="$*"
echo "Cleaning up system for the following libraries: ${LIBS}..." > /dev/stderr
sleep 5

for F in ${LIBS}; do
    do_revdep ${F}
done


# libnspr4.so.6 libplc4.so.6 libplds4.so.6 libcrypto.so.0.9.7 libintl.so.7


    

