#!/bin/sh

usage="\
$0 <jpeg-dir>
    will cause jpeg to be built and installed into the
    directory which contains this script.
    
    You will need to have OPENRSDK installed, either at
    /usr/local/OPEN_R_SDK, or else set the OPENRSDK_ROOT
    environment variable.
    
    The patch contained within this script was relative to
    the jpeg-6b release, and may need to be tweaked
    or replaced to support newer versions...
";


if [ $# -lt 1 -o "$1" == "-h" -o "$1" == "--help" ] ; then
	printf "$usage";
	exit 2;
fi;

pushd "`dirname \"$0\"`"
TGT="`pwd`";
popd;

pushd "$1";

echo "Configuring..."
./configure --prefix="$TGT" --disable-shared mipsel-linux
if [ "$?" -gt 0 ] ; then
    echo "Configure failed.";
    exit 1;
fi;

echo "Patching..."
patch -p1 <<'EOF'
diff -ru jpeg-6b/Makefile jpeg-6b-aperios/Makefile
--- jpeg-6b/Makefile	Thu Mar 17 14:31:05 2005
+++ jpeg-6b-aperios/Makefile	Thu Mar 17 14:28:41 2005
@@ -5,6 +5,9 @@
 
 # Read installation instructions before saying "make" !!
 
+OPENRSDK_ROOT?=/usr/local/OPEN_R_SDK
+ORBIN=$(OPENRSDK_ROOT)/bin/mipsel-linux-
+
 # For compiling with source and object files in different directories.
 srcdir = .
 
@@ -20,10 +23,10 @@
 mandir = $(prefix)/man/man$(manext)
 
 # The name of your C compiler:
-CC= gcc
+CC= $(ORBIN)gcc
 
 # You may need to adjust these cc options:
-CFLAGS= -O2  -I$(srcdir)
+CFLAGS= -O3  -I$(srcdir) -frename-registers -fomit-frame-pointer -ffast-math
 # Generally, we recommend defining any configuration symbols in jconfig.h,
 # NOT via -D switches here.
 # However, any special defines for ansi2knr.c may be included here:
@@ -60,9 +63,9 @@
 # directory creation command
 MKDIR= mkdir
 # library (.a) file creation command
-AR= ar rc
+AR= $(ORBIN)ar rc
 # second step in .a creation (use "touch" if not needed)
-AR2= ranlib
+AR2= $(ORBIN)ranlib
 # installation program
 INSTALL= /usr/bin/install -c
 INSTALL_PROGRAM= ${INSTALL}
@@ -133,7 +136,7 @@
 TROBJECTS= jpegtran.$(O) rdswitch.$(O) cdjpeg.$(O) transupp.$(O)
 
 
-all:  libjpeg.$(A) cjpeg djpeg jpegtran rdjpgcom wrjpgcom
+all:  libjpeg.$(A) 
 
 # Special compilation rules to support ansi2knr and libtool.
 .SUFFIXES: .lo .la
Only in jpeg-6b: config.log
Only in jpeg-6b: config.status
EOF
if [ "$?" -gt 0 ] ; then
    echo "Patching failed.";
    exit 1;
fi;


echo "Making..."
make;
if [ "$?" -gt 0 ] ; then
    echo "Make failed.";
    exit 1;
fi;

echo "Installing..."
make install-lib;
if [ "$?" -gt 0 ] ; then
    echo "Make install failed.";
    exit 1;
fi;

