import tempfile
import os, subprocess, shutil

import tg

from bazsvn import custom
from .restricted import PRED

class Zampolit(tg.TGController):
    allow_only = PRED

    @tg.expose(content_type='application/pdf')
    def index(self):
        tempd = tempfile.mkdtemp('.bazampolit') 

        p = subprocess.Popen(['git', 'svn', 'clone',
                              "file://%s" % custom.REPOSITORY, 'repository'],
                             cwd=tempd,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            raise EnvironmentError(p.returncode, err)

        # TODO(xavid): Make this more generic, or at least use the bazki
        #              locker.
        p = subprocess.Popen(['/mit/xavid/bin/zampolit'],
                             cwd=os.path.join(tempd, 'repository'),
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        if p.returncode != 0:
            raise EnvironmentError(p.returncode, err)

        with open(os.path.join(tempd, 'repository', "repository-wc.pdf")) as f:
            data = f.read()

        shutil.rmtree(tempd)

        return data

