#!/bin/sh

if [ "$#" = 0 ]; then
    echo "usage: $0 [-w wrapper] <C code...>" >&2
    exit 1
fi

if [ "$1" = -w ]; then
    wrapper="$2"
    shift 2
fi

f=$(mktemp -d -t gccrun.XXXXXXXX) || exit 1
if [ "${0##*/}" = "g++run" ]; then
    file="$f/command.cc"
    compiler="g++"
    cat > "$file" << EOF
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>

using namespace std;
EOF
else
    file="$f/command.c"
    compiler="gcc"
    cat > "$file" << EOF
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/syscall.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
EOF
fi

cat >> "$file" << EOF
int
main(int argc, char *argv[], char *envp[])
{
	$@;
	return 0;
}
EOF
"$compiler" -o "$f/command" "$file"
if [ -n "$wrapper" ]; then
    "$wrapper" "$f/command"
else
    "$f/command"
fi
r=$?
rm -r "$f"
exit $r
