#!/usr/bin/env perl

use File::Basename;
use Cwd;
$cwd = dirname Cwd::abs_path($0);

$i = 0;
while ($i < @ARGV) {
    $arg = $ARGV[$i];
    if ($arg =~ /-i|-p|-l|-s|-r|-f|-c/) {
        push @args, $ARGV[$i];
        $i++;
        push @args, $ARGV[$i];
        $i++;
    } elsif ($arg eq "-h") {
        print_help();
        exit 0;
    } elsif ($arg eq "-v") {
        print_version();
        exit 0;
    } elsif ($arg =~ /^-/) {
        print_help();
        exit 1;
    } else {
        $option_num = @args;
        while ($i < @ARGV) {
            push @pgms, $ARGV[$i];
            $i++;
        }
    }
}

print_help() and exit 1 unless defined @pgms;

$cmd = "@pgms @args $option_num";
exec $cmd or die "Cannot execute this command: $cmd\n";

sub print_help {
    print STDERR 
        "dmirun : execute a DMI process

====== usage ======
dmirun
        [-i hostname_or_ip_addr]
        [-p port_number]
        [-l listen_port_number]
        [-s memmory_size]
        [-c]
        [-h]
        [-v]
        $pgm arguments...

====== options ======
-i hostname_or_ip_address : hostname or ip address of the host which will be 
        connected firstly. If you omit this option, this process becomes the 
        \"first\" DMI process (which will be connected by other DMI processes 
        later).
-p port_number : port number of the host which will be connected firstly. 
        If you omit this option, the 7880 port is used.
-l listen_port_number : port number listened by this process. If you omit 
        this option, the 7880 port is used.
-s memory_size : memory size provided by this process
-c : exit immediately when DMI_xxx() is going to return FALSE
-h : print this message
-v : print version

See http://haraken.info/ for more details.
";
}

sub print_version {
    print STDERR 
        "DMI version ".`$cwd/dmiversion`." by haraken
See also http://haraken.info/dmi/ for more details.
";
}
