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