#!/usr/bin/env escript
%%! -name oc_reporting_usage_stats@127.0.0.1 -setcookie oc_reporting -hidden

%% @author Mark Mzyk <mmzyk@opscode.com>
%% @copyright 2013 Opscode Inc

main(Args) ->
  init_code_path(),
  ok = application:start(crypto), %% ensure crypt is started, used by oc_wm_request
  PropList = extract_args(Args),
  Send = fun(Message) -> send_to_graphite(PropList, Message) end,
  report_unique_orgs(Send),
  report_unique_nodes(Send).

extract_args([]) ->
  handle_error_and_exit(4, "No args were given: need graphite ip and port");
extract_args([Arg1|ArgList]) ->
  %% Basic arg checking. Return a proplist of expected args
  GraphiteHost = case inet_parse:address(Arg1) of
                {ok, IPTuple} ->
                  IPTuple;
                _ ->
                  handle_error_and_exit(4, "First arg must be a valid ip address for graphite")
              end,
  [Arg2|_Tail] = ArgList, %% Pull Arg2 from the remaing list
  GraphitePort = try list_to_integer(Arg2) of
                   Port ->
                      Port
                 catch
                   error:badarg ->
                    handle_error_and_exit(4, "Second arg must be a valid port for graphite")
                 end,
  %% Any extra args are just ignored
  [{graphite_host, GraphiteHost}, {graphite_port, GraphitePort}].

init_code_path() ->
  code:add_paths(filelib:wildcard("../lib/opscoderl_wm*/ebin", escript:script_name())).

report_unique_orgs(Send) ->
  NumOrgs = get_unique_orgs_last_hour(),
  GraphitePath = "reporting.usage.org_hits_last_hour",
  Message = [GraphitePath, " " , integer_to_list(NumOrgs), " " , integer_to_list(get_timestamp())],
  Send(Message).

report_unique_nodes(Send) ->
  NumNodes = get_unique_nodes_last_hour(),
  GraphitePath = "reporting.usage.node_hits_last_hour",
  Message = [GraphitePath, " ", integer_to_list(NumNodes), " ", integer_to_list(get_timestamp())],
  Send(Message).

get_unique_orgs_last_hour() ->
  ReqId = generate_request_id(),
  {ok, NumOrgs} = call_reporting('reporting_db', 'unique_orgs_last_hour', [ReqId]),
  NumOrgs.

get_unique_nodes_last_hour() ->
  ReqId = generate_request_id(),
  {ok, NumNodes} = call_reporting('reporting_db', 'unique_nodes_last_hour', [ReqId]),
  NumNodes.

generate_request_id() ->
  oc_wm_request:make_req_id().

call_reporting(Mod, Fun, Args) ->
  Node = reporting_node(),
  case rpc:call(Node, Mod, Fun, Args) of
    {badrpc, Reason} ->
        handle_error_and_exit(2, Reason);
    {error, Error} ->
        handle_error_and_exit(2, Error);
    Result ->
        Result
  end.

reporting_node() ->
  'oc_reporting@127.0.0.1'.

send_to_graphite(Config, Message) ->
  GraphiteHost = proplists:get_value(graphite_host, Config),
  GraphitePort = proplists:get_value(graphite_port, Config),
  Socket = case gen_tcp:connect(GraphiteHost, GraphitePort, [binary, {packet, 0}]) of
            {ok, OpenSocket} ->
              OpenSocket;
            {error, Reason} ->
              handle_error_and_exit(3, Reason)
           end,
  case gen_tcp:send(Socket, [Message, "\n"]) of
    ok ->
      ok;
    {error, Reason2} ->
      handle_error_and_exit(3, Reason2)
  end,
  gen_tcp:close(Socket).

get_timestamp() ->
  {MegaSecs, Secs, _MicroSecs} = now(),
  %% now() is a timestamp tuple. Use math to convert to a unix epoch integer
  %% The math is based on the unixtime fun found in estatsd
  %% https://github.com/RJ/estatsd
  MegaSecs * 1000000 + Secs.

handle_error_and_exit(ExitCode, Message) ->
  io:format(standard_error, "~p~n", [Message]),
  halt(ExitCode).

