#!/usr/bin/env escript

-define(SELF, 'github_link@127.0.0.1').
-define(TARGET, 'delivery@127.0.0.1').
-define(COOKIE, 'delivery').

main(Args) ->
    init_network(),
    [{Ent,Org,Proj},{GithubOwner,GithubRepo}] = parse_args(Args),
    case rpc_call(?TARGET, deliv_github_api, link_project, [Ent, Org, Proj, GithubOwner, GithubRepo]) of
        ok ->
            io:format("Success! Delivery project ~s linked to ~s/~s.~n~n", [Proj, GithubOwner, GithubRepo]);
        {error, Why} ->
            perror(io:format("Error: ~p~n", [Why]))
    end.

init_network() ->
    net_kernel:start([?SELF, longnames]),
    erlang:set_cookie(node(), ?COOKIE),
    pong = net_adm:ping(?TARGET).

parse_args([EntName, OrgName, ProjName, GithubRepoOwner, GithubRepoName]) ->
    [{EntName,OrgName,ProjName}, {GithubRepoOwner, GithubRepoName}];
parse_args(Other) ->
    perror(io:format("Invalid Arguments: ~p~n", [Other])).

rpc_call(Node, Module, Function, Args) ->
    case rpc:call(Node, Module, Function, Args) of
        {badrpc, Reason} ->
            perror(io_lib:format("RPC call ~p:~p:~p:~p failed with error ~p~n",
                                 [Node, Module, Function, Args, Reason]));
        Res ->
            Res
    end.

perror(Msg) ->
    io:format(Msg),
    erlang:halt(1).
