#!/usr/bin/python2
"""
    Does a global search for the old mysql password for a given domain and replaces it with the new password

    Copyright  Afrihost.com (PTY) Ltd 2003
    Original file by: Ed Pascoe <ed@pascoe.co.za>
    $Id: Menu.py,v 1.3 2003/03/31 08:59:37 elp Exp $
"""
__author__  = "Ed Pascoe <ed@pascoe.co.za>"
__date__    = "$Date: 2003/03/31 08:59:37 $ "
__version__ = "$Revision: 1.3 $"
__credits__ = "Afrihost.com -- The best webhosting. Ever."

import os.path, sys,os
if __name__=='__main__': sys.path.append(os.path.realpath(os.path.dirname(sys.argv[0]))+'/pylib')
import optparse,glob
import Cpanel

def mysqluserfix(username,newpw):
    if sys.platform.find('freebsd') > -1 :
        mysqlhome='/var/db/mysql'
    elif sys.platform.find('linux') > -1 :
        mysqlhome='/var/lib/mysql'
    else:
        sys.stderr.write("Don't know how to handle platform %s\n" % (sys.platform))
        sys.exit(1)

    g="%s/%s*" % (mysqlhome,username)
    for db in glob.glob(g):
        db=db[len(mysqlhome)+1:]
        print "Fixing access for db: '%s'" % (db)
        cmd=r"""echo "grant all on %s.* to %s@localhost identified by '%s'"|mysql mysql """ % (db,username,newpw)
        print cmd
        os.system(cmd)
        cmd=r"""echo "grant all on %s.* to %s@'127.0.0.1' identified by '%s'"|mysql mysql """ % (db,username,newpw)
        print cmd
        os.system(cmd)
    os.system("mysqladmin reload")

if __name__=='__main__':
    usage="Usage: %prog [<options>] " +"\n"+__doc__+"\n"
    parser=optparse.OptionParser(usage)
    parser.add_option("-d","--domain", dest="domain", type="string", help="Domain to search (without the www) ")
    parser.add_option("-o","--oldpw", dest="oldpw", type="string", help="The old mysql password")
    parser.add_option("-n","--newpw", dest="newpw", type="string", help="The new mysql password")
    (options,args) = parser.parse_args()

    c=Cpanel.Cpanel()
    username=c.user(options.domain)
    mysqluserfix(username,options.newpw)
    
    try: hd=c.homedir(username)
    except:
        sys.stderr.write( "Sorry, I can't find that domain (%s) on the system\n" % (options.domain))
        sys.exit(1)
    hd=os.path.join(hd,'public_html')
    for root,dirs,files in os.walk(hd):
        for f in files:
            fname=os.path.join(root,f)
            out=[]
            haschanged=False
            for line in open(fname,"r"):
                p=line.find(options.oldpw)
                if p > -1:
                    haschanged=1
                    line=line.replace(options.oldpw,options.newpw)
                    #print line
                out.append(line)
            if haschanged:
                print "Replacing file",fname
                c=open(fname,"w")
                c.write("".join(out))
                c.close()
            


#    vim600: sw=4 fdm=marker expandtab sm ts=3
