#!/bin/bash

tmpsrc=/tmp/cscript-$$.c
tmpexe=/tmp/cscript-$$

if [ $# -eq 0 -o ! -f "$1" ]; then
    echo "$1 is not an existing file."
    echo "usage: cscript <C script file> [ <arguments>... ]"
    echo "Runs gcc to compile the single-file C program containing a shebang line in its first line and executes it with the given arguments."
    exit
fi

origsrc="$1"

shift

declare -a argvdefs
argvdefs=( "$@" )
for (( i= 1; i <= $# ; i= i+1 )); do
    argvdefs[$i-1]="-DARGV$i=${argvdefs[$i-1]}"
done

tail -n +2 "$origsrc" > $tmpsrc

gccargs=`sed -n '1,/^$/p' $tmpsrc | grep ^gcc`
gccargs="${gccargs#* }"

if [ -n "$gccargs" ]; then
    gccargs=" $gccargs"
    exe=`echo $gccargs | sed 's/^.* -o *\([^ ]*\).*$/\1/'`
    if [ "$exe" = "$gccargs" -o -z "$exe" ]; then
        gccargs="-o $tmpexe $gccargs"
        exe="$tmpexe"
    fi
    dir="${origsrc%/*}"
    baresrc="${origsrc##*/}"
    gccargs=`echo $gccargs | sed s!$baresrc!$tmpsrc!`
    cd "$dir"
    echo gcc "${argvdefs[@]}" $gccargs
    gcc "${argvdefs[@]}" $gccargs
    status=$?
    cd -
    if [ "${exe#/}" != "$exe" ]; then
        exe="$dir/$exe"
    else
        exe="./$exe"
    fi
    if [ $status -eq 0 ]; then
        "$exe" "$@"
        status=$?
    fi
else
    gcc -o $tmpexe "${argvdefs[@]}" $tmpsrc && $tmpexe "$@"
    status=$?
fi

rm -f $tmpexe $tmpsrc

exit $status

