#!/usr/bin/python
"""Changes a subversion  username/password, can also be used to strip out or add back in usernames and passwords"""
__author__  = "Ed Pascoe <ed@pascoe.co.za>"
__credits__ = "Afrihost.com -- The best webhosting. Ever."


import optparse,os,sys,os.path,re

class SVNManipulate:
    def __init__(self):
        pass
    def stripAuth(self,location):
        """Removes any username from a repository"""
        #url="http://elp@test.brevis.co.za/svn/tags"
        authre=re.compile(r'^(.*?)(url=|repos=)(.*//)(.*?)@(.*)$') #Compile first because we are going to call this re repeatedly.
        for root,dirs,files in os.walk(location):
            p=root.find('.svn')
            if p==-1 or len(root)-p != 4: continue #len(.svn)=4
            out=[]
            fname=os.path.join(root,'entries')
            os.chmod(fname,0755)
            f=file(fname,"r+")
            for line in f:
                m=authre.search(line)
                if m: line=m.group(1)+m.group(2)+m.group(3)+m.group(5)+"\n"
                out.append(line)
            f.seek(0)
            f.truncate()
            f.write("".join(out))
            f.close()
    def addAuth(self,username,location):
        """Set the username to the given value"""
        self.stripAuth(location) #Remove any existing usernames
        authre=re.compile(r'^(.*?)(url=|repos=)(.*?//)(\w+.*?)(/.*)$') #Compile first because we are going to call this re repeatedly.
        for root,dirs,files in os.walk(location):
            p=root.find('.svn')
            if p==-1 or len(root)-p != 4: continue #len(.svn)=4
            out=[]
            fname=os.path.join(root,'entries')
            os.chmod(fname,0755)
            f=file(fname,"r+")
            for line in f:
                m=authre.search(line)
                if m: line=m.group(1)+m.group(2)+m.group(3)+username+"@"+m.group(4)+m.group(5)+"\n"
                out.append(line)
            f.seek(0)
            f.truncate()
            f.write("".join(out))
            f.close()
        
if __name__=='__main__':
    usage="Usage: %prog [<options>] <directory>" +"\n"+__doc__+"\n"
    parser=optparse.OptionParser(usage)
    parser.add_option("-n","--noauth", dest="noauth", action="store_true", default=0, help="Strip out any usernames and passwords for the repository")
    parser.add_option("-s","-u","--user","--setauth", dest="auth", type="string", default="", help="Set the authentication username to AUTH")
    (options,args) = parser.parse_args()

    if not args:
        parser.print_help()
        sys.exit(1)

    svnm=SVNManipulate()

    if options.noauth:
        for d in args:
            svnm.stripAuth(d)
    if options.auth:
        for d in args:
            svnm.addAuth(options.auth,d)
