#!/bin/sh

# This script wraps around m68k-elf-gcc, providing a cross compiler
# interface similar to that provided by gcc for native compilations.
# That is, both single-file compilations and multiple-file builds are
# supported.

# Written by Jason Foo <foo-jr@ee.uwa.edu.au>
# Last updated on 20 September 2002

# Define program names.
CC=m68k-elf-gcc
OBJCOPY=m68k-elf-objcopy

# Define the compiler options.
ASFLAGS="-Wa,-I\"$ROBIOS/include\",--register-prefix-optional"
CFLAGS="-m68332 -I\"$ROBIOS/include\" -fomit-frame-pointer"
LDLIBS="-L\"$ROBIOS/lib\""
SCRIPT="-Wl,-T\"$ROBIOS/ldfiles/robi-ram.ld\""

# Abort with an error message if no files were specified.
if test -z "$*"
then
    echo "$0: no input files."
    exit 1
fi

# Determine whether to perform linking or not.
LINK=1
for ARGUMENT in $*
do
    # Don't link if -c option specified.
    if test "${ARGUMENT:0:2}" = -c
    then
        LINK=0
    fi
    # Don't link if -S option specified.
    if test "${ARGUMENT:0:2}" = -S
    then
        LINK=0
    fi
    # Don't link if -E option specified.
    if test "${ARGUMENT:0:2}" = -E
    then
        LINK=0
    fi
    # Don't link if -M? option specified.
    if test "${ARGUMENT:0:2}" = -M
    then
        LINK=0
    fi
done

if test $LINK = 1
then
    # Determine the output file name.
    TARGET=a.out
    THISTIME=0
    for ARGUMENT in $*
    do
        if test $THISTIME = 1
        then
            TARGET="$ARGUMENT"
            THISTIME=0
        fi
        if test "${ARGUMENT:0:2}" = -o
        then
            TARGET="${ARGUMENT:2}"
            if test -z "$TARGET"
            then
                THISTIME=1
            fi
        fi
    done

    # Run the compiler.
    eval $CC $ASFLAGS $CFLAGS -nostdlib $LDLIBS $* $SCRIPT || exit $?

    # Convert the ELF executable to S records.
    if test -f "$TARGET"
    then
	ELF="${TARGET%.hex}.elf"
	mv "$TARGET" "$ELF"
	$OBJCOPY -O srec --gap-fill=0 "$ELF" "$TARGET"
	chmod -x "$ELF" "$TARGET"
    fi
else
    # Run the compiler.
    eval $CC $ASFLAGS $CFLAGS $* || exit $?
fi
