#!/usr/bin/env escript

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

main(Args) ->
    init_network(),
    [BitbucketUrl, BitbucketUserId, BitbucketUserPass, EnterpriseName] = parse_args(Args),
		EntId = case rpc_call(?TARGET, deliv_enterprise, fetch, [EnterpriseName]) of
			{ok, Enterprise} ->
				rpc_call(?TARGET, deliv_enterprise, getval, [id, Enterprise]);
			{error, not_found} ->
				perror(io:format("Error: Enterprise ~p not found~n", [EnterpriseName]));
			{error, Reason} ->
				perror(io:format("Error: Enterprise ~p fetch failed with error: ~p~n", [EnterpriseName, Reason]))
		end,
    case rpc_call(?TARGET, bitbucket_basic_auth, save_basic_auth_credentials, [BitbucketUrl, BitbucketUserId, BitbucketUserPass, EntId]) of
        {ok, _} ->
            io:format("Successfully added new Bitbucket configuration.~n");
        {error, conflict} ->
            perror(io:format("Error: Bitbucket configuration already exists!~n"));
        {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([_BitbucketUrl, _BitbucketUserId, _BitbucketUserPass,
            _EnterpriseName] = Args) ->
    Args;
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).
