#!/usr/bin/env python

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

Usage: %(program)s [-b] [-h]

Where:
    -b
    --batch
       Output only the CRYPT_KEY.

    --help
    -h
       Print this help message and exit.
"""


import commands
import getopt
import os
import sys


program = sys.argv[0]
batch = None

def usage(code, msg=''):
    print __doc__ % globals()
    if msg:
        print msg
    sys.exit(code)

try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'bh',
                               ['batch','help'])
except getopt.error, msg:
    usage(1, msg)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        usage(0)
    elif opt in ('-b', '--batch'):
        batch = 1


try:
    import paths
except ImportError:
    pass

from TMDA import Util


def keygen():
    # Use the kernel's random number generator if available.
    randomdev = '/dev/urandom'
    if os.path.exists(randomdev):
        key = open(randomdev,'rb').read(20)
    else:
        # Otherwise generate some pseudo-random data from the system
        # and use the SHA of resulting key as the key.
        import sha
        if not batch:
            # Warn user that use of a cryptographic random number
            # generator is preferred.
            warning = ("key generation on a system without a "
                       + randomdev + " device is not recommended!")
            print "WARNING:"
            print '*' * len(warning)
            print warning
            print '*' * len(warning)
            print
        unpredictable = ( "date",
                          "fstat",
                          "iostat",
                          "vmstat",
                          "finger",
                          "ps -la",
                          "netstat",
                          "uname -a",
                          "cat /etc/passwd",
                          "cat /etc/aliases",
                          "cat /proc/interrupts" )
        key_data = ''
        for i in unpredictable:
            if commands.getstatusoutput(i)[0] == 0:
                key_data = key_data + os.popen(i).read()
        key = sha.new(key_data + "key").digest()
    return Util.hexlify(key)


def main():
    
    if not batch:
        print "Generating a unique, 160-bit private key, please wait a moment.."
        print

    key = keygen()

    if len(key) != 40:
        print "Oops, generated key is not 40-characters long, exiting!"
        sys.exit()

    print "CRYPT_KEY =", '"' + key + '"'

    if not batch:
        print
        print "Now paste the above line into your ~/.tmdarc file,"
        print "and make sure to keep your key secret!"


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