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