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