#!/bin/bash
# Begin /usr/sbin/remove-lafiles.sh

# This script creates a backup copy of the target .la file in $BACKUP, as well
# as sequential backups of any additional files modified when removing a
# particular .la file.

BACKUP=/usr/lib/lafile-backup

# Make sure we are running with root privs
if test "${EUID}" -ne 0; then
    echo "Error: $(basename ${0}) must be run as the root user! Exiting..."
    exit 1
fi

# Make sure our input is sane
if test "${#}" -ne 1; then
    echo "Error $(basename ${0}) takes only one argument! Exiting..."
    exit 2
fi
if test $(basename "${1}") == "${1}"; then
    echo "Error: $(basename ${0}) requires the full path! Exiting..."
    exit 3
fi
if test ! -f "${1}"; then
    echo "Error: ${1} does not exist! Exiting..."
    exit 3
fi
if test ! $(echo "${1}" | grep '\.la$'); then
    echo "Error: ${1} can only be a libtool archive! Exiting..."
    exit 3
fi

lafile="${1}"
lalinker=$(echo "$(basename ${lafile})" | sed -e 's/^lib/-l/' -e 's/\.la//')

get_backup_file(){
    # return correct filename with .# extesion if it already exists
    # $1 is full path of original filename
    # return is new filename
    local filebase="${1}"
    if test -f "${BACKUP}${filebase}.bak"; then
        local file=$(ls "${BACKUP}${filebase}.bak"* | sort -V | tail -n 1)
        local ext=$(echo ${file##$BACKUP$filebase.bak.})
        if test "${ext}" == "${BACKUP}${filebase}.bak"; then
            echo "${BACKUP}${filebase}.bak.1"
        else
            let ext++
            echo "${BACKUP}${filebase}.bak.${ext}"
        fi
    else
        echo "${BACKUP}${filebase}.bak"
    fi
}

bufile=$(get_backup_file ${lafile})
echo "Moving ${lafile} to ${bufile}.bak."
mv "${lafile}" "${BACKUP}${lafile}.bak" 2>&1 > /dev/null
echo ""
echo "Finding references to ${lafile} in installed .la files..."
for targetfile in `find /usr/lib -name "*.la"`; do
    grep -q "${lafile}" "${targetfile}" &&
    butarget=$(get_backup_file ${targetfile}) &&
    echo "Created backup copy of ${targetfile} at ${butarget}" &&
    install -vDm644 "${targetfile}" "${butarget}" 2>&1 > /dev/null &&
    sed "s@${lafile}@${lalinker}@g" -i "${targetfile}" 2>&1 > /dev/null
done

unset BACKUP lafile lalinker bufile targetfile butarget
# End /usr/sbin/remove-lafiles.sh

