#!/usr/bin/python

"""
Okay. See the simpleAuto functionality. This is now great for simple
cases. It creates a temp local dir to receive the stuff, then monitors
a set of files for changes, and compiles whenever there's a change.

The other modes are rather specific, but show cases when multiple source files are needed.
Naturally, this ought really just to use make, but I'm not smart enough.

"""

import sys
mode= (len(sys.argv)<2)*'defence' + (len(sys.argv)==2)*sys.argv[-1].lower()
    
if 'def' in mode:
    print "Continuous compile mode for DEFENCE"
    diffFile='/home/cpbl/papers/thesis/srcTmp/tmpDiffd'
    compileScript='/home/cpbl/papers/thesis/compileDefence.sh'

    srcFiles=[
        ['/home/cpbl/papers/thesis/defence.tex','/home/cpbl/papers/thesis/srcTmp/defenceDraft.tex'],
        ['/home/cpbl/papers/thesis/defencePaper1.tex','/home/cpbl/papers/thesis/srcTmp/defencePaper1.tex'],
        ['/home/cpbl/papers/thesis/defencePaper2.tex','/home/cpbl/papers/thesis/srcTmp/defencePaper2.tex'],
        ['/home/cpbl/papers/thesis/defencePaper3.tex','/home/cpbl/papers/thesis/srcTmp/defencePaper3.tex'],
        ]
    #compileFile='/home/cpbl/papers/thesis/srcTmp/defenceDraft.tex'
elif mode=='allthesis':
    print "Continuous compile mode for all three papers of dissertation"

    diffFile='/home/cpbl/papers/thesis/srcTmp/tmpDifft'
    compileScript='/home/cpbl/papers/thesis/fcompileThesis && /home/cpbl/papers/thesis/compileIncomeCMA && /home/cpbl/papers/thesis/compileWeather && /home/cpbl/papers/thesis/compileVeblen'


    srcFiles=[
        ['/home/cpbl/papers/incomeCMA/incomeCMA4.tex','/home/cpbl/papers/thesis/srcTmp/incomeCMA4draft.tex'],
        ['/home/cpbl/papers/veblenNeighbourhoods/veblenNeighbourhoods3.tex','/home/cpbl/papers/thesis/srcTmp/veblenNeighbourhoodsdraft.tex'],
        ['/home/cpbl/papers/weather/weatherLocation2.tex','/home/cpbl/papers/thesis/srcTmp/weatherdraft.tex'],
        ['/home/cpbl/papers/thesis/diss.tex','/home/cpbl/papers/thesis/srcTmp/dissDraft.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperOne.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOne.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperTwo.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwo.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperThree.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThree.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperOneAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOneAppendix.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperTwoAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwoAppendix.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperThreeAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThreeAppendix.tex'],
        ]

elif 'diss' in mode or 'thesis' in mode: # DISSERTATION
    print "Continuous compile mode for DISSERTATION"

    diffFile='/home/cpbl/papers/thesis/srcTmp/tmpDifft'
    compileScript='/home/cpbl/papers/thesis/fcompileThesis '#&& /home/cpbl/papers/thesis/compileIncomeCMA'

    srcFiles=[
        ['/home/cpbl/papers/thesis/acknowledgements.tex','/home/cpbl/papers/thesis/srcTmp/acknowledgements.tex'],
        ['/home/cpbl/papers/thesis/diss.tex','/home/cpbl/papers/thesis/srcTmp/dissDraft.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperOne.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOne.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperTwo.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwo.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperThree.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThree.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperOneAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOneAppendix.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperTwoAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwoAppendix.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperThreeAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThreeAppendix.tex'],
        ]
elif 'inc' in mode:
    print "Continuous compile mode for IncomeCMA paper"
    diffFile='/home/cpbl/papers/thesis/srcTmp/tmpDiffi'
    compileScript='/home/cpbl/papers/thesis/compileIncomeCMA'

    srcFiles=[
        ['/home/cpbl/papers/incomeCMA/incomeCMA4.tex','/home/cpbl/papers/thesis/srcTmp/incomeCMA4draft.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperOne.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOne.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperOneAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOneAppendix.tex'],
        ]
    #compileFile='/home/cpbl/papers/thesis/srcTmp/defenceDraft.tex'
elif 'weath' in mode:
    print "Continuous compile mode for Weather paper"
    diffFile='/home/cpbl/papers/thesis/srcTmp/tmpDiffw'
    compileScript='/home/cpbl/papers/thesis/compileWeather'

    srcFiles=[
        ['/home/cpbl/papers/weather/weatherLocation2.tex','/home/cpbl/papers/thesis/srcTmp/weatherdraft.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperThree.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThree.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperThreeAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThreeAppendix.tex'],
        ]
elif mode in ['210','climate']:
    print "Continuous compile mode for simultaneously monitoring various Econ 210 files"
    srcFiles=[
        ['/home/cpbl/climate/science'],
        ['/home/cpbl/climate/syllabus'],
        ['/home/cpbl/climate/examQuestions'],
        #['/home/cpbl/climate/assignment01-02'],
        #['/home/cpbl/climate/lec01-intro'],
        ]
    compileScript='simpleAuto'
elif 'eblen' in mode:
    print "Continuous compile mode for Veblen Neighbourhoods theory paper"
    diffFile='/home/cpbl/papers/thesis/srcTmp/tmpDiffv'
    compileScript='/home/cpbl/papers/thesis/compileVeblen'

    srcFiles=[
        ['/home/cpbl/papers/veblenNeighbourhoods/veblenNeighbourhoods3.tex','/home/cpbl/papers/thesis/srcTmp/veblenNeighbourhoodsdraft.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperTwo.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwo.tex'],
        ['/home/cpbl/papers/thesis/thesisPaperTwoAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwoAppendix.tex'],
        ]
