chiark / gitweb /
427e4d08795710586fb6f02229f78cadb98b0ac4
[chiark-utils.git] / scripts / random-word
1 #!/usr/bin/perl -w
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 strict;
20
21 use IO::Handle;
22 use IO::File;
23 use POSIX;
24
25 our $want= 1;
26 our $filename= "/usr/share/dict/words";
27 our @randfile= ("/dev/urandom", "/dev/random");
28
29 sub fail ($) { die "random-word: $_[0]\n"; }
30 open D, ">/dev/null" or fail("open /dev/null: $!");
31
32 while (@ARGV && $ARGV[0] =~ m/^\-/) {
33     $_= shift @ARGV;
34     if (m/^\-\-?$/) {
35         last;
36     } elsif (m/^\-n(\d+)$/) {
37         $want= $1;
38     } elsif (m/^\-f/ && length > 2) {
39         $filename= $'; #';
40     } elsif (m/^\-r/ && length > 2) {
41         @randfile= ($'); #');
42     } elsif (m/^\-D$/) {
43         open D, ">&STDERR" or fail("dup stderr for debug: $!");
44     } else {
45         fail("unknown option \`$_'");
46     }
47 }
48
49 sub debug ($) {
50     print D "random-word: debug: $_[0]\n"
51         or fail("write debug: $!");
52 }
53
54 our $randfile;
55 our $r;
56
57 for $randfile (@randfile) {
58     $r= new IO::File "$randfile", 'r';
59     debug("open $randfile ".($r ? "ok" : "failed $!"));
60     last if $r;
61     $!==&ENOENT or fail("cannot open $randfile: $!");
62 }
63 $r or fail("could not open any random device: $!\n (tried @randfile)");
64 $r->autoflush(0);
65
66 our $w= new IO::File $filename, 'r';
67 $w or fail("cannot open $filename: $!");
68 debug("open $filename ok");
69 our @words= <$w>;
70 $w->error and fail("cannot read $filename: $!");
71 debug("read $filename ok");
72
73 our @out;
74 while (@out < $want) {
75     my $rbytes;
76     $!=0; read $r,$rbytes,4;
77     length $rbytes==4 or fail("cannot read $randfile: $!");
78     my $wordno= unpack 'L',$rbytes;
79     $wordno &= ~0x80000000;
80     $wordno %= @words;
81     $_= $words[$wordno];
82     chomp;
83     debug("picked $wordno \`$_'");
84     next unless m/^([a-z][-a-z]+)$/;
85     push @out, $1;
86     debug("good, now ".scalar @out);
87 }
88
89 debug("enough");
90
91 print join(' ',@out), "\n"
92     or fail("cannot write output: $!");