#!/bin/sh
exec ${GUILE-guile} -e '(ttn-do randomish-wep-key)' -s $0 "$@" # -*-scheme-*-
!#
;;; randomish-wep-key --- produce a somewhat random WEP key

;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2009,
;;   2010, 2011 Thien-Thi Nguyen
;;
;; This file is part of ttn-do, released under the terms of the
;; GNU General Public License as published by the Free Software
;; Foundation; either version 3, or (at your option) any later
;; version.  There is NO WARRANTY.  See file COPYING for details.

;;; Commentary:

;; Usage: randomish-wep-key [--count N] BITLEN
;;
;; Display to stdout a somewhat randomly-produced WEP key of BITLEN bits.
;; The output is in hexadecimal, so it's a good idea to choose a BITLEN
;; that is a multiple of four.  Also, there is a "-" separating every
;; group of four hex digits, like so: abcd-1234-99...
;;
;; Optional arg --count N specifies how many to keys (one per line) to
;; write.  A negative N means to continue until interrupted.

;;; Code:

(define-module (ttn-do randomish-wep-key)
  #:export (main)
  #:use-module ((ttn-do zzz banalities) #:select (check-hv
                                                  qop<-args)))

(set! *random-state* (seed->random-state
                      (let ((pair (gettimeofday)))
                        (* (car pair) (cdr pair)))))

(define (spew len)
  (let ((acc '(#\newline)))
    (define (push x)
      (set! acc (cons x acc)))
    (let loop ((pos 0) (n (random (ash 1 len))))
      (if (= len pos)
          (display (apply string acc))
          (let ((next-pos (+ 4 pos)))
            (push (string-ref "01234567889abcdef" (logand n #xf)))
            (and (not (= len next-pos))
                 (zero? (remainder (- len next-pos) 16))
                 (push #\-))
            (loop next-pos (ash n -4)))))))

(define (main/qop qop)
  (and (null? (qop '()))
       (error "missing BITLEN"))
  (let ((count (or (qop 'count string->number) 1))
        (len (or (string->number (car (qop '())))
                 (error "invalid BITLEN"))))
    (or (zero? (remainder len 4))
        (error "BITLEN not a multiple of 4"))
    (do ((i 0 (1+ i)))
        ((= i count))
      (spew len))))

(define (main args)
  (check-hv args '((package . "ttn-do")
                   (version . "1.2")
                   (help . commentary)))
  (main/qop
   (qop<-args
    args '((count (single-char #\c) (value #t))))))

;;; randomish-wep-key ends here