#!/usr/bin/env escript
%% -*- erlang -*-
a(L) -> list_to_atom(L).
main_([Node,Mod,Fun|Args]) ->
    %% FIXME: does tmp@ need to be disambiguated to avoid clashes?

    ThisNode=
        binary_to_atom(
          iolist_to_binary(
            io_lib:format("exo_call_~s@127.0.0.1",[os:getpid()])), utf8),
    %% io:format("ThisNode=~p~n",[ThisNode]),
    case net_kernel:start([ThisNode, longnames]) of
        {ok, _NetKernelPid} ->
            case os:getenv("EXO_COOKIE") of
                false ->
                    io:format("Need EXO_COOKIE~n");
                StrCookie ->
                    Cookie = a(StrCookie),
                    erlang:set_cookie(node(), Cookie),
                    case rpc:call(a(Node), a(Mod), a(Fun), Args) of
                        {ok, Text} ->
                            io:format("~s", [Text])
                    end
            end;
        Error ->
            %% FIXME: If epmd is not running, this will fail.  How to
            %% start epmd and try again?
            Report = io_lib:format("epmd not runnig? : ~p~n", [Error]),
            io:put_chars(standard_error, Report),
            halt(1)
    end.
            
main(Args) ->
    try main_(Args)
    catch C:E ->
            Report = io_lib:format("~p~n", [{C,E,erlang:get_stacktrace()}]),
            io:put_chars(standard_error, Report),
            halt(1)
    end.