elif 'all'==mode:
    """ Crazy mode to compile everything relevant for each given file. This should become the master mode.
    
    """
    srcFiles=[
        ['/home/cpbl/papers/thesis/diss.tex','/home/cpbl/papers/thesis/srcTmp/dissDraft.tex',['/home/cpbl/papers/thesis/fcompileThesis']],
        ['/home/cpbl/papers/thesis/thesisPaperOne.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOne.tex',['/home/cpbl/papers/thesis/fcompileThesis','/home/cpbl/papers/thesis/compileIncomeCMA']],
        ['/home/cpbl/papers/thesis/thesisPaperTwo.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwo.tex',['/home/cpbl/papers/thesis/fcompileThesis','/home/cpbl/papers/thesis/compileVeblen']],
        ['/home/cpbl/papers/thesis/thesisPaperThree.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThree.tex',['/home/cpbl/papers/thesis/fcompileThesis','/home/cpbl/papers/thesis/compileWeather']],
        ['/home/cpbl/papers/thesis/thesisPaperOneAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperOneAppendix.tex',['/home/cpbl/papers/thesis/fcompileThesis','/home/cpbl/papers/thesis/compileIncomeCMA']],
        ['/home/cpbl/papers/thesis/thesisPaperTwoAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperTwoAppendix.tex',['/home/cpbl/papers/thesis/fcompileThesis','/home/cpbl/papers/thesis/compileVeblen']],
        ['/home/cpbl/papers/thesis/thesisPaperThreeAppendix.tex','/home/cpbl/papers/thesis/srcTmp/thesisPaperThreeAppendix.tex',['/home/cpbl/papers/thesis/fcompileThesis','/home/cpbl/papers/thesis/compileWeather']],
        ]
    compileScript='auto'
else:
    print "Don't know what you mean. So I'll assume the argument you gave me is the name of a tex file, without a tex extension, in the current directory"
    compileScript='simpleAuto'
    srcFiles=[
        [mode]
        ]

import os, time

## """
## def doCompileScript(cs,srcFiles=None):
##     if cs=='auto':
##         css=[sf[2] for sf in srcFiles]
##     else:
##         css=[cs]
##     for aCompileScript in css:
##         os.system(aCompileScript)
## """

if compileScript == 'simpleAuto':
    """
 Each element of srcFiles should contain one element: the source file full path
 They are independent...

 The "auto" means I don't need a compile script. This will jsut do a simple pdflatex.
"""
    firsttime=True
    doItTwice=False
    while 1:
        for oneGroup in srcFiles:
            apath,fname=os.path.split(oneGroup[0])
            if not apath:
                apath=os.getcwd()
            apath+='/'
            #print apath,fname
            fromfile=oneGroup[0]+'.tex'
            if not os.path.exists(apath+'srcTmp'):
                os.mkdir(apath+'srcTmp')
            os.chdir(apath+'srcTmp')
            tofile=apath+'srcTmp/'+fname+'Draft.tex'
            diffFile=apath+'srcTmp/'+fname+'_diff.tmp'
            pdffile=apath+'srcTmp/'+fname+'Draft.pdf'
            viewfile=apath+'srcTmp/'+fname+'DraftMod.pdf'
            shellfile=apath+fname+'_compileshellfile.sh'
            os.system('diff '+fromfile + ' '+tofile +' > '+diffFile)
            anyd=open(diffFile).read()
            pathList={'dd':apath+'srcTmp/','tf':tofile,'ff':fromfile,'vf':viewfile,'pf':pdffile}
            if anyd or firsttime:
                outs="""
                cd %(dd)s
                cp %(ff)s %(tf)s
                pdflatex %(tf)s  && cp %(pf)s  %(vf)s
                """%pathList
                if firsttime:
                    outs+="""
                    evince %(vf)s &
                    """%pathList
                if doItTwice:
                    outs+="""
                    cp %(ff)s %(tf)s
                    pdflatex %(tf)s  && cp %(pf)s  %(vf)s
                    """%pathList

                fout=open(shellfile,'wt')
                fout.write(outs)
                fout.close()
                os.system('bash '+shellfile)
                print '\n            ........ Waiting for change in source files'# '+srcFiles+'...'
        firsttime=False
        time.sleep(2)
    foo
    
#doCompileScript(compileSript,srcFiles=None):
if not compileScript == 'auto':
    os.system(compileScript)
print '\n            ........ Waiting for change in source files'# '+srcFiles+'...'

while 1:

    ####This needs fixing. Should accumulate list of scripts that need running from all diffs, then run a unique set of them.
    
    os.system('diff '+srcFiles[0][0] + ' '+srcFiles[0][1] +' > '+diffFile)
    for ss,cc in srcFiles[1:]:
        os.system('diff '+ss + ' '+cc +' >> '+diffFile)
        
    anyd=open(diffFile).read()
    if anyd:
        for ss,cc in srcFiles[1:]:
            os.system('cp '+ss + ' '+cc)
            #os.system('cp '+srcFiles[0][1] + ' '+compileFile)
        os.system(compileScript)
        for ss,cc in srcFiles[1:]:
            os.system('cp '+ss + ' '+cc)
            #os.system('cp '+srcFiles[0][1] + ' '+compileFile)
        os.system(compileScript)
        print '\n            ........ Waiting for change in source files'# '+srcFiles+'...'
    else:
        time.sleep(2)


