From a2d15bdd78f071549d46aa6ac5467a8a8cf6ebbd Mon Sep 17 00:00:00 2001 From: euxane Date: Sun, 24 Nov 2024 17:17:02 +0100 Subject: main: add module --- main.nim | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 main.nim (limited to 'main.nim') diff --git a/main.nim b/main.nim new file mode 100644 index 0000000..04a81f1 --- /dev/null +++ b/main.nim @@ -0,0 +1,97 @@ +# tickwatch +# Author: Euxane TRAN-GIRARD +# Licence: EUPL-1.2 + +import std/sugar +import std/math +import std/times +import std/net +import std/posix +import std/paths +import std/strutils +import std/parseopt + +import file +import ping +import logger + + +const + NAME = "tickwatch" + VERSION = staticExec(""" + command -v git >/dev/null && git describe --tags --always || echo $VERSION + """).strip() + HELP_TEXT = + staticRead("readme.md") + .split("```help", 1)[1] + .split("```", 1)[0] + .strip() + +proc registerTerminationHandlers() = + proc terminationHandler(sig: cint) {.noconv.} = flushAndQuit() + var action = SigAction(sa_handler: terminationHandler) + for signal in [SIGTERM, SIGHUP, SIGQUIT, SIGINT]: + discard sigaction(signal, action) + +proc main() = + var + scale: Scale = log2 + symbols = UNICODE_SYMBOLS + (min, max) = (0, 1000) + probe: (timeout: Duration) -> int + + for optKind, key, val in getopt(): + if optKind notin {cmdLongOption, cmdShortOption}: + raise newException(ValueError, "Invalid argument: " & key) + + case key: + + of "help", "h": + echo HELP_TEXT + quit(0) + + of "version", "v": + echo NAME & " " & VERSION + quit(0) + + of "scale": + case val: + of "logarithmic", "log", "log2": scale = log2 + of "log10": scale = log10 + of "ln": scale = ln + of "linear", "lin": scale = (val: float) => val + + of "symbols": + case val: + of "unicode", "utf8", "utf-8": symbols = UNICODE_SYMBOLS + of "numeric", "ascii": symbols = NUMERIC_SYMBOLS + + of "min": min = parseInt(val) + of "max": max = parseInt(val) + + of "ping": + let targetIp = parseIpAddress(val) + let mon = initPingMonitor(targetIp, procIdent()) + probe = (timeout: Duration) => mon.ping(timeout).inMilliseconds.int + + of "value": + let mon = initFileValueMonitor(Path val) + probe = (timeout: Duration) => mon.readValue() + + of "change": + let mon = initFileChangeMonitor(Path val) + probe = (timeout: Duration) => mon.readValue() + + if probe == nil: + raise newException(ValueError, "Missing monitor argument") + + loop(probe, (val: int) => symbols.indicator(min, max, val, scale)) + + +when not defined(test): + try: + registerTerminationHandlers() + main() + except CatchableError as err: + stderr.writeLine err.msg + quit(1) -- cgit v1.2.3