#!/bin/sh
#
# Erlang compiler shell script
# Compiles a module (-shared)
#
# To execute need to invoke execution stub
# We also need a program to make an executable (ie. include stub)
#

ERL=$HOME/gerl
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:$ERL/erlib/:$ERL/lib/:./
export LD_LIBRARY_PATH
#echo $LD_LIBRARY_PATH

OS=`uname`

#
# Check compile options
#

if [ `echo $1 | cut -c1` = '-' ] ; then
    case $1 in
       '-static'):
            prog=$3
            flags="-s $2"
            opt=-g
            static=-p
            ;;
       '-debug'):
            prog=$2
            flags=-d
            opt=-g
            static=
            ;;
       '-opt'):
            prog=$2
            flags=
            opt=-O3
            static=
            ;;
       '-o'):
            soname=$2
            prog=$3
            flags=
            static=
            opt=-O2 -g
            ;;
       *):
            prog=$1
            flags=
            opt=-g
            static=
            ;;
    esac
else
    prog=$1
    flags= 
    opt=-g
    static=
fi

if [ ! -f $prog ] ; then
    echo Unable to find $1
    exit 1
fi

outname=`echo $prog | cut -f1 -d'.'`

if [ x$soname = x ] ; then
    soname=$outname
fi

$ERL/bin/driver $flags $prog > $outname.c

if [ ! -s $outname.c ] ; then
    echo $outname.c is an empty file, compilation failed.
    exit 1
fi

if [ $OS = 'Linux' ] ; then
    if [ x$static = 'x-p' ] ; then
        gcc $static $opt -I$ERL/lib/ -L$ERL/lib/ $outname.c $ERL/lib/bif.c $ERL/lib/erlang.c -ldl $ERL/lib/liberl.a $ERL/lib/GC/gc.a
    else
	    echo gcc $static $opt -rdynamic -I$ERL/lib/ -shared -Wl,-soname,$outname.so.t -o $soname.so $outname.c -Llib/
	    gcc $static $opt -fPIC -rdynamic -I$ERL/lib/ -shared -Wl,-soname,$outname.so.t -o $soname.so $outname.c -Llib/
    fi
else
	gcc -fPIC -g -c -I$ERL/lib/ $outname.c  
#	gcc -shared -o $soname.so $outname.o -Llib/liberl.a
	gcc -g -I$ERL/lib/ -shared -o $soname.so $outname.c -Llib/ 
    rm $outname.o

fi

#ar crs $1.so $1.$$.o
# 'ar' the .o now?

