chiark / gitweb /
Merge branch 'master' into newacpi
[chiark-utils.git] / scripts / random-word
1 #!/usr/bin/perl
2
3 # Copyright 2004 Ian Jackson <ian@chiark.greenend.org.uk>
4 #
5 # This script and its documentation (if any) are free software; you
6 # can redistribute it and/or modify them under the terms of the GNU
7 # General Public License as published by the Free Software Foundation;
8 # either version 3, or (at your option) any later version.
9
10 # chiark-named-conf and its manpage are distributed in the hope that
11 # it will be useful, but WITHOUT ANY WARRANTY; without even the
12 # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
13 # PURPOSE.  See the GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, consult the Free Software Foundation's
17 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
18
19 use IO::Handle;
20 use IO::File;
21 use POSIX;
22
23 $want= 1;
24 $filename= "/usr/share/dict/words";
25 @randfile= ("/dev/urandom", "/dev/random");
26
27 sub fail ($) { die "random-word: $_[0]\n"; }
28 open D, ">/dev/null" or fail("open /dev/null: $!");
29
30 while ($ARGV[0] =~ m/^\-/) {
31     $_= shift @ARGV;
32     if (m/^\-\-?$/) {
33         last;
34     } elsif (m/^\-n(\d+)$/) {
35         $want= $1;
36     } elsif (m/^\-f/ && length > 2) {
37         $filename= $';
38     } elsif (m/^\-r/ && length > 2) {
39         @randfile= ($');
40     } elsif (m/^\-D$/) {
41         open D, ">&STDERR" or fail("dup stderr for debug: $!");
42     } else {
43         fail("unknown option \`$_'");
44     }
45 }
46
47 sub debug ($) {
48     print D "random-word: debug: $_[0]\n"
49         or fail("write debug: $!");
50 }
51
52 for $randfile (@randfile) {
53     $r= new IO::File "$randfile", 'r';
54     debug("open $randfile ".($r ? "ok" : "failed $!"));
55     last if $r;
56     $!==&ENOENT or fail("cannot open $randfile: $!");
57 }
58 $r or fail("could not open any random device: $!\n (tried @randfile)");
59 $r->autoflush(0);
60
61 $w= new IO::File $filename, 'r';
62 $w or fail("cannot open $filename: $!");
63 debug("open $filename ok");
64 @words= <$w>;
65 $w->error and fail("cannot read $filename: $!");
66 debug("read $filename ok");
67
68 while (@out < $want) {
69     $!=0; read $r,$rbytes,4;
70     length $rbytes==4 or fail("cannot read $randfile: $!");
71     $wordno= unpack 'L',$rbytes;
72     $wordno &= ~0x80000000;
73     $wordno %= @words;
74     $_= $words[$wordno];
75     chomp;
76     debug("picked $wordno \`$_'");
77     next unless m/^([a-z][-a-z]+)$/;
78     push @out, $1;
79     debug("good, now ".scalar @out);
80 }
81
82 debug("enough");
83
84 print join(' ',@out), "\n"
85     or fail("cannot write output: $!");