#!/bin/bash
#
# Run Rasm51e through DOSBox.
# by Jim Paris <jim@jtan.com>
# Modified by Nelson Elhage <nelhage@mit.edu> to make it act less retarded

set -e

# If you have dosbox and wish to use this script on your own machine,
# just copy the files from /mit/6.115/share/rasm and change this variable.
RASMDIR=/mit/6.115/share/rasm

# Figure out what they want to assemble
if [ $# != 1 ] ; then
    echo Usage: $0 filename.asm
    echo Assembles 8051 code using Rasm51e through DOSBox.
    exit 1
fi

source="$1"
[ -e "$source" ] || source="$1".asm
[ -e "$source" ] || source="$1".ASM
if [ ! -e "$source" ] ; then
    echo "Error: can't find $1, $1.asm, or $1.ASM"
    exit 1
fi
base="`echo "$source" | sed s/.[aA][sS][mM]$//`"

# Warn if it uses any includes.  We won't sanitize these filenames.
# if grep -i '#include' "$source" >/dev/null 2>&1 ; then
#     echo "Warning: your source file uses the #include directive,"
#     echo "which may have problems with long or complex filenames."
# fi

# Make temp dir
TMP=/tmp/rasm-$$; export TMP
trap 'rm -rf $TMP' 0 1 2 15
mkdir -p $TMP

# Make a copy of the main asm file, prepending included files with "I:"
cp -f "$source" $TMP/TEMP.ASM

# Don't pop up any windows
SDL_VIDEODRIVER=dummy; export SDL_VIDEODRIVER

# Use DOSBox to assemble it
# echo "Executing DOSBox..."
set +e
dosbox -conf $RASMDIR/dosbox.conf \
    -c "mount c ." \
    -c "mount t $TMP" \
    -c "mount r $RASMDIR" \
    -c "c:" \
    -c "r:\\rasm51e.exe t:temp.asm -o -l -e > t:LOG" \
    -c "exit" \
    >$TMP/doslog 2>&1 
if [ $? -ne 0 ] || [ ! -e $TMP/TEMP.ERR ] ; then
    echo "Sorry, DOSBox failed.  Full output follows:"
    cat $TMP/doslog
    cat $TMP/LOG
    exit 1
fi
set -e

# Show output
# cat $TMP/LOG | sed -e 's/\r//'; echo

cp -f $TMP/TEMP.LST "$base".lst
cp -f $TMP/TEMP.ERR "$base".err

# Exit with proper result code
if head -1 $TMP/TEMP.ERR | grep '^0 error' >/dev/null 2>&1 ; then
    # Don't generate a .obj file unless the build succeeded, so make
    # works right.
    cp -f $TMP/TEMP.OBJ "$base".obj
    exit 0
else
    perl -pi -e "s/temp.asm/$source/" $TMP/TEMP.ERR
    perl -lne 's/\r$//; print "$1:$2: $3" if m{^t:([^ ]+)\s+(\d+)\s+(.+)$}' $TMP/TEMP.ERR
    exit 1
fi

