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

%% @author Mark Mzyk <mmzyk@opscode.com>
%% @copyright (c) 2014 Chef Software, Inc <legal@getchef.com>

%% Needed so that this escript isn't run in interpretive mode. It makes use
%% of timer:tc which uses apply, so it needs to have the funs it's going to
%% reference already defined.
-mode(compile).
%% Need to export all functions that will be run by apply
-export([call_reporting/3]).

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,
  refresh_matviews(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())).

refresh_matviews(Send) ->
  ReqId = generate_request_id(),
  %% Time how long this call takes to get a rough idea how long the refresh_matviews sql
  %% function takes. This will include some overhead, but there is no way to get
  %% postgres to return for a single function how long it takes while executing the function
  %% (There are options, such as the slow query log, but for that we need to pull the data
  %% from splunk and inject into graphite - which might be possibly using the splunk rest api)

  {Microseconds, {ok, RowsUpdated}} = timer:tc(?MODULE, call_reporting, [reporting_db, refresh_matviews, [ReqId]]),

  GraphitePath = "reporting.refresh_matviews.duration",
  Message = [GraphitePath, " " , to_secs(Microseconds), " " , integer_to_list(get_timestamp())],
  Send(Message),

  GraphitePath2 = "reporting.refresh_matviews.rows_updated",
  Message2 = [GraphitePath2, " ", integer_to_list(RowsUpdated), " ", integer_to_list(get_timestamp())],
  Send(Message2).

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).

-spec to_secs(Microseconds :: number()) -> list().
to_secs(Microseconds) ->
  Seconds = Microseconds / 1.0e6,
  io_lib:format("~.6f",[Seconds]).
