#! /usr/bin/python

'Set new ftp password for cpanel and ftp account'

import crypt
import sys
import re
import os

def setrandompassword(username, password=None):
    if username=='root':
        return Exception('Changing root password like this is not a good idea')
    random = open("/dev/urandom","r").read(200);
    alphabetsoup = re.sub("[^A-Za-z0-9]","",random)
    if password:
        newpassword=password
    else:
        newpassword = alphabetsoup[:10]
    salt = alphabetsoup[10:18]
    newcrypt = crypt.crypt(newpassword,"$1$"+salt+"$")
    oldcrypt =  None

    # fixme: set postgres passwords
    # fixme: set frontpage passwords

    # set mysql password
    r = {
        'username': username,
        'newpassword': newpassword,
        'newcrypt': newcrypt,
    }

    # set ftp passwords
    sitename=os.popen("grep ^DNS= /var/cpanel/users/%s" % username,'r').readline()[4:].strip()
    r['sitename']=sitename
    r['text'] = "The new password for site %(sitename)s is user %(username)s password %(newpassword)s" % r
    files = (
        "/etc/proftpd/passwd.vhosts",
        "/etc/proftpd/"+username,
        # "/etc/shadow",
         "/etc/master.passwd",   # BSD!  ouch!  we're going to do this without locking ... we're not scared...
    )
    # Set system password
    os.system(r"usermod -p '%(newcrypt)s' '%(username)s'" % r)
    # Set user mysql password
    mysql = os.popen('mysql','w')
    mysql.write("SET PASSWORD for '%(username)s'@'localhost' = PASSWORD('%(newpassword)s');" % r)
    mysql.close()
    # Set FTP account passwords
    for file in files:
        if not os.path.exists(file): continue
        content=[]
        ocontent=[]
        change=False
        fd = open(file,'r')
        for line in fd:
            ocontent.append(line)
            bits=line.split(":")
            if len(bits)>1 and (bits[0]==username or bits[1]==oldcrypt):
                if not oldcrypt: oldcrypt=bits[1]
                bits[1]=newcrypt
                line=':'.join(bits)
                #print '#', file
                #sys.stdout.write(line)
                change=True
            content.append(line)
        fd.close()
    
        if not change: continue
        fd=open(file,'w')
        fd.writelines(content)
        fd.close()
        # print "Wrote "+file
    return r


if __name__=="__main__":
    import optparse
    parser=optparse.OptionParser("%prog [options] username ...")
    parser.add_option("-p","--password",dest="password", action="store", default=None, help="use given password")
    (options,args) = parser.parse_args()

    if len(args)==0:
        print "Usage: ftpsetrandompasswd username [username ...]"
        print "Set new passwords for the listed user accounts"

    for username in args:
        r= setrandompassword(username, password=options.password)
        print r['text']

