chiark / gitweb /
print vprogress messages to files if any -D options specified
[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=      00001,
41   mf_screenshot=      00010,
42   mf_readscreenshot=  00020,
43   mf_analyse=         00100,
44   mfm_special=        07000,
45   
46   mode_findwindow=    00001,
47   mode_screenshot=    00011,
48   mode_analyse=       00120,
49   mode_showcharset=   01000,
50
51   mode_all=           00111,
52 };
53
54 enum outmodekind {
55   omk_unset, omk_upload, omk_str, omk_raw, omk_none
56 };
57 static enum outmodekind o_outmode_kind;
58 static const char *o_outmode_str= 0;
59
60 static enum mode o_mode= mode_all;
61 static char *o_screenshot_fn;
62 static const char *o_serv_pctb, *o_serv_dict_fetch, *o_serv_dict_submit;
63
64 const char *o_resolver= "./dictionary-manager";
65 FILE *screenshot_file;
66 const char *o_ocean, *o_pirate;
67 int o_quiet;
68
69 static pid_t screenshot_compressor=-1;
70
71 enum flags o_flags=
72    ff_charset_allowedit |
73    ff_dict_fetch|ff_dict_submit|ff_dict_pirate;
74
75 static void vbadusage(const char *fmt, va_list) FMT(1,0) NORET;
76 static void vbadusage(const char *fmt, va_list al) {
77   fputs("bad usage: ",stderr);
78   vfprintf(stderr,fmt,al);
79   fputc('\n',stderr);
80   exit(12);
81 }
82 DEFINE_VWRAPPERF(static, badusage, NORET);
83
84 static void open_screenshot_file(int for_write) {
85   if (!fnmatch("*.gz",o_screenshot_fn,0)) {
86     int mode= for_write ? O_WRONLY|O_CREAT|O_TRUNC : O_RDONLY;
87     sysassert(! gzopen(o_screenshot_fn, mode, &screenshot_file,
88                        &screenshot_compressor, "-1") );
89   } else {
90     screenshot_file= fopen(o_screenshot_fn, for_write ? "w" : "r");
91     if (!screenshot_file)
92       fatal("could not open screenshots file `%s': %s",
93             o_screenshot_fn, strerror(errno));
94   }
95 }
96
97 static void run_analysis(void) {
98   FILE *tf;
99
100   sysassert( tf= tmpfile() );
101   progress("running recognition...");
102   analyse(tf);
103
104   if (o_flags & ff_upload) {
105     if (npages<=1)
106       fatal("Recognition successful, but refusing to upload partial data\n"
107             " (--single-page specified).  Specify an output mode?");
108   }
109
110   sysassert( fseek(tf,0,SEEK_SET) == 0);
111
112   progress_log("processing results (--%s)...", o_outmode_str);
113   pid_t processor;
114   sysassert( (processor= fork()) != -1 );
115
116   if (!processor) {
117     sysassert( dup2(fileno(tf),0) ==0 );
118     EXECLP_HELPER("commod-results-processor", o_outmode_str, (char*)0);
119   }
120
121   waitpid_check_exitstatus(processor, "output processor/uploader", 0);
122   fclose(tf);
123   progress_log("all complete.");
124 }
125
126 static void rsync_core(const char *stem, const char *suffix,
127                        const char *zopt) {
128   pid_t fetcher;
129
130   progress("Updating dictionary %s...",stem);
131
132   sysassert( (fetcher= fork()) != -1 );
133   if (!fetcher) {
134     const char *rsync= getenv("YPPSC_PCTB_RSYNC");
135     if (!rsync) rsync= "rsync";
136   
137     const char *src= getenv("YPPSC_PCTB_DICT_UPDATE");
138     char *remote= masprintf("%s/master-%s.txt%s", src, stem, suffix);
139     char *local= masprintf("_master-%s.txt%s", stem, suffix);
140     if (DEBUGP(rsync))
141       fprintf(stderr,"executing rsync to fetch %s to %s\n",remote,local);
142     char *opts= masprintf("-Lt%s%s",
143                           zopt,
144                           DEBUGP(rsync) ? "v" : "");
145     execlp(rsync, "rsync",opts,"--",remote,local,(char*)0);
146     sysassert(!"exec rsync failed");
147   }
148
149   waitpid_check_exitstatus(fetcher, "rsync", 0);
150 }
151
152 void fetch_with_rsync_gz(const char *stem) { rsync_core(stem,".gz",""); }
153 void fetch_with_rsync(const char *stem) { rsync_core(stem,"","z"); }
154
155 static void set_server(const char *envname, const char *defprotocol,
156                        const char *defvalue, const char *defvalue_test,
157                        const char *userspecified,
158                        int enable) {
159   const char *value;
160   
161   if (!enable) { value= "0"; goto ok; }
162
163   if (userspecified)
164     value= userspecified;
165   else if ((value= getenv(envname)))
166     ;
167   else if (o_flags & ff_testservers)
168     value= defvalue_test;
169   else
170     value= defvalue;
171
172   if (value[0]=='/' || (value[0]=='.' && value[1]=='/'))
173     /* absolute or relative pathname - or anyway, something with no hostname */
174     goto ok;
175
176   const char *colon= strchr(value, ':');
177   const char *slash= strchr(value, '/');
178
179   if (colon && (!slash || colon < slash))
180     /* colon before the first slash, if any */
181     /* rsync :: protocol specification - anyway, adding scheme:// won't help */
182     goto ok;
183
184   int vallen= strlen(value);
185
186   value= masprintf("%s%s%s", defprotocol, value,
187                    vallen && value[vallen-1]=='/' ? "" : "/");
188
189  ok:
190   sysassert(! setenv(envname,value,1) );
191 }
192
193 int main(int argc, char **argv) {
194   const char *arg;
195
196   sysassert( setlocale(LC_MESSAGES,"") );
197   sysassert( setlocale(LC_CTYPE,"en_GB.UTF-8") ||
198              setlocale(LC_CTYPE,"en.UTF-8") );
199
200 #define ARGVAL  ((*++argv) ? *argv : \
201                  (badusage("missing value for option %s",arg),(char*)0))
202
203 #define IS(s) (!strcmp(arg,(s)))
204
205   while ((arg=*++argv)) {
206     if (IS("--find-window-only"))      o_mode= mode_findwindow;
207     else if (IS("--screenshot-only"))  o_mode= mode_screenshot;
208     else if (IS("--show-charset"))     o_mode= mode_showcharset;
209     else if (IS("--analyse-only") ||
210              IS("--same"))             o_mode= mode_analyse;
211     else if (IS("--everything"))       o_mode= mode_all;
212     else if (IS("--find-island"))      o_flags |= ffs_printisland;
213     else if (IS("--single-page"))      o_flags |= ff_singlepage;
214     else if (IS("--quiet"))            o_quiet= 1;
215     else if (IS("--edit-charset"))     o_flags |= ff_charset_edit;
216     else if (IS("--no-edit-charset"))  o_flags &= ~(ffm_charset);
217     else if (IS("--test-servers"))     o_flags |= ff_testservers;
218     else if (IS("--dict-local-only"))  o_flags &= ~ffs_dict;
219     else if (IS("--dict-read-only"))   o_flags &= (~ffs_dict | ff_dict_fetch);
220     else if (IS("--dict-anon"))        o_flags &= ~ff_dict_pirate;
221     else if (IS("--dict-submit"))      o_flags |= ff_dict_fetch|ff_dict_submit;
222     else if (IS("--raw-tsv"))          o_outmode_kind= omk_raw;
223     else if (IS("--upload"))           o_outmode_kind= omk_upload;
224     else if (IS("--arbitrage") ||
225              IS("--tsv") ||
226              IS("--best-prices"))      o_outmode_kind=omk_str,
227                                        o_outmode_str=arg+2;
228
229     else if (IS("--screenshot-file")||
230              IS("--screenshots-file")) o_screenshot_fn= ARGVAL;
231     else if (IS("--pctb-server"))         o_serv_pctb=        ARGVAL;
232     else if (IS("--dict-submit-server"))  o_serv_dict_submit= ARGVAL;
233     else if (IS("--dict-update-server"))  o_serv_dict_fetch=  ARGVAL;
234     else if (IS("--ocean"))            o_ocean=  ARGVAL;
235     else if (IS("--pirate"))           o_pirate= ARGVAL;
236 #define DF(f)                                   \
237     else if (IS("-D" #f))                       \
238       debug_flags |= dbg_##f;
239     DEBUG_FLAG_LIST
240 #undef DF
241     else if (IS("--window-id")) {
242       char *ep;
243       unsigned long windowid= strtoul(ARGVAL,&ep,0);
244       if (*ep) badusage("invalid window id");
245       set_yppclient_window(windowid);
246     } else
247       badusage("unknown option `%s'",arg);
248   }
249
250   /* Consequential changes to options */
251
252   if (o_mode & mf_analyse) {
253     if (!o_outmode_kind) {
254       if (o_flags & ff_printisland) {
255         o_outmode_kind= omk_none;
256         o_flags |= ff_singlepage;
257       } else {
258         o_outmode_kind= omk_upload;
259       }
260     }
261
262     if (o_outmode_kind==omk_upload) {
263       o_flags |= ffs_upload;
264       o_outmode_str= "upload";
265     }
266   }
267
268   /* Defaults */
269   
270   set_server("YPPSC_PCTB_PCTB",
271              "http://",          "pctb.ilk.org" /*pctb.crabdance.com*/,
272                                  "pctb.ilk.org",
273              o_serv_pctb,        o_flags & (ff_needisland|ff_upload));
274              
275   set_server("YPPSC_PCTB_DICT_UPDATE",
276              "rsync://",         "rsync.pctb.chiark.greenend.org.uk/pctb",
277                                  "rsync.pctb.chiark.greenend.org.uk/pctb/test",
278              o_serv_dict_fetch,   o_flags & ff_dict_fetch);
279
280   set_server("YPPSC_PCTB_DICT_SUBMIT",
281              "http://",           "dictup.pctb.chiark.greenend.org.uk",
282                                   "dictup.pctb.chiark.greenend.org.uk/test",
283              o_serv_dict_submit,  o_flags & ff_dict_submit);
284
285   if (!o_screenshot_fn)
286     o_screenshot_fn= masprintf("%s/_pages.ppm.gz", get_vardir());
287
288   /* Actually do the work */
289              
290   canon_colour_prepare();
291   
292   if (o_mode & mf_findwindow) {
293     screenshot_startup();
294     find_yppclient_window();
295   }
296   if (!ocean)  ocean=  o_ocean;
297   if (!pirate) pirate= o_pirate;
298   
299   if (o_flags & ff_needisland)
300     if (!ocean)
301       badusage("need --ocean option when not using actual YPP client window"
302                " (consider supplying --pirate too)");
303   if (ocean)
304     sysassert(! setenv("YPPSC_OCEAN",ocean,1) );
305   if (pirate && (o_flags & ff_dict_pirate))
306     sysassert(! setenv("YPPSC_PIRATE",pirate,1) );
307
308   switch (o_mode & mfm_special) {
309   case 0:                                      break;
310   case mode_showcharset:  ocr_showcharsets();  exit(0);
311   default:                                     abort();
312   }
313
314   if (o_mode & mf_screenshot) {
315     open_screenshot_file(1);
316     if (o_flags & ff_singlepage) take_one_screenshot();
317     else take_screenshots();
318     progress_log("OK for you to move the mouse now, and you can"
319                  " use the YPP client again.");
320     progress("Finishing handling screenshots...");
321     gzclose(&screenshot_file,&screenshot_compressor,"screenshots output");
322   }
323   if (o_mode & mf_readscreenshot) {
324     if ((o_flags & ff_upload) && !(o_flags & ff_testservers))
325       badusage("must not reuse screenshots for upload to live PCTB database");
326     open_screenshot_file(0);
327     if (o_flags & ff_singlepage) read_one_screenshot();
328     else read_screenshots();
329     gzclose(&screenshot_file,&screenshot_compressor,"screenshots input");
330   }
331   if (o_mode & mf_analyse) {
332     if (o_flags & ff_needisland) {
333       find_islandname();
334       if (o_flags & ff_printisland)
335         printf("%s, %s\n", archipelago, island);
336       sysassert(! setenv("YPPSC_ISLAND",island,1) );
337     }
338     switch (o_outmode_kind) {
339     case omk_upload: case omk_str:   run_analysis();        break;
340     case omk_raw:                    analyse(stdout);       break;
341     case omk_none:                                          break;
342     default: abort();
343     }
344   }
345   progress_log("Finished.");
346   return 0;
347 }
348
349
350
351
352 DEFINE_VWRAPPERF(, progress, )
353 DEFINE_VWRAPPERF(, progress_log, )
354 DEFINE_VWRAPPERF(, progress_spinner, )
355 DEFINE_VWRAPPERF(, warning, )
356 DEFINE_VWRAPPERF(, fatal, NORET)
357
358 static int last_progress_len;
359      
360 static void vprogress_core(int spinner, const char *fmt, va_list al) {
361   int r;
362   
363   if (o_quiet) return;
364   if (!debug_flags && !isatty(2)) return;
365   
366   if (last_progress_len)
367     putc('\r',stderr);
368
369   r= vfprintf(stderr,fmt,al);
370
371   if (spinner) {
372     putc(spinner,stderr);
373     r++;
374   }
375
376   if (r < last_progress_len) {
377     fprintf(stderr,"%*s", last_progress_len - r, "");
378     if (!r) putc('\r', stderr);
379     else while (last_progress_len-- > r) putc('\b',stderr);
380   }
381   last_progress_len= r;
382
383   if (ferror(stderr) || fflush(stderr)) _exit(16);
384 }
385    
386 void vprogress(const char *fmt, va_list al) { vprogress_core(0,fmt,al); }
387 void vprogress_spinner(const char *fmt, va_list al) {
388   static const char spinchars[]="/-\\";
389   static int spinner;
390
391   vprogress_core(spinchars[spinner],fmt,al);
392   spinner++;
393   spinner %= (sizeof(spinchars)-1);
394 }
395
396 void vprogress_log(const char *fmt, va_list al) {
397   if (o_quiet) return;
398   
399   progress("");
400   vfprintf(stderr,fmt,al);
401   putc('\n',stderr);
402   fflush(stderr);
403 }
404
405 void vwarning(const char *fmt, va_list al) {
406   progress("");
407   fputs("Warning: ",stderr);
408   vfprintf(stderr,fmt,al);
409   fputs("\n",stderr);
410   fflush(stderr);
411 }
412
413 void vfatal(const char *fmt, va_list al) {
414   progress("");
415   fputs("\n\nFatal error: ",stderr);
416   vfprintf(stderr,fmt,al);
417   fflush(stderr);
418   fputs("\n\n",stderr);
419   _exit(4);
420 }
421
422 void sysassert_fail(const char *file, int line, const char *what) {
423   int e= errno;
424   progress("");
425   fprintf(stderr,
426           "\nfatal operational error:\n"
427           " unsuccessful execution of: %s\n"
428           " %s:%d: %s\n\n",
429           what, file,line, strerror(e));
430   _exit(16);
431 }
432
433 void waitpid_check_exitstatus(pid_t pid, const char *what, int sigpipeok) { 
434   pid_t got;
435   int st;
436   for (;;) {
437     got= waitpid(pid, &st, 0);
438     if (pid==-1) { sysassert(errno==EINTR); continue; }
439     break;
440   }
441   sysassert( got==pid );
442
443   if (WIFEXITED(st)) {
444     if (WEXITSTATUS(st))
445       fatal("%s failed with nonzero exit status %d",
446             what, WEXITSTATUS(st));
447   } else if (WIFSIGNALED(st)) {
448     if (!sigpipeok || WTERMSIG(st) != SIGPIPE)
449       fatal("%s died due to signal %s%s", what,
450             strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
451   } else {
452     fatal("%s gave strange wait status %d", what, st);
453   }
454 }
455
456 char *masprintf(const char *fmt, ...) {
457   char *r;
458   va_list al;
459   va_start(al,fmt);
460   sysassert( vasprintf(&r,fmt,al) >= 0);
461   sysassert(r);
462   va_end(al);
463   return r;
464 }