#! /usr/bin/python3

import sys
import re
import glob
import os
import pwd
import socket

# Convert /home/dlscodrv/public_html/wp-content/plugins/bookshelf/includes
# to
# http://dlsconsulting.co.za/wp-content/plugins/bookshelf/includes/
# via
# <VirtualHost 41.76.208.21:80>
#   ServerName dlsconsulting.co.za
#   ServerAlias www.dlsconsulting.co.za
#   DocumentRoot /home/dlscodrv/public_html
# </VirtualHost>

document_roots={}
r={
    'ServerName': socket.gethostname(),
    'DocumentRoot': '/usr/local/apache/htdocs',
}

def parseline(line):
    global r
    line=line.strip()
    m = re.search(r'(\S+)\s*([^#]+)?',line)
    if not m:
        return
    keyword,value=m.groups()
    if not value: return
    r[keyword]=value
    if keyword=="ServerRoot":
        filespec=value.strip('" \'')
        os.chdir(filespec)
    if keyword=="Include":
        filespec=value.strip('" \'');
        file_list=glob.glob(filespec)
        for filename in file_list:
            parsefile(filename);
    elif keyword in ("</VirtualHost>", "<VirtualHost"):
        names = r.get('ServerAlias','').strip(" \"'")
        names=names+' '+r.get('ServerName','').strip(" \"'");
        for name in names.split():
            document_roots[ name ]  = r.get('DocumentRoot','').strip(" \"'");
    
def parsefile(filename):
    if not os.path.exists(filename):
        return
    cwd = os.getcwd()
    fd=open(filename,'r')
    for line in fd:
        parseline(line)
    fd.close()
    os.chdir(cwd);

def badness(name):
    rc = name.count('.')+name.count('*')*100 
    if name.startswith('www.'): rc +=2
    if name.endswith('.afrihost.com'): rc += 3
    if name.endswith('.aserv.co.za'): rc += 3
    if name.find('demo')>=0 or name.find('test')>=0: rc += 1
    return rc
    

def showpath(args,document_roots):
    shown=0
    seen = {}
    for path in args:
        if not path.startswith('/'):
            path=os.getcwd()+'/'+path
            path=path.replace("/./","/")
        if path in seen: continue # avoid silly duplicates, fwiw ...
        seen[path]=True
        m={}
        dr=''
        sn=None
        for ServerName,DocumentRoot in list(document_roots.items()):
            if ServerName.strip('.').find('.') <0 : continue
            for prefix in ('','/u1','/u2','/usr'):
                if path.startswith(prefix+DocumentRoot+'/'):
                    if not sn or badness(sn) > badness(ServerName):
                        dr=prefix+DocumentRoot
                        sn=ServerName
        if not dr:
            public_html='public_html';
            offset=path.find(public_html);
            if offset>0:
                dr=path[:offset+len(public_html)]
        if sn:
            www_sn = 'www.'+sn
            if www_sn in document_roots and document_roots[sn]==document_roots[www_sn]: sn=www_sn;
            print('http://'+sn+path[len(dr):])
            shown+=1
    return shown

def main():
    args=sys.argv[1:]
    if len(args)==0:
        args=['', os.environ.get('PWD',os.getcwd())+'/' ]

    # Moo
    uid = os.stat(".").st_uid;
    try:
        username = pwd.getpwuid(uid).pw_name
    except:
        username = str(uid)

    userfile = '/var/cpanel/users/%s' % username

    # Try the user's configuration file:
    for subdomainfile in glob.glob('/var/cpanel/userdata/%s/*.*' % username):
        if subdomainfile.endswith(".stor") or subdomainfile.endswith(".cache"): continue
        fd=open(subdomainfile,'r');
        servername=None
        documentroot=None
        for line in fd:
            bits=line.strip().split(" ",1)
            if len(bits)!=2: continue
            if bits[0]=='servername:': servername=bits[1]
            if bits[0]=='documentroot:': documentroot=bits[1]
        if servername and documentroot:
            document_roots[servername]=documentroot

    # Read httpd.conf:
    for httpd_conf in ('/etc/httpd/conf/httpd.conf', '/usr/local/apache/conf/httpd.conf', '/etc/apache2/apache2.conf', ):
        if not os.path.exists(httpd_conf): continue
        try:
            parsefile(httpd_conf)
        except:
            pass

    if showpath(args,document_roots): return

    # Read /var/cpanel/users/myusernm -- last ditch effort
    if os.path.exists(userfile): 
        fd=open(userfile,'r')
        for line in fd:
            bits=line.split('=',1);
            if len(bits)!=2: continue
            if bits[0]=='DNS': 
                document_roots[bits[1].strip()]= pwd.getpwuid(os.stat(".").st_uid).pw_dir+'/public_html';
        fd.close()

    if showpath(args,document_roots): return


if __name__=="__main__":
    main()

