#!/usr/pkg/bin/python2.7
#
# Copyright (C) 2001-2007 Jason R. Mastaler <jason@mastaler.com>
#
# This file is part of TMDA.
#
# TMDA is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  A copy of this license should
# be included in the file COPYING.
#
# TMDA is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with TMDA; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


from optparse import OptionParser, make_option

import binascii
import os
import sys

try:
    import paths
except ImportError:
    # Prepend /usr/lib/python2.x/site-packages/TMDA/pythonlib
    sitedir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3],
                           'site-packages', 'TMDA', 'pythonlib')
    sys.path.insert(0, sitedir)

from TMDA import Version


# option parsing

opt_desc = "Generate a unique 160-bit hex key."

opt_list = [
    make_option("-d", "--device",
                default="/dev/urandom", dest="device",
                help=("""Draw random numbers from a random data source 
                         device other than /dev/urandom""")),
    make_option("-b", "--batch",
                action="store_true", default=False, dest="batch",
                help="Output only the CRYPT_KEY"),
    make_option("-V", 
                action="store_true", default=False, dest="full_version",
                help="show full TMDA version information and exit"),
    ]

parser = OptionParser(option_list=opt_list, description=opt_desc, 
                      version=Version.TMDA)
(opts, args) = parser.parse_args()

if opts.full_version:
    print Version.ALL
    sys.exit()


def keygen():
    # Use the kernel's random number generator.
    if os.path.exists(opts.device):
        key = open(opts.device,'rb').read(20)
        return binascii.hexlify(key)
    #elif sys.platform == 'win32':
        # The Windows equivalent of polling /dev/urandom is to call
        # the Windows Crypto/API function "CryptGenRandom"
        # (http://tinyurl.com/4z0q).  At present there is no wrapper
        # for this in the Python standard library on Windows so we
        # can't utilize it.
    else:
        return None
    
def main():
    
    if not opts.batch:
        print "Generating a unique, 160-bit private key, please wait a moment.."
        print

    key = keygen()

    if key is None:
        # Use of a cryptographic random number generator is required.
        warning = ("key generation on a system without a "
                   + opts.device + " device is not supported!")
        print "WARNING:"
        print '*' * len(warning)
        print warning
        print
        print "specify a different random number device with the '-d' option,"
        print "or use http://tmda.net/cgi-bin/tmda-keygen if your system lacks one."
        print '*' * len(warning)
        print "exiting!"
        sys.exit()
        
    if len(key) <> 40:
        print "Oops, generated key is not 40-characters long, exiting!"
        sys.exit()

    print key
    
    if not opts.batch:
        print
        print "Now paste the above key into ~/.tmda/crypt_key"
        print "and make sure to keep your key secret! (chmod 600 ~/.tmda/crypt_key)"


# This is the end my friend.
if __name__ == '__main__':
    main()
