#!/usr/pkg/bin/python2.7
#----------------------------------------------------------------------------
# Project Name: MOSS
# File Name: mkpasswd.py
# Description: Generate MD5-encrypted password.
#
# Created: 2004. 08. 07
# RCS-ID: $Id: mkpasswd.py,v 1.9 2004/10/06 14:58:25 myunggoni Exp $
# Copyright: (c) 2004 by myunggoni
# License: GNU General Public License
# Author: Myung-Gon Park <myunggoni@users.kldp.net>
#----------------------------------------------------------------------------

import os
import sys
import string
import getpass
import getopt
import md5

def print_usage():
	print "Usage: %s {-n | -c <filename>} username" % os.path.basename(sys.argv[0])
	print "       -h     --help          Display this usage information"
	print "       -n     --no-file       Display results on standard out"
	print "       -c     --create-file   Update or create a new file"

if __name__ == "__main__":
	try:
		opts, args = getopt.getopt(sys.argv[1:], "hnc:", ["help", "no-file", "create-file"])
	except getopt.GetoptError:
		print_usage()
		sys.exit(1)

	filename = None
	stdout = None

	if len(args) != 1:
		print_usage()
		sys.exit(1)
	else:
		id = args[0]

	for opt, arg in opts:
		if opt in ("-h", "--help"):
			print_usage()
			sys.exit(0)
		
		if opt in ("-n", "--no-file"):
			if filename:
				print_usage()
				sys.exit(1)
			else:
				stdout = 1

		if opt in ("-c", "--create-file"):
			if stdout:
				print_usage()
				sys.exit(1)
			else:
				filename = arg

	if not stdout and not filename:
		print_usage()
		sys.exit(1)
	
	if filename and os.path.isfile(filename):
		fp = open(filename, "r")

		for line in fp.readlines():
			line = string.split(line, ":")

			if line[0] == id:
				print "ID already exists in %s" % filename
				sys.exit(1)
		
		fp.close()
	
	passwd1 = getpass.getpass("Password: ")
	passwd2 = getpass.getpass("Retype password: ")

	if passwd1 == passwd2:
		hash = md5.new()
		hash.update(passwd1)
		passwd = hash.hexdigest()
	else:
		print "Passwords do not match"
		sys.exit(1)	
	
	info = id + ":" + passwd

	if stdout:
		print info
	else:
		try:
			fp = open(filename, "a")
			fp.write(info + '\n')
			fp.close()
			
		except IOError, error:
			print error.strerror
			sys.exit(1)

		print "Password encryption completed"
