__all__=('checkLink','fixup_mail_admins')
import os
def checkLink():
    try:
        from django.conf.settings import PROJ_DIR
        cwd = PROJ_DIR
    except:
        cwd = os.path.realpath(os.getcwd())
    P = cwd.split(os.sep)
    if 'project' in P:
        P = P[:P.index('project')]
        projDir = os.sep + os.path.join(*P)
    elif os.path.isdir(os.path.join(cwd,'project')):
        projDir = cwd
    else:
        return
    projDir = os.path.normpath(os.path.normcase(projDir))
    pProjDir = os.path.dirname(projDir)
    if pProjDir==projDir: return
    F = os.listdir(pProjDir)
    for f in F:
        fn = os.path.join(pProjDir,f)
        if not os.path.islink(fn): continue
        try:
            tn = os.readlink(fn)
        except:
            continue
        if not os.path.isabs(tn):
            tn = os.path.join(os.path.dirname(fn),tn)
        TN = os.path.normpath(os.path.normcase(tn))
        if TN==projDir: return f.lower()
    return

def fixup_mail_admins(from_name='Mr. ReportLab'):
	from django.core.mail.message import EmailMultiAlternatives
	def mail_admins(subject, message, fail_silently=False, connection=None,
					html_message=None):
		"""Sends a message to the admins, as defined by the ADMINS setting."""
		from django.conf import settings
		if not settings.ADMINS:
			return
		mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
					message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
					connection=connection)
		try:
			from socket import gethostname
			hostname = gethostname()
			hostname = hostname.split('.')[0]
		except:
			hostname = 'localhost'

		link = checkLink() or ''
		if link: link += ' '
		mail.from_email = '%s%s <rptlab@%s.reportlab.com>' % (link,from_name,hostname)
		if html_message:
			mail.attach_alternative(html_message, 'text/html')
		mail.send(fail_silently=fail_silently)
	from django.core import mail
	mail.mail_admins=mail_admins
