chiark / gitweb /
WIP overhaul of plumbing, databases, etc.
[ypp-sc-tools.db-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=      0001,
41   mf_screenshot=      0010,
42   mf_readscreenshot=  0020,
43   mf_analyse=         0100,
44   
45   mode_findwindow=    0001,
46   mode_screenshot=    0011,
47   mode_analyse=       0120,
48
49   mode_all=           0111,
50 };
51
52 static enum mode o_mode= mode_all;
53 static char *o_screenshot_fn;
54 static int o_quiet;
55 static const char *o_outputmode= "upload";
56 static const char *o_serv_pctb, *o_serv_dict_fetch, *o_serv_dict_submit;
57
58 const char *o_resolver= "./dictionary-manager";
59 FILE *screenshot_file;
60
61 enum flags o_flags= ff_dict_fetch|ff_dict_submit|ff_dict_pirate;
62
63 static void vbadusage(const char *fmt, va_list) FMT(1,0) NORET;
64 static void vbadusage(const char *fmt, va_list al) {
65   fputs("bad usage: ",stderr);
66   vfprintf(stderr,fmt,al);
67   fputc('\n',stderr);
68   exit(12);
69 }
70 DEFINE_VWRAPPERF(static, badusage, NORET);
71
72 static void open_screenshot_file(const char *mode) {
73   screenshot_file= fopen(o_screenshot_fn, mode);
74   if (!screenshot_file)
75     fatal("could not open screenshots file `%s': %s",
76           o_screenshot_fn, strerror(errno));
77 }
78
79 static void run_analysis(void) {
80   FILE *tf;
81
82   sysassert( tf= tmpfile() );
83   progress("running recognition...");
84   analyse(tf);
85
86   if (o_flags & ff_upload) {
87     if (o_flags & ff_singlepage)
88       fatal("Recognition successful, but refusing to upload partial data\n"
89             " (--single-page specified).  Specify an output mode?");
90   }
91
92   sysassert( fseek(tf,0,SEEK_SET) == 0);
93
94   progress_log("processing results (--%s)...", o_outputmode);
95   pid_t processor;
96   sysassert( (processor= fork()) != -1 );
97
98   if (!processor) {
99     sysassert( dup2(fileno(tf),0) ==0 );
100     execlp("./yppsc-commod-processor", "yppsc-commod-processor",
101            o_outputmode, (char*)0);
102     sysassert(!"execlp commod-processor failed");
103   }
104
105   waitpid_check_exitstatus(processor, "output processor/uploader");
106   fclose(tf);
107   progress_log("all complete.");
108 }
109
110 void fetch_with_rsync(const char *stem) {
111   pid_t fetcher;
112
113   sysassert( (fetcher= fork()) != -1 );
114   if (!fetcher) {
115     const char *rsync= getenv("YPPSC_PCTB_RSYNC");
116     if (!rsync) rsync= "rsync";
117   
118     const char *src= getenv("YPPSC_PCTB_DICT_UPDATE");
119     char *remote= masprintf("%s/master-%s.txt", src, stem);
120     char *local= masprintf("#master-%s#.txt", stem);
121     execlp(rsync, "rsync",
122            DEBUGP(rsync) ? "-vLt" : "-Lt",
123            "--",remote,local,(char*)0);
124     sysassert(!"exec rsync failed");
125   }
126
127   waitpid_check_exitstatus(fetcher, "dictionary-manager --update");
128 }
129
130 static void set_server(const char *envname, const char *defprotocol,
131                        const char *defvalue, const char *userspecified,
132                        int enable) {
133   const char *value;
134   
135   if (!enable) { value= "0"; goto ok; }
136
137   if (userspecified)
138     value= userspecified;
139   else if ((value= getenv(envname)))
140     ;
141   else
142     value= defvalue;
143
144   if (value[0]=='/' || (value[0]=='.' && value[1]=='/'))
145     /* absolute or relative pathname - or anyway, something with no hostname */
146     goto ok;
147
148   const char *colon= strchr(value, ':');
149   const char *slash= strchr(value, '/');
150
151   if (colon && (!slash || colon < slash))
152     /* colon before the first slash, if any */
153     /* rsync :: protocol specification - anyway, adding scheme:// won't help */
154     goto ok;
155
156   value= masprintf("%s%s", defprotocol, value);
157
158  ok:
159   sysassert(! setenv(envname,value,1) );
160 }
161
162 int main(int argc, char **argv) {
163   const char *arg;
164
165   sysassert( setlocale(LC_MESSAGES,"") );
166   sysassert( setlocale(LC_CTYPE,"en_GB.UTF-8") ||
167              setlocale(LC_CTYPE,"en.UTF-8") );
168
169 #define ARGVAL  ((*++argv) ? *argv : \
170                  (badusage("missing value for option %s",arg),(char*)0))
171
172 #define IS(s) (!strcmp(arg,(s)))
173
174   while ((arg=*++argv)) {
175     if (IS("--find-window-only"))      o_mode= mode_findwindow;
176     else if (IS("--screenshot-only"))  o_mode= mode_screenshot;
177     else if (IS("--analyse-only") ||
178              IS("--same"))             o_mode= mode_analyse;
179     else if (IS("--everything"))       o_mode= mode_all;
180     else if (IS("--single-page"))      o_flags |= ff_singlepage;
181     else if (IS("--quiet"))            o_quiet= 1;
182     else if (IS("--edit-charset"))     o_flags |= ff_editcharset;
183     else if (IS("--dict-local-only"))  o_flags &= ~ffs_dict;
184     else if (IS("--dict-read-only"))   o_flags &= (~ffs_dict | ff_dict_fetch);
185     else if (IS("--dict-anon"))        o_flags &= ~ff_dict_pirate;
186     else if (IS("--dict-submit"))      o_flags |= ff_dict_fetch|ff_dict_submit;
187     else if (IS("--upload") ||
188              IS("--arbitrage") ||
189              IS("--tsv") ||
190              IS("--best-prices"))      o_outputmode= arg+2;
191     else if (IS("--raw-tsv"))          o_outputmode= 0;
192     else if (IS("--screenshot-file"))  o_screenshot_fn= ARGVAL;
193     else if (IS("--pctb-server"))         o_serv_pctb=        ARGVAL;
194     else if (IS("--dict-submit-server"))  o_serv_dict_submit= ARGVAL;
195     else if (IS("--dict-update-server"))  o_serv_dict_fetch=  ARGVAL;
196 #define DF(f)                                   \
197     else if (IS("-D" #f))                       \
198       debug_flags |= dbg_##f;
199     DEBUG_FLAG_LIST
200 #undef DF
201     else if (IS("--window-id")) {
202       char *ep;
203       unsigned long windowid= strtoul(ARGVAL,&ep,0);
204       if (*ep) badusage("invalid window id");
205       set_yppclient_window(windowid);
206     } else
207       badusage("unknown option `%s'",arg);
208   }
209
210   /* Consequential changes to options */
211   
212   if (!strcmp("upload",o_outputmode))
213     o_flags |= ffs_upload;
214
215   /* Defaults */
216   
217   set_server("YPPSC_PCTB_PCTB",
218              "http://",           "pctb.ilk.org",
219              o_serv_pctb,         o_flags & (ff_needisland|ff_upload));
220              
221   set_server("YPPSC_PCTB_DICT_UPDATE",
222              "rsync://",          "rsync.pctb.chiark.greenend.org.uk/pctb",
223              o_serv_dict_fetch,   o_flags & ff_dict_fetch);
224
225   set_server("YPPSC_PCTB_DICT_SUBMIT",
226              "http://",           "dictup.pctb.chiark.greenend.org.uk",
227              o_serv_dict_submit,  o_flags & ff_dict_submit);
228
229   if (!o_screenshot_fn)
230     o_screenshot_fn= masprintf("%s/#pages#.ppm",get_vardir());
231
232   /* Actually do the work */
233              
234   if (o_mode & mf_findwindow) {
235     screenshot_startup();
236     find_yppclient_window();
237   }
238   if (o_mode & mf_screenshot) {
239     open_screenshot_file("w");
240     if (o_flags & ff_singlepage) take_one_screenshot();
241     else take_screenshots();
242   }
243   if (o_mode & mf_readscreenshot) {
244     open_screenshot_file("r");
245     if (o_flags & ff_singlepage) read_one_screenshot();
246     else read_screenshots();
247   }
248   if (o_mode & mf_analyse) {
249     find_islandname();
250     if (o_outputmode)
251       run_analysis();
252     else
253       analyse(stdout);
254   }
255   return 0;
256 }
257
258
259
260
261 DEFINE_VWRAPPERF(, progress, )
262 DEFINE_VWRAPPERF(, progress_log, )
263 DEFINE_VWRAPPERF(, progress_spinner, )
264 DEFINE_VWRAPPERF(, warning, )
265 DEFINE_VWRAPPERF(, fatal, NORET)
266
267 static int last_progress_len;
268      
269 static void vprogress_core(int spinner, const char *fmt, va_list al) {
270   int r;
271   
272   if (o_quiet) return;
273   if (!isatty(2)) return;
274   
275   if (last_progress_len)
276     putc('\r',stderr);
277
278   r= vfprintf(stderr,fmt,al);
279
280   if (spinner) {
281     putc(spinner,stderr);
282     r++;
283   }
284
285   if (r < last_progress_len) {
286     fprintf(stderr,"%*s", last_progress_len - r, "");
287     if (!r) putc('\r', stderr);
288     else while (last_progress_len-- > r) putc('\b',stderr);
289   }
290   last_progress_len= r;
291
292   if (ferror(stderr) || fflush(stderr)) _exit(16);
293 }
294    
295 void vprogress(const char *fmt, va_list al) { vprogress_core(0,fmt,al); }
296 void vprogress_spinner(const char *fmt, va_list al) {
297   static const char spinchars[]="/-\\";
298   static int spinner;
299
300   vprogress_core(spinchars[spinner],fmt,al);
301   spinner++;
302   spinner %= (sizeof(spinchars)-1);
303 }
304
305 void vprogress_log(const char *fmt, va_list al) {
306   if (o_quiet) return;
307   
308   progress("");
309   vfprintf(stderr,fmt,al);
310   putc('\n',stderr);
311   fflush(stderr);
312 }
313
314 void vwarning(const char *fmt, va_list al) {
315   progress("");
316   fputs("Warning: ",stderr);
317   vfprintf(stderr,fmt,al);
318   fputs("\n",stderr);
319   fflush(stderr);
320 }
321
322 void vfatal(const char *fmt, va_list al) {
323   progress("");
324   fputs("\n\nFatal error: ",stderr);
325   vfprintf(stderr,fmt,al);
326   fflush(stderr);
327   fputs("\n\n",stderr);
328   _exit(4);
329 }
330
331 void sysassert_fail(const char *file, int line, const char *what) {
332   int e= errno;
333   progress("");
334   fprintf(stderr,
335           "\nfatal operational error:\n"
336           " unsuccessful execution of: %s\n"
337           " %s:%d: %s\n\n",
338           what, file,line, strerror(e));
339   _exit(16);
340 }
341
342 void waitpid_check_exitstatus(pid_t pid, const char *what) { 
343   pid_t got;
344   int st;
345   for (;;) {
346     got= waitpid(pid, &st, 0);
347     if (pid==-1) { sysassert(errno==EINTR); continue; }
348     break;
349   }
350   sysassert( got==pid );
351
352   if (WIFEXITED(st)) {
353     if (WEXITSTATUS(st))
354       fatal("%s failed with nonzero exit status %d",
355             what, WEXITSTATUS(st));
356   } else if (WIFSIGNALED(st)) {
357     fatal("%s died due to signal %s%s", what,
358           strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
359   } else {
360     fatal("%s gave strange wait status %d", what, st);
361   }
362 }
363
364 char *masprintf(const char *fmt, ...) {
365   char *r;
366   va_list al;
367   va_start(al,fmt);
368   sysassert( vasprintf(&r,fmt,al) >= 0);
369   sysassert(r);
370   va_end(al);
371   return r;
372 }