2 * ypp-commodities main program: argument parsing etc.
5 * This is part of ypp-sc-tools, a set of third-party tools for assisting
6 * players of Yohoho Puzzle Pirates.
8 * Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
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.
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.
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/>.
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.
30 void debug_flush(void) {
31 sysassert(!ferror(debug));
32 sysassert(!fflush(debug));
35 const char *get_vardir(void) { return "."; }
36 const char *get_libdir(void) { return "."; }
40 omk_unset, omk_upload, omk_str, omk_raw, omk_none
42 static enum outmodekind o_outmode_kind;
43 static const char *o_outmode_str= 0;
45 static char *o_screenshot_fn;
46 static const char *o_serv_pctb, *o_serv_dict_fetch, *o_serv_dict_submit;
48 const char *o_resolver= "./dictionary-manager";
49 FILE *screenshot_file;
50 const char *o_ocean, *o_pirate;
53 static pid_t screenshot_compressor=-1;
55 enum mode o_mode= mode_all;
57 ff_charset_allowedit |
58 ff_dict_fetch|ff_dict_submit|ff_dict_pirate;
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);
67 DEFINE_VWRAPPERF(static, badusage, NORET);
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") );
75 screenshot_file= fopen(o_screenshot_fn, for_write ? "w" : "r");
77 fatal("could not open screenshots file `%s': %s",
78 o_screenshot_fn, strerror(errno));
82 static void run_analysis(void) {
85 sysassert( tf= tmpfile() );
86 progress("running recognition...");
89 if (o_flags & ff_upload) {
91 fatal("Recognition successful, but refusing to upload partial data\n"
92 " (--single-page specified). Specify an output mode?");
95 sysassert( fseek(tf,0,SEEK_SET) == 0);
97 progress_log("processing results (--%s)...", o_outmode_str);
99 sysassert( (processor= fork()) != -1 );
102 sysassert( dup2(fileno(tf),0) ==0 );
103 EXECLP_HELPER("commod-results-processor", o_outmode_str, (char*)0);
106 waitpid_check_exitstatus(processor, "output processor/uploader", 0);
108 progress_log("all complete.");
111 static void rsync_core(const char *stem, const char *suffix,
115 progress("Updating dictionary %s...",stem);
117 sysassert( (fetcher= fork()) != -1 );
119 const char *rsync= getenv("YPPSC_PCTB_RSYNC");
120 if (!rsync) rsync= "rsync";
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);
126 fprintf(stderr,"executing rsync to fetch %s to %s\n",remote,local);
127 char *opts= masprintf("-Lt%s%s",
129 DEBUGP(rsync) ? "v" : "");
130 execlp(rsync, "rsync",opts,"--",remote,local,(char*)0);
131 sysassert(!"exec rsync failed");
134 waitpid_check_exitstatus(fetcher, "rsync", 0);
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"); }
140 static void set_server(const char *envname, const char *defprotocol,
141 const char *defvalue, const char *defvalue_test,
142 const char *userspecified,
146 if (!enable) { value= "0"; goto ok; }
149 value= userspecified;
150 else if ((value= getenv(envname)))
152 else if (o_flags & ff_testservers)
153 value= defvalue_test;
157 if (value[0]=='/' || (value[0]=='.' && value[1]=='/'))
158 /* absolute or relative pathname - or anyway, something with no hostname */
161 const char *colon= strchr(value, ':');
162 const char *slash= strchr(value, '/');
164 if (colon && (!slash || colon < slash))
165 /* colon before the first slash, if any */
166 /* rsync :: protocol specification - anyway, adding scheme:// won't help */
169 int vallen= strlen(value);
171 value= masprintf("%s%s%s", defprotocol, value,
172 vallen && value[vallen-1]=='/' ? "" : "/");
175 sysassert(! setenv(envname,value,1) );
178 int main(int argc, char **argv) {
181 sysassert( setlocale(LC_MESSAGES,"") );
182 sysassert( setlocale(LC_CTYPE,"en_GB.UTF-8") ||
183 setlocale(LC_CTYPE,"en.UTF-8") );
185 #define ARGVAL ((*++argv) ? *argv : \
186 (badusage("missing value for option %s",arg),(char*)0))
188 #define IS(s) (!strcmp(arg,(s)))
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") ||
211 IS("--best-prices")) o_outmode_kind=omk_str,
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;
222 else if (IS("-D" #f)) \
223 debug_flags |= dbg_##f;
226 else if (IS("--window-id")) {
228 unsigned long windowid= strtoul(ARGVAL,&ep,0);
229 if (*ep) badusage("invalid window id");
230 set_yppclient_window(windowid);
232 badusage("unknown option `%s'",arg);
235 /* Consequential changes to options */
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;
243 o_outmode_kind= omk_upload;
247 if (o_outmode_kind==omk_upload) {
248 o_flags |= ffs_upload;
249 o_outmode_str= "upload";
255 set_server("YPPSC_PCTB_PCTB",
256 "http://", "pctb.ilk.org" /*pctb.crabdance.com*/,
258 o_serv_pctb, o_flags & (ff_needisland|ff_upload));
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);
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);
270 if (!o_screenshot_fn)
271 o_screenshot_fn= masprintf("%s/_pages.ppm.gz", get_vardir());
273 /* Actually do the work */
275 canon_colour_prepare();
277 if (o_mode & mf_findwindow) {
278 screenshot_startup();
279 find_yppclient_window();
281 if (!ocean) ocean= o_ocean;
282 if (!pirate) pirate= o_pirate;
284 if (o_flags & ff_needisland)
286 badusage("need --ocean option when not using actual YPP client window"
287 " (consider supplying --pirate too)");
289 sysassert(! setenv("YPPSC_OCEAN",ocean,1) );
290 if (pirate && (o_flags & ff_dict_pirate))
291 sysassert(! setenv("YPPSC_PIRATE",pirate,1) );
293 switch (o_mode & mfm_special) {
295 case mode_showcharset: ocr_showcharsets(); exit(0);
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");
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");
316 if (o_mode & mf_analyse) {
317 if (o_flags & ff_needisland) {
319 if (o_flags & ff_printisland)
320 printf("%s, %s\n", archipelago, island);
321 sysassert(! setenv("YPPSC_ISLAND",island,1) );
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;
330 progress_log("Finished.");
337 DEFINE_VWRAPPERF(, progress, )
338 DEFINE_VWRAPPERF(, progress_log, )
339 DEFINE_VWRAPPERF(, progress_spinner, )
340 DEFINE_VWRAPPERF(, warning, )
341 DEFINE_VWRAPPERF(, fatal, NORET)
343 static int last_progress_len;
345 static void vprogress_core(int spinner, const char *fmt, va_list al) {
349 if (!debug_flags && !isatty(2)) return;
351 if (last_progress_len)
354 r= vfprintf(stderr,fmt,al);
357 putc(spinner,stderr);
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);
366 last_progress_len= r;
368 if (ferror(stderr) || fflush(stderr)) _exit(16);
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[]="/-\\";
376 vprogress_core(spinchars[spinner],fmt,al);
378 spinner %= (sizeof(spinchars)-1);
381 void vprogress_log(const char *fmt, va_list al) {
385 vfprintf(stderr,fmt,al);
390 void vwarning(const char *fmt, va_list al) {
392 fputs("Warning: ",stderr);
393 vfprintf(stderr,fmt,al);
398 void vfatal(const char *fmt, va_list al) {
400 fputs("\n\nFatal error: ",stderr);
401 vfprintf(stderr,fmt,al);
403 fputs("\n\n",stderr);
407 void sysassert_fail(const char *file, int line, const char *what) {
411 "\nfatal operational error:\n"
412 " unsuccessful execution of: %s\n"
414 what, file,line, strerror(e));
418 void waitpid_check_exitstatus(pid_t pid, const char *what, int sigpipeok) {
422 got= waitpid(pid, &st, 0);
423 if (pid==-1) { sysassert(errno==EINTR); continue; }
426 sysassert( got==pid );
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)":"");
437 fatal("%s gave strange wait status %d", what, st);
441 char *masprintf(const char *fmt, ...) {
445 sysassert( vasprintf(&r,fmt,al) >= 0);