3e92a861dbd11f9a7c7d210110429603822a62e1
[reactos.git] / reactos / tools / mkconfig.c
1 #include <string.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4
5 #define max(a, b) ((a) > (b) ? (a) : (b))
6
7 int
8 write_if_change(char* outbuf, char* filename)
9 {
10 FILE* out;
11 unsigned int end;
12 char* cmpbuf;
13 unsigned int stat;
14
15 out = fopen(filename, "rb");
16 if (out == NULL)
17 {
18 out = fopen(filename, "wb");
19 if (out == NULL)
20 {
21 fprintf(stderr, "Unable to create output file\n");
22 return(1);
23 }
24 fputs(outbuf, out);
25 fclose(out);
26 return(0);
27 }
28
29 fseek(out, 0, SEEK_END);
30 end = ftell(out);
31 cmpbuf = malloc(end);
32 if (cmpbuf == NULL)
33 {
34 fprintf(stderr, "Out of memory\n");
35 fclose(out);
36 return(1);
37 }
38
39 fseek(out, 0, SEEK_SET);
40 stat = fread(cmpbuf, 1, end, out);
41 if (stat != end)
42 {
43 fprintf(stderr, "Failed to read data\n");
44 fclose(out);
45 return(1);
46 }
47 if (end == strlen(outbuf) && memcmp(cmpbuf, outbuf, end) == 0)
48 {
49 fclose(out);
50 return(0);
51 }
52
53 fclose(out);
54 out = fopen(filename, "wb");
55 if (out == NULL)
56 {
57 fprintf(stderr, "Unable to create output file\n");
58 return(1);
59 }
60
61 stat = fwrite(outbuf, 1, strlen(outbuf), out);
62 if (strlen(outbuf) != stat)
63 {
64 fprintf(stderr, "Unable to write output file\n");
65 fclose(out);
66 return(1);
67 }
68 fclose(out);
69 return(0);
70 }
71
72 int
73 main(int argc, char* argv[])
74 {
75 int include_tests;
76 unsigned int i;
77 char* outbuf;
78 char* s;
79 char config[512];
80
81 if (argc == 1)
82 {
83 fprintf(stderr, "Not enough arguments\n");
84 return(1);
85 }
86
87 outbuf = malloc(256 * 1024);
88 if (outbuf == NULL)
89 {
90 fprintf(stderr, "Out of memory 1\n");
91 return(1);
92 }
93
94 s = outbuf;
95 s = s + sprintf(s, "/* Automatically generated, ");
96 s = s + sprintf(s, "Edit the Makefile to change configuration */\n");
97 s = s + sprintf(s, "#ifndef __INCLUDE_CONFIG_H\n");
98 s = s + sprintf(s, "#define __INCLUDE_CONFIG_H\n");
99 strcpy(config, "");
100 include_tests = 0;
101 for (i = 2; i < argc; i++)
102 {
103 if (strcmp(argv[i], "REGTESTS") == 0)
104 {
105 include_tests = 1;
106 }
107 s = s + sprintf(s, "#define %s\n", argv[i]);
108 strcat(config, argv[i]);
109 if (i != (argc - 1))
110 {
111 strcat(config, " ");
112 }
113 }
114 if (include_tests)
115 {
116 s = s + sprintf(s, "#ifndef __ASM__\n");
117 s = s + sprintf(s, "extern void PrepareTests();\n");
118 s = s + sprintf(s, "#define PREPARE_TESTS PrepareTests();\n");
119 s = s + sprintf(s, "#endif /* __ASM__ */\n");
120 }
121 else
122 {
123 s = s + sprintf(s, "#define PREPARE_TESTS\n");
124 }
125 s = s + sprintf(s, "#define CONFIG \"%s\"\n", config);
126 s = s + sprintf(s, "#endif /* __INCLUDE_CONFIG_H */\n");
127
128 return(write_if_change(outbuf, argv[1]));
129 }