#!/usr/local/bin/perl

# Copyright (C) 2006 Konosuke Watanabe <sasugaanija@gmail.com>


$cmd = $0;
$cmd =~ s/^(.*)\///;

if ($cmd eq "dgcc.pl") {
    $cc = "/usr/local/bin/gcc";
    $cross = "/usr/local/cross/arm-linux/bin/arm-linux-gcc"
} elsif ($cmd eq "dg++.pl") {
    $cc="/usr/local/bin/g++";
    $cross = "/usr/local/cross/arm-linux/bin/arm-linux-g++"
} else {
    die "unsupported command";
}

$cross_host = "yakumo";
$cross_dir = "/home/nosuke/cross";

$compileonly = 0;

$out = 0;
$skipcc = 0;

$outfile = "";
$infile = "";

foreach $arg (@ARGV) {

    if ($arg eq "-c") {
	$compileonly = 1;
	push(@arg_cpp, "-E");
	push(@arg_cc, $arg);
    } elsif ($arg eq "-o") {
	$out = 1;
	push(@arg_cpp, $arg);
	push(@arg_cc, $arg);
    } elsif ($arg =~ /^-i.*/
	     || $arg eq "-x"
	     || $arg eq "-aux-info"
	     || $arg eq "--param" 
	     || $arg eq "-isystem"
	     || $arg eq "-u" 
	     || $arg eq "-Xlinker" 
	     || $arg eq "-G") {
	$skipcc = 1;
	push(@arg_cpp, $arg);
    } elsif ($arg =~ /-Wp.*/) {
	push(@arg_cpp, $arg);	
    } elsif ($arg =~ /^[^-].*/) {
	if ($out) {
	    $out = 0;
	    $outfile = $arg;
	    push(@arg_cpp, "out_tmp.$$.c");
	    push(@arg_cc, "out_tmp.$$.o");
	} elsif ($skipcc) {
	    $skipcc = 0;
	    push(@arg_cpp, $arg);
	} else {
	    $infile = $arg;
	    push(@arg_cpp, $arg);
	    push(@arg_cc, "out_tmp.$$.c");
	}
    } else {
	push(@arg_cpp, $arg);
	push(@arg_cc, $arg);
    }

}

if (! $compileonly) {
    system($cc, @ARGV);
} else {

    if (system($cc, @arg_cpp) % 256) {
	die "*** cpp failed\n";
    }

    if (system("scp", "out_tmp.$$.c", "$cross_host:$cross_dir") % 256) {
	die "*** c-file scp failed\n";
    }


    open(SCRIPT, ">dgcc_$$.sh");

    print SCRIPT 'PATH=/usr/local/cross/arm-linux/bin:$PATH' . "\n";
    print SCRIPT "cd $cross_dir && $cross ";
    foreach $eacharg (@arg_cc) {
	$eacharg =~ s/"/\\"/g;	
	print SCRIPT $eacharg  . " ";
    }
    close(SCRIPT);

    if (system("scp", "dgcc_$$.sh", "$cross_host:$cross_dir") % 256) {
	die "*** script scp failed\n"
    }
    
    if (system("ssh", $cross_host, "( cd $cross_dir && sh dgcc_$$.sh )") % 256) {
	die "*** ssh failed\n";
    }

    if (system("scp", "$cross_host:$cross_dir/out_tmp.$$.o", $outfile) % 256) {
	die "*** object scp failed\n"
    }

    system("rm dgcc_$$.sh");
    system("rm out_tmp.$$.c");

    system("ssh", $cross_host, "rm $cross_dir/out_tmp.$$.c $cross_dir/out_tmp.$$.o $cross_dir/dgcc_$$.sh");
}

