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