#!mkcmd
# $Id: rrdup.m,v 1.11 2007/10/22 17:46:37 ksb Exp $
from '<unistd.h>'
from '<stdlib.h>'
from '<string.h>'

basename "rrdup" ""
require "std_help.m" "std_version.m"
require "rrrdupdate.m"

from '"machine.h"'

%i
static char rcsid[] =
	"$Id: rrdup.m,v 1.11 2007/10/22 17:46:37 ksb Exp $";
%%

# require the envopt code from mkcmd, we should have a .m for that.
getenv;
int named "iErr" {
	local
}

char* named "pcDest" {
	param "[host:]port"
	user "iErr = rrrdupdate(%n, 0, 0, 0, 0);if (iErr < 0) {fprintf(stderr, \"%%s: rrrdupdate: %%s: %%d\\n\", %b, %n, iErr);exit(1);}"
	help "the destination for the RRD update"
}
left "pcDest" {
}

exit {
	named "Pump"
}

%c
static int u_envopt(char *, int *, char ***);
/* push the updated from stdin out to a remote RRD daemon		(orig)
 * update path.rrd -t template time:values
 * update path.srt -s name time:value 
 */
static void
Pump()
{
	int iErr, i, iArgC;
	char *pcIn, acLine[10*BUFSIZ];
	char **ppcArgs, *pcParam;
	static char *apcDummy[2] = {"rrdup", (char *)0}; // ZZZ make this take the real program base name

	while ((char *)0 != (pcIn = fgets(acLine, sizeof acLine, stdin))) {
		if((char *)0 != (pcParam = strrchr(pcIn, '\n')) )  {
			*pcParam = '\0';
		}
		iArgC = 0;
		ppcArgs =  apcDummy; 
		u_envopt(pcIn, &iArgC, &ppcArgs);
		if (iArgC < 4)
			continue;
		if (strcmp(ppcArgs[1], "update"))
			continue;
		if (!strcmp(ppcArgs[3], "--template") || !strcmp(ppcArgs[3], "-t")) {
			pcParam = ppcArgs[4];
			i = 5;
		} else {
			pcParam = NULL;
			i = 3;
		}
		for (; i < iArgC; ++i) {
			iErr = rrrdupdate(NULL, ppcArgs[2], pcParam, ppcArgs[i]);
			if (iErr < 0) {
				fprintf(stderr, "%s: %s: send datapoint: %d\n", progname, pcDest, iErr);
				exit(1);
			}
		}
	}
	exit(0);
}
%%
