#!/usr/bin/env python2.5
import os, sys, base64, time, shutil
from subprocess import Popen,PIPE


# 1.  grab the user passwords from aisparser@neil.home:./passwords
cmd = "ssh aisparser@neil.home cat ./passwords"
p = Popen( cmd, env=os.environ, shell=True, stdout=PIPE, stderr=PIPE )

passwords = {}
for line in p.stdout:
	(un,pw) = line.strip().split(':')
	passwords[un] = pw

#print passwords

# Process the current customer list file
customers = {}
for line in open('customers.txt'):
	fields = line.strip().split(':')
	if len(fields) > 1:
		un, pw = fields
	else:
		un = fields[0]
		pw = None
	customers[un] = pw

for cust in customers:
	if cust not in passwords:
#		print "Adding %s to the password list" % (cust)	
		# Bug here -- could generate a pw with a : in it
		pw = base64.b64encode(open('/dev/urandom').read(15))[:10]
		print "un: %s" % (cust)
		print "pw: %s" % (pw)
		customers[cust] = pw

		cmd = "ssh aisparser@neil.home htpasswd -b ./passwords %s %s" % (cust,pw)
		p = Popen( cmd, env=os.environ, shell=True, stdout=PIPE, stderr=PIPE )
		if p.stderr:
			for line in p.stderr:
				print "%s" % (line.strip())
		
# Rewrite the customer list with new passwords
cust_backup = 'customers.txt.' + time.strftime("%Y%m%d%H%M%S")
shutil.copy('customers.txt',cust_backup)
fp = open('customers.txt', 'w')
for cust in customers:
	fp.write("%s:%s\n" % (cust,customers[cust]))
fp.close()
