#! /bin/bash
#
# patchexe.sh, version 1.1
# Written by Richard Dawe <rich@phekda.freeserve.co.uk>
#
# Rebuild Fileutils with patches for:
#
# *  __set_need_fake_dot_dotdot() bug in DJGPP 2.03.
#
#

# Debug
if [ "a$1" = "a-g" ]; then
    set -x
    shift
fi

# Check we that we're in the djgpp/ directory of the Fileutils sources.
# Check we can find some required files.
REQFILES="$(basename $0) opendir.c"
for i in ${REQFILES}; do
    if [ ! -r $i ]; then
	echo "$(basename $0) must be run in djgpp/ of the Fileutils sources"
	echo "Current directory is $(pwd)"
	exit 1
    fi
done

# Check that the DJGPP.ENV and DJGPP version header is present.
if [ ! -r ${DJDIR}/djgpp.env -o ! -r ${DJDIR}/include/sys/version.h ]; then
    echo \
"DJGPP not installed or corrupted in ${DJDIR} - please (re-)install djdev"
    exit 1
fi

# Check that we're linking against DJGPP 2.03.
if [ ! -r ${DJDIR}/manifest/djdev203.ver ]; then
    echo \
"DJGPP version is not 2.03:

* If you're using an earlier version, please upgrade to the latest.
* If you're using a later version, then you do not need to run
  this patch script."
    exit 1
fi

# Check that the library sources are installed.
if [ ! -d ${DJDIR}/src ]; then
    echo \
"DJGPP libc sources are not installed in ${DJDIR} - please install djlsr203"
    exit 1
fi

# Copy the gcc.opt file and nuke -Werror. gcc 3.x complains a lot more
# and so will barf on the library sources, if we use -Werror.
sed -e 's:-Werror::' ${DJDIR}/src/gcc.opt > gcc.opt

echo Compiling patched opendir.c...

if [ ! -r opendir.o ]; then
    cmd="gcc @gcc.opt -I${DJDIR}/include "
    cmd="$cmd -I${DJDIR}/src/libc/posix/dirent -c opendir.c"
    echo $cmd
    $($cmd)
fi

cd ../src
echo Changed into $(pwd)

PATCHOBJS=../djgpp/opendir.o
cat Makefile | sed -e "s:^\(LDADD.*\)$:\1 ${PATCHOBJS}:" > Makefile.djg

for i in *.exe; do
    echo Patching $i...
    rm -f $i
    make -f Makefile.djg $i
done
