import std/[os, strutils]

import posix

proc getFileSize(path: string): BiggestInt =
  var rawInfo: Stat
  if stat(path, rawInfo) < 0'i32:
    raiseOSError(osLastError(), path)
  rawInfo.st_size

let
  hostname = getEnv("COLLECTD_HOSTNAME", "localhost")
  interval = max(60, getEnv("COLLECTD_INTERVAL", "0").parseFloat.int)
  args = commandLineParams()

doAssert(args.len == 1, "pass only the NNCP spool directry as an argument")

type DirStats =  tuple[size: BiggestInt, packets: int]

proc sumDir(path: string): DirStats =
  for kind, path in walkDir path:
    if kind == pcFile:
      result.size = result.size + getFileSize(path)
      inc result.packets

while true:
  var stats: tuple[rx: DirStats, tx: DirStats]
  for kind, path in walkDir args[0]:
    if kind == pcDir:
      block:
        var rx = sumDir(path / "rx")
        stats.rx.size = stats.rx.size + rx.size
        stats.rx.packets.inc rx.packets
      block:
        var tx = sumDir(path / "tx")
        stats.tx.size = stats.tx.size + tx.size
        stats.tx.packets.inc tx.packets
  stdout.writeLine("""PUTVAL "$#/exec-nncp/bytes-rx" interval=$# N:$#""" %
    [hostname, $interval, $stats.rx.size])
  stdout.writeLine("""PUTVAL "$#/exec-nncp/pending_operations-rx" interval=$# N:$#""" %
    [hostname, $interval, $stats.rx.packets])
  stdout.writeLine("""PUTVAL "$#/exec-nncp/bytes-tx" interval=$# N:$#""" %
    [hostname, $interval, $stats.tx.size])
  stdout.writeLine("""PUTVAL "$#/exec-nncp/pending_operations-tx" interval=$# N:$#""" %
    [hostname, $interval, $stats.tx.packets])
  flushFile stdout
  sleep interval*1000
