from glob import glob
import re
import os

from django.conf import settings

from doc_builder.base import BaseBuilder
from projects.utils import run

latex_re = re.compile('the LaTeX files are in (.*)\.')
pdf_re = re.compile('Output written on (.+) \(')


class Builder(BaseBuilder):

    def build(self, project, version):
        version_slug = 'latest'
        if version:
            version_slug = version.slug
        self._cd_makefile(project)
        #latex_results = run('make latex')
        latex_results = run('sphinx-build -b latex '
                            '-d _build/doctrees   . _build/latex')
        match = latex_re.search(latex_results[1])
        if match:
            latex_dir = match.group(1).strip()
            os.chdir(latex_dir)
            tex_file = glob.glob('*.tex')[0]
            #pdf_results = run('make')
            pdf_results = run('pdflatex -interaction=nonstopmode %s' % tex_file)
            #Check the return code was good before symlinking
            pdf_match = pdf_re.search(pdf_results[1])
            if pdf_match:
                from_file = os.path.join(os.getcwd(),
                                         "%s" % pdf_match.group(1).strip())
                to_path = os.path.join(settings.MEDIA_ROOT,
                                       'pdf',
                                       project.slug,
                                       version_slug)
                if not os.path.exists(to_path):
                    os.makedirs(to_path)
                to_file = os.path.join(to_path, '%s.pdf' % project.slug)
                if os.path.exists(from_file):
                    run('mv -f %s %s' % (from_file, to_file))
                else:
                    print "File doesn't exist, not symlinking."
            else:
                print "PDF Building failed. Moving on."
                if project.build_pdf:
                    project.build_pdf = False
                    project.save()

@@ -421,33 +421,56 @@
     
-self._cd_makefile(project
+os.chdir(project.conf_filename.rstrip('conf.py')
 )%0A  
@@ -638,23 +638,18 @@
         
-match =
+if
  latex_r
@@ -653,98 +653,22 @@
 x_re
-.search(latex_results%5B1%5D)%0A        if match:%0A            latex_dir = match.group(1).strip()
+sults%5B0%5D == 0:
 %0A   
@@ -689,17 +689,22 @@
 dir(
+'_build/
 latex
-_dir
+'
 )%0A  
@@ -728,13 +728,8 @@
 e = 
-glob.
 glob
@@ -1894,8 +1894,63 @@
 .save()%0A
+%09else:%0A%09    print os.getcwd()%0A%09    print latex_results%0A

Make pdf building not crap out on scury pdf's.