#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <locale.h>
#include <libintl.h>
#include <stdlib.h>
#include <unistd.h>
#include <pkglib.h>
#define COMMAND '!'
#define LSIZE 256
#define ERR_NOTROOT "You must be \"root\" for %s to execute properly."
static void usage(void);
static int docmd(char *cmd, char *file, char *input);
int
main(int argc, char *argv[])
{
FILE *fpout, *fp;
char line[LSIZE],
*pt,
*keyword,
*input,
*cmd,
*srcfile,
*destfile;
int flag;
char *prog;
(void) setlocale(LC_ALL, "");
#if !defined(TEXT_DOMAIN)
#define TEXT_DOMAIN "SYS_TEST"
#endif
(void) textdomain(TEXT_DOMAIN);
prog = set_prog_name(argv[0]);
if (getuid()) {
progerr(gettext(ERR_NOTROOT), prog);
exit(1);
}
if (argc != 5)
usage();
cmd = argv[1];
keyword = argv[2];
srcfile = argv[3];
destfile = argv[4];
srcfile = argv[3];
if ((fp = fopen(srcfile, "r")) == NULL) {
progerr(gettext("unable to open %s"), srcfile);
exit(1);
}
input = tempnam(NULL, "sedinp");
if ((fpout = fopen(input, "w")) == NULL) {
progerr(gettext("unable to open %s"), input);
exit(2);
}
flag = (-1);
while (fgets(line, LSIZE, fp)) {
for (pt = line; isspace(*pt); )
++pt;
if (*pt == '#')
continue;
if (*pt == COMMAND) {
if (flag > 0)
break;
pt = strtok(pt+1, " \t\n");
if (!pt) {
progerr(gettext("null token after '!'"));
exit(1);
}
flag = (strcmp(pt, keyword) ? 0 : 1);
} else if (flag == 1) {
(void) fputs(line, fpout);
}
}
(void) fclose(fpout);
if (flag > 0) {
if (docmd(cmd, destfile, input)) {
progerr(gettext("command failed <%s>"), cmd);
exit(1);
}
}
(void) unlink(input);
return (0);
}
static int
docmd(char *cmd, char *file, char *input)
{
char *tempout;
char command[256];
tempout = tempnam(NULL, "temp1");
if (!tempout)
return (-1);
(void) sprintf(command, "%s -f %s <%s >%s", cmd, input, file, tempout);
if (system(command))
return (-1);
(void) sprintf(command, "cp %s %s", tempout, file);
if (system(command))
return (-1);
(void) unlink(tempout);
free(tempout);
return (0);
}
static void
usage(void)
{
(void) fprintf(stderr, gettext("usage: %s cmd keyword src dest\n"),
get_prog_name());
exit(2);
}