#!/bin/bash
#set -x
####################################################
#
#  $URL: svn://svn.code.sf.net/p/gar/code/csw/mgar/gar/v2/bin/fixlibtool $
#  $Date: 2010-02-10 10:06:09 -0500 (Wed, 10 Feb 2010) $
#  $Revision: 8462 $
#  $LastChangedRevision: 8462 $
#
#  Author: Mike Watters (mwatters~~@~~opencsw.org)
#  Intended to remove the use of libtool's 
#  pseudo-libraries for opencsw builds.
#
#  Usage: fixlibtool $(WORKSRC)
#
#  Intened usage:
#  DISTFILES += fixlibtool
#  post-configure-modulated:
#       @(echo "~~~ Fixing Libtool ~~~")
#       @$(DOWNLOADDIR)/fixlibtool $(WORKSRC)
#       @$(MAKECOOKIE)
#
####################################################
umask 0022
PATH=/opt/csw/bin

if [ $# -ne 1 ]; then
    gecho "USAGE: $(basename $0) WORKSRC"
    exit 1
fi
BASEPATH=$1

## Fix Makefiles
for mk in $(gfind ${BASEPATH} -name Makefile -print); do
    gcp ${mk} ${mk}.orig
    LT_FILES=$(for lib in $(gegrep -v '^#|^$' ${mk} | \
                   ggrep '/opt/csw.*/lib/.*\.la'); do \
                   echo $lib |gsed -ne '/\/opt.*\.la/p'; done)
    for file in ${LT_FILES}; do
        LIB_NAME=$(ggrep 'dlname=' ${file} | \
            gsed -e "s/.*'\(.*\)'/\1/" \
                -e "s/^lib//" \
                -e "s/\.so.*$//")
        fixpath=$(gecho $file |gsed 's/\//\\\//g')
        gsed "s/${fixpath}/-l${LIB_NAME}/g" ${mk} >${mk}.new
        LIB_DIR=$(ggrep 'libdir=' ${file} | gsed -e "s/.*'\(.*\)'/\1/")
        perl -pe 's,(LDFLAGS =[^\\]*)(\\)?\n,$1 -R'${LIB_DIR}' -L'${LIB_DIR}' $2\n,' ${mk}.new >${mk}
        gchmod +x ${mk}
    done
done

## Fix libtool Script
for lt in $(gfind ${BASEPATH} -name libtool -print); do
    gcp ${lt} ${lt}.orig
    gsed "/for search_ext in .*\.la/s/\.la//" ${lt} >${lt}.new
    gmv ${lt}.new ${lt}
    gchmod +x ${lt}
done

for LTMAIN in $(gfind ${BASEPATH} -name ltmain.sh -print); do
    gcp ${LTMAIN} ${LTMAIN}.orig
    gsed "/for search_ext in .*\.la/s/\.la//" ${LTMAIN} >${LTMAIN}.new
    gmv ${LTMAIN}.new ${LTMAIN}
    gchmod +x ${LTMAIN}
done

exit 0
