#! /bin/sh
prefix=/usr
exec_prefix=/usr
BINDIR=/usr/bin
LINK=gcc
LIBDIR=/usr/lib64
LIBS="-lpthread -lm -ldl -lstdc++ -lgcc_s -lgcc  "
CFLAGS="-fmessage-length=0 -grecord-gcc-switches -fstack-protector -O2 -Wall -D_FORTIFY_SOURCE=2 -funwind-tables -fasynchronous-unwind-tables -I../libffi/include"

# Extra options for Windows.  config.status sets these conditionals to either "" or "#".

EXTRALDFLAGS=""
#EXTRALDFLAGS="-mwindows -Wl,-u,WinMain"
##EXTRALDFLAGS="-mwindows -Wl,-u,WinMain"
##EXTRALDFLAGS="-mwindows -Wl,-u,_WinMain@16"
##EXTRALDFLAGS="-mwindows -Wl,-u,_WinMain@16"

#SUFFIX="obj"
SUFFIX="o"

# Extra options for Mac OS X
#EXTRALDFLAGS="-Wl,-no_pie"

TMPSRCFILE=/tmp/polysrc.$$
TMPOBJFILE=/tmp/polyobj.$$.$SUFFIX
trap 'rm -f $TMPSRCFILE $TMPOBJFILE' 0

compile()
{
    echo "use \"$1\"; PolyML.export(\"$2\", main);" | ${BINDIR}/poly -q --error-exit
}

link()
{
    if [ X"$2" = "X" ]
    then
        ${LINK} ${EXTRALDFLAGS} ${CFLAGS} $1 -L${LIBDIR} -lpolymain -lpolyml ${LIBS}
    else
        ${LINK} ${EXTRALDFLAGS} ${CFLAGS} $1 -o $2 -L${LIBDIR} -lpolymain -lpolyml ${LIBS}
    fi
}

printhelp()
{
    echo "Usage: polyc [OPTION]... [SOURCEFILE]"
    echo Compile and link a Standard ML source file with Poly/ML.
    echo
    echo "   -c           Compile but do not link.  The object file is written to the source file with .$SUFFIX extension."
    echo "   -o output    Write the executable file to 'output'"
    echo "   --help       Write this text and exit"
    exit
}

usage()
{
    echo $1
    echo "Usage: polyc [OPTION]... [SOURCEFILE]"
    exit 1
}

checkml()
{
    extension="${1##*.}"
    case "$extension" in
        sml|ML)
             return 0 ;;
        o|obj)
             return 1;;
        *)
             test -r $1 && file -b $1 | grep -q text ;;
    esac
}

sourcefile=""
objectfile=""
execfile=""
compileonly="no"

while [ $# -gt 0 ]
do
    case "$1" in
        --help)
            printhelp ;;
        -c) compileonly="yes";;
        -o)
            shift
            [ $# -eq 0 ] && usage "Expected file name after -o"
            execfile="$1";;
        *)
            [ X"$sourcefile" = "X" ] || usage "Only one source file name allowed"
            sourcefile="$1";;
    esac
    shift
done

[ X"$sourcefile" = "X" ] && usage "No input files"
[ -r "$sourcefile" ] || usage "Error: $sourcefile: No such file"

case "$compileonly" in
     yes)
         objectfile=${sourcefile%%.*}
         compile $sourcefile $objectfile
         ;;
     no)
         if checkml $sourcefile
         then
             compile $sourcefile $TMPOBJFILE && link $TMPOBJFILE $execfile
         else
             link $sourcefile $execfile
         fi
         ;;
esac
