#!/bin/sh

# Settings

PKG_NAME=pgplot
NCORES=`sysctl hw.ncpu | awk '{print $2}'`

# Work out the root directory

pushd ../.. > /dev/null
ROOT_DIR=`pwd`
popd > /dev/null

# Create the madsdk configuration directory in the source tree

SRC_DIR=$ROOT_DIR/src/$PKG_NAME

rm -rf ${SRC_DIR}/sys_madsdk
mkdir ${SRC_DIR}/sys_madsdk

cat > ${SRC_DIR}/sys_madsdk/gfortran.conf <<EOF
XINCL="-I/usr/X11R6/include"
FCOMPL="gfortran"
FFLAGC="-Wall -fPIC -O"
CCOMPL="gcc"
CFLAGC="-Wall -fPIC -DPG_PPU -O"
CFLAGD="-Wall -O"
PGBIND_FLAGS="bsd"
LIBS="-L/usr/X11R6/lib -lX11"
RANLIB="ranlib"
SHARED_LIB="libpgplot.dylib"
SHARED_LD="gcc -shared -o libpgplot.dylib"
SHARED_LIB_LIBS="-L/usr/X11R6/lib -lX11 -lpng -L${ROOT_DIR}/lib -lgfortran"
EOF

# Change into build dir

BUILD_DIR=${SRC_DIR}_build

rm -rf $BUILD_DIR
mkdir $BUILD_DIR

echo "Building in $BUILD_DIR"

cd $BUILD_DIR

# Copy over a customized driver list

sed -e "s/^! PNDRIV/ PNDRIV/" \
    -e "s/^! PSDRIV/ PSDRIV/" \
    -e "s/^! XWDRIV/ XWDRIV/" ${SRC_DIR}/drivers.list > drivers.list

# Make the makefile

$SRC_DIR/makemake $SRC_DIR madsdk

# Fix a bogus dependency on PNG headers

sed -e 's|\./png\.h||' \
    -e 's|\./pngconf\.h||' \
    -e 's|\./zlib\.h||' \
    -e 's|\./zconf\.h||' -i .old makefile

# Build

make -j$NCORES

# Install

rm -rf ${ROOT_DIR}/pgplot
mkdir ${ROOT_DIR}/pgplot

cp -a libpgplot.a libpgplot.dylib grfont.dat rgb.txt pgxwin_server ${ROOT_DIR}/pgplot/

ln -sf ../pgplot/libpgplot.a ${ROOT_DIR}/lib/libpgplot.a
ln -sf ../pgplot/libpgplot.dylib ${ROOT_DIR}/lib/libpgplot.dylib

# Finish
