chiark / gitweb /
Rename yppsc-* helpers
[ypp-sc-tools.main.git] / pctb / convert.c
1 /*
2  * ypp-commodities main program: argument parsing etc.
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
10  *  This program is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation, either version 3 of the License, or
13  *  (at your option) any later version.
14  * 
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  * 
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  * 
23  *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24  *  are used without permission.  This program is not endorsed or
25  *  sponsored by Three Rings.
26  */
27
28 #include "convert.h"
29
30 void debug_flush(void) {
31   sysassert(!ferror(debug));
32   sysassert(!fflush(debug));
33 }
34
35 const char *get_vardir(void) { return "."; }
36 const char *get_libdir(void) { return "."; }
37
38
39 enum mode {
40   mf_findwindow=      0001,
41   mf_screenshot=      0010,
42   mf_readscreenshot=  0020,
43   mf_analyse=         0100,
44   
45   mode_findwindow=    0001,
46   mode_screenshot=    0011,
47   mode_analyse=       0120,
48
49   mode_all=           0111,
50 };
51
52 static enum mode o_mode= mode_all;
53 static char *o_screenshot_fn;
54 static int o_quiet;
55 static const char *o_outputmode= "upload";
56 static const char *o_serv_pctb, *o_serv_dict_fetch, *o_serv_dict_submit;
57
58 const char *o_resolver= "./dictionary-manager";
59 FILE *screenshot_file;
60
61 enum flags o_flags= ff_dict_fetch|ff_dict_submit|ff_dict_pirate;
62
63 static void vbadusage(const char *fmt, va_list) FMT(1,0) NORET;
64 static void vbadusage(const char *fmt, va_list al) {
65   fputs("bad usage: ",stderr);
66   vfprintf(stderr,fmt,al);
67   fputc('\n',stderr);
68   exit(12);
69 }
70 DEFINE_VWRAPPERF(static, badusage, NORET);
71
72 static void open_screenshot_file(const char *mode) {
73   screenshot_file= fopen(o_screenshot_fn, mode);
74   if (!screenshot_file)
75     fatal("could not open screenshots file `%s': %s",
76           o_screenshot_fn, strerror(errno));
77 }
78
79 static void run_analysis(void) {
80   FILE *tf;
81
82   sysassert( tf= tmpfile() );
83   progress("running recognition...");
84   analyse(tf);
85
86   if (o_flags & ff_upload) {
87     if (o_flags & ff_singlepage)
88       fatal("Recognition successful, but refusing to upload partial data\n"
89             " (--single-page specified).  Specify an output mode?");
90   }
91
92   sysassert( fseek(tf,0,SEEK_SET) == 0);
93
94   progress_log("processing results (--%s)...", o_outputmode);
95   pid_t processor;
96   sysassert( (processor= fork()) != -1 );
97
98   if (!processor) {
99     sysassert( dup2(fileno(tf),0) ==0 );
100     EXECLP_HELPER("commod-results-processor", o_outputmode, (char*)0);
101   }
102
103   waitpid_check_exitstatus(processor, "output processor/uploader");
104   fclose(tf);
105   progress_log("all complete.");
106 }
107
108 void fetch_with_rsync(const char *stem) {
109   pid_t fetcher;
110
111   sysassert( (fetcher= fork()) != -1 );
112   if (!fetcher) {
113     const char *rsync= getenv("YPPSC_PCTB_RSYNC");
114     if (!rsync) rsync= "rsync";
115   
116     const char *src= getenv("YPPSC_PCTB_DICT_UPDATE");
117     char *remote= masprintf("%s/master-%s.txt", src, stem);
118     char *local= masprintf("#master-%s#.txt", stem);
119     execlp(rsync, "rsync",
120            DEBUGP(rsync) ? "-vLt" : "-Lt",
121            "--",remote,local,(char*)0);
122     sysassert(!"exec rsync failed");
123   }
124
125   waitpid_check_exitstatus(fetcher, "dictionary-manager --update");
126 }
127
128 static void set_server(const char *envname, const char *defprotocol,
129                        const char *defvalue, const char *userspecified,
130                        int enable) {
131   const char *value;
132   
133   if (!enable) { value= "0"; goto ok; }
134
135   if (userspecified)
136     value= userspecified;
137   else if ((value= getenv(envname)))
138     ;
139   else
140     value= defvalue;
141
142   if (value[0]=='/' || (value[0]=='.' && value[1]=='/'))
143     /* absolute or relative pathname - or anyway, something with no hostname */
144     goto ok;
145
146   const char *colon= strchr(value, ':');
147   const char *slash= strchr(value, '/');
148
149   if (colon && (!slash || colon < slash))
150     /* colon before the first slash, if any */
151     /* rsync :: protocol specification - anyway, adding scheme:// won't help */
152     goto ok;
153
154   value= masprintf("%s%s", defprotocol, value);
155
156  ok:
157   sysassert(! setenv(envname,value,1) );
158 }
159
160 int main(int argc, char **argv) {
161   const char *arg;
162
163   sysassert( setlocale(LC_MESSAGES,"") );
164   sysassert( setlocale(LC_CTYPE,"en_GB.UTF-8") ||
165              setlocale(LC_CTYPE,"en.UTF-8") );
166
167 #define ARGVAL  ((*++argv) ? *argv : \
168                  (badusage("missing value for option %s",arg),(char*)0))
169
170 #define IS(s) (!strcmp(arg,(s)))
171
172   while ((arg=*++argv)) {
173     if (IS("--find-window-only"))      o_mode= mode_findwindow;
174     else if (IS("--screenshot-only"))  o_mode= mode_screenshot;
175     else if (IS("--analyse-only") ||
176              IS("--same"))             o_mode= mode_analyse;
177     else if (IS("--everything"))       o_mode= mode_all;
178     else if (IS("--single-page"))      o_flags |= ff_singlepage;
179     else if (IS("--quiet"))            o_quiet= 1;
180     else if (IS("--edit-charset"))     o_flags |= ff_editcharset;
181     else if (IS("--dict-local-only"))  o_flags &= ~ffs_dict;
182     else if (IS("--dict-read-only"))   o_flags &= (~ffs_dict | ff_dict_fetch);
183     else if (IS("--dict-anon"))        o_flags &= ~ff_dict_pirate;
184     else if (IS("--dict-submit"))      o_flags |= ff_dict_fetch|ff_dict_submit;
185     else if (IS("--upload") ||
186              IS("--arbitrage") ||
187              IS("--tsv") ||
188              IS("--best-prices"))      o_outputmode= arg+2;
189     else if (IS("--raw-tsv"))          o_outputmode= 0;
190     else if (IS("--screenshot-file"))  o_screenshot_fn= ARGVAL;
191     else if (IS("--pctb-server"))         o_serv_pctb=        ARGVAL;
192     else if (IS("--dict-submit-server"))  o_serv_dict_submit= ARGVAL;
193     else if (IS("--dict-update-server"))  o_serv_dict_fetch=  ARGVAL;
194 #define DF(f)                                   \
195     else if (IS("-D" #f))                       \
196       debug_flags |= dbg_##f;
197     DEBUG_FLAG_LIST
198 #undef DF
199     else if (IS("--window-id")) {
200       char *ep;
201       unsigned long windowid= strtoul(ARGVAL,&ep,0);
202       if (*ep) badusage("invalid window id");
203       set_yppclient_window(windowid);
204     } else
205       badusage("unknown option `%s'",arg);
206   }
207
208   /* Consequential changes to options */
209   
210   if (!strcmp("upload",o_outputmode))
211     o_flags |= ffs_upload;
212
213   /* Defaults */
214   
215   set_server("YPPSC_PCTB_PCTB",
216              "http://",           "pctb.ilk.org",
217              o_serv_pctb,         o_flags & (ff_needisland|ff_upload));
218              
219   set_server("YPPSC_PCTB_DICT_UPDATE",
220              "rsync://",          "rsync.pctb.chiark.greenend.org.uk/pctb",
221              o_serv_dict_fetch,   o_flags & ff_dict_fetch);
222
223   set_server("YPPSC_PCTB_DICT_SUBMIT",
224              "http://",           "dictup.pctb.chiark.greenend.org.uk",
225              o_serv_dict_submit,  o_flags & ff_dict_submit);
226
227   if (!o_screenshot_fn)
228     o_screenshot_fn= masprintf("%s/#pages#.ppm",get_vardir());
229
230   /* Actually do the work */
231              
232   if (o_mode & mf_findwindow) {
233     screenshot_startup();
234     find_yppclient_window();
235   }
236   if (o_mode & mf_screenshot) {
237     open_screenshot_file("w");
238     if (o_flags & ff_singlepage) take_one_screenshot();
239     else take_screenshots();
240   }
241   if (o_mode & mf_readscreenshot) {
242     open_screenshot_file("r");
243     if (o_flags & ff_singlepage) read_one_screenshot();
244     else read_screenshots();
245   }
246   if (o_mode & mf_analyse) {
247     find_islandname();
248     if (o_outputmode)
249       run_analysis();
250     else
251       analyse(stdout);
252   }
253   return 0;
254 }
255
256
257
258
259 DEFINE_VWRAPPERF(, progress, )
260 DEFINE_VWRAPPERF(, progress_log, )
261 DEFINE_VWRAPPERF(, progress_spinner, )
262 DEFINE_VWRAPPERF(, warning, )
263 DEFINE_VWRAPPERF(, fatal, NORET)
264
265 static int last_progress_len;
266      
267 static void vprogress_core(int spinner, const char *fmt, va_list al) {
268   int r;
269   
270   if (o_quiet) return;
271   if (!isatty(2)) return;
272   
273   if (last_progress_len)
274     putc('\r',stderr);
275
276   r= vfprintf(stderr,fmt,al);
277
278   if (spinner) {
279     putc(spinner,stderr);
280     r++;
281   }
282
283   if (r < last_progress_len) {
284     fprintf(stderr,"%*s", last_progress_len - r, "");
285     if (!r) putc('\r', stderr);
286     else while (last_progress_len-- > r) putc('\b',stderr);
287   }
288   last_progress_len= r;
289
290   if (ferror(stderr) || fflush(stderr)) _exit(16);
291 }
292    
293 void vprogress(const char *fmt, va_list al) { vprogress_core(0,fmt,al); }
294 void vprogress_spinner(const char *fmt, va_list al) {
295   static const char spinchars[]="/-\\";
296   static int spinner;
297
298   vprogress_core(spinchars[spinner],fmt,al);
299   spinner++;
300   spinner %= (sizeof(spinchars)-1);
301 }
302
303 void vprogress_log(const char *fmt, va_list al) {
304   if (o_quiet) return;
305   
306   progress("");
307   vfprintf(stderr,fmt,al);
308   putc('\n',stderr);
309   fflush(stderr);
310 }
311
312 void vwarning(const char *fmt, va_list al) {
313   progress("");
314   fputs("Warning: ",stderr);
315   vfprintf(stderr,fmt,al);
316   fputs("\n",stderr);
317   fflush(stderr);
318 }
319
320 void vfatal(const char *fmt, va_list al) {
321   progress("");
322   fputs("\n\nFatal error: ",stderr);
323   vfprintf(stderr,fmt,al);
324   fflush(stderr);
325   fputs("\n\n",stderr);
326   _exit(4);
327 }
328
329 void sysassert_fail(const char *file, int line, const char *what) {
330   int e= errno;
331   progress("");
332   fprintf(stderr,
333           "\nfatal operational error:\n"
334           " unsuccessful execution of: %s\n"
335           " %s:%d: %s\n\n",
336           what, file,line, strerror(e));
337   _exit(16);
338 }
339
340 void waitpid_check_exitstatus(pid_t pid, const char *what) { 
341   pid_t got;
342   int st;
343   for (;;) {
344     got= waitpid(pid, &st, 0);
345     if (pid==-1) { sysassert(errno==EINTR); continue; }
346     break;
347   }
348   sysassert( got==pid );
349
350   if (WIFEXITED(st)) {
351     if (WEXITSTATUS(st))
352       fatal("%s failed with nonzero exit status %d",
353             what, WEXITSTATUS(st));
354   } else if (WIFSIGNALED(st)) {
355     fatal("%s died due to signal %s%s", what,
356           strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
357   } else {
358     fatal("%s gave strange wait status %d", what, st);
359   }
360 }
361
362 char *masprintf(const char *fmt, ...) {
363   char *r;
364   va_list al;
365   va_start(al,fmt);
366   sysassert( vasprintf(&r,fmt,al) >= 0);
367   sysassert(r);
368   va_end(al);
369   return r;
370 }