blob: ed8118601a60ca7e6582de80056243ac3c5ce6e9 [file] [log] [blame]
Lev Walkinc9b2f282017-11-05 20:32:15 -08001/*
2 * Since working awk is not present on every supported platform
3 * (notably Solaris), and nawk is not the same on Solaris and Linux,
4 * this program is a replacement for it to extract test parameter from the.
5 * string specified in the command line.
6 */
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <sysexits.h>
11
12static void
13usage(const char *progname) {
14 fprintf(stderr, "Search PARAM=VALUE pattern in the given string\n");
15 fprintf(stderr, "Usage: %s <parameter-name> <default-value> <string>\n",
16 progname);
17}
18
19static const char *
20search(const char *param, const char *haystack) {
21
22 const char *p = strstr(haystack, param);
23 if(p && p[strlen(param)] == '=') {
24 const char *param_begin = &p[strlen(param) + 1];
25 const char *param_end = param_begin;
26 for(param_end = param_begin; param_end; param_end++) {
27 switch(*param_end) {
28 case '0' ... '9':
29 continue;
30 default:
31 break;
32 }
33 break;
34 }
35
36 static char static_buf[64];
37
38 if((param_end - param_begin) <= 0) {
39 fprintf(stderr, "Parameter %s is malformed after '='\n", param);
40 return NULL;
41 }
42
43 if((param_end - param_begin) >= (ssize_t)sizeof(static_buf)) {
44 fprintf(stderr, "Parameter %s value exceeds buffer size %zu\n",
45 param, sizeof(static_buf));
46 return NULL;
47 }
48
49 memcpy(static_buf, param_begin, param_end - param_begin);
50 static_buf[param_end - param_begin] = '\0';
51 return static_buf;
52 } else if(p) {
53 fprintf(stderr, "Parameter %s should contain '='\n", param);
54 return NULL;
55 }
56
57 return NULL;
58}
59
60int
61main(int ac, char **av) {
62 if(ac != 4) {
63 usage(av[0]);
64 exit(EX_USAGE);
65 }
66
67 const char *value = search(av[1], av[3]);
68 if(value) {
69 printf("%s\n", value);
70 } else {
71 printf("%s\n", av[2]);
72 }
73}