#!/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},OauthAppName] = parse_args(Args),
    case rpc_call(?TARGET, deliv_github_api, link_project, [Ent, Org, Proj, GithubOwner, GithubRepo, OauthAppName]) of
        {ok, Url} ->
            io:format("Please go to the URL below to finish the process:~n~s~n", [Url]);
        {error, Why, Desc} ->
            perror(io:format("Error: ~p -- ~p~n", [Why, Desc]))
    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, OauthAppName]) ->
    [{EntName,OrgName,ProjName},
     {GithubRepoOwner, GithubRepoName},
     OauthAppName];
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).
