#!/bin/sh

# Take a bunch of perhaps non-uniquely-named files (because of truncation)
# from a library and regenerate them in the current dir with unique names.

libname=$1
tmpdir=/tmp/mklib$$
namefile=$tmpdir/onames

progname=`basename $0`

# Check a few obvious errors:
if [ ! -f $libname ]; then
    echo "${progname}: can not find ${libname} in current dir `pwd`."
    exit 1
fi
if [ ! -r $libname ]; then
    echo "${progname}: can not read ${libname}."
    exit 1
fi

mkdir -p $tmpdir || (echo "${progname}: Cannot make temp dir ${tmpdir}"; exit 1)

trap "rm -f ${namefile}; rmdir ${tmpdir}" 0

# Get the list of names:
ar t $libname | grep -v '^__.SYMDEF' > $namefile

# Extract each one.  For the duplicates, we extract the first one
# and then move it (using the 'm' option to ar) to the end of the
# archive, so that the next time we extract that name we'll get the
# next one.
i=0
for f in `cat $namefile`; do
    if [ -f "$f" ]; then	# non-unique case (file exists):
	while [ -f ${f}_${i} ]; do # double check for existing files
	    i=`expr $i + 1`
	done
	name=${f}_${i}
	mv $f $name		# rename extracted first one
	ar m $libname $f	# move first one to end of archive
	ar x $libname $f	# extract next one
	i=`expr $i + 1`
    else			# it's unique, just extract it
	name=$f
	ar x $libname $f
	i=0			# reset name counter
    fi
    names="${names} ${name}"
done

# Now append '.o' to all the extracted files that don't have it already
# (due to truncation).
for n in $names; do
    if echo $n | /usr/bin/grep -s '\.o$'; then
	:
    else
	mv $n ${n}.o
    fi
done
