#!/usr/bin/python

"""
Utility to create the proceedings.

For usage info, invoke

$> python proceedings.py --help

Version: 1.0.0
Maintainer: Loris Sauter <loris.sauter@unibas.ch>

Changelog:

 1.0.0 - Initial version


Authors:

 Loris Sauter

"""

import argparse
import os

# ==================================== #
# Constants                            #
# ==================================== #

REPORT_FILE = 'reportContent.tex'
BIB_FILE = 'report.bib'
PROCEEDINGS_FILE_NAME = 'proceedings'
TEX_EXTENSION = '.tex'

ADDBIB_STATEMENT = '\\addbibresource{%s/%s/'+BIB_FILE+'}'
IMPORT_STATEMENT = '\\import{%s/%s/}{%s}'
GRAPHICS_STATMENT = '{%s/%s/images/}'
GRAPHICS_PROLOG = '\\graphicspath{\n {images/}'
GRAPHICS_EPILOG = '}'
GENERATED_HEADER = '% THIS FILE IS GENERATED BY proceedings.py'

AUXILIARY_EXTENSIONS = ['log','aux','dvi','lof','lot','bit','idx','glo','bbl','bcf','ilg','toc','ind','out','blg','fdb_latexmk','fls','synctex.gz','snm','run.xml','nav','vrb']

BIBLIOGRAPHY_FILE = 'bibliography.tex'
MAIN_FILE = 'main.tex'
GRAPHICS_FILE = 'graphics.tex'

# ==================================== #
# Arguments / Argparse setup           #
# ==================================== #

parser = argparse.ArgumentParser(
  description= '''\
  Utility tool to create and compile the proceedings of student reports.

  This requires minimal effort from the assistants to create
  a proceedings document, based on the individual reports of
  student(s) (groups).

  NOTE
  Please follow the steps outlined below carefuly.

  ''',
  formatter_class=argparse.RawDescriptionHelpFormatter,
  epilog='''\

  STUDENT USAGE:

  proceedings.py -z -- Cleanes auxiliary latex files
  proceedings.py -p -- Compiles the file in single mode

  ASSISTANT USAGE:

  Unfortunately, this tool requires some preparatory work:

  PREREQUISITES

  1. Create a content folder, where you will copy all the downloaded submissions to.
     Let's refer to this content folder as CONTENT
  2. Copy the reportContent folders of the submissions to CONTENT and rename them.
     A resonable naming scheme would be something sequential, e.g. g1, g2, g3, ...
  3. In the proceedings.tex file, change the produceProceedings bool to true.
  4. Run this tool and pass CONTENT as argument (--directory)

  Thank you for reading the documentation.
  '''
  )

parser.add_argument("-d", "--directory", help="The folder with all the report content folders downloaded")
parser.add_argument("-r", "--report", help="The name of the report file, i.e. the one in the group folders.", default=REPORT_FILE)
parser.add_argument("-c", "--clean", help="Flag to remove all auxiliary files", action='store_true')
parser.add_argument("-z", "--clean-only", help="Only clean, i.e. remove auxiliary files", action='store_true')
parser.add_argument("-n", "--no-compile", help="To not compile [the proceedings].", action='store_true')
parser.add_argument("-v", "--verbose", help="Verbose execution", action='store_true')
parser.add_argument("-s", "--simulate", help="To only simulate, not execute the commands", action='store_true')
parser.add_argument("-p", "--pdf", help="To only compile the document", action='store_true')


# ==================================== #
# Utility functions                    #
# ==================================== #

def removeIfExistis(file):
    if os.path.exists(file):
        if args.simulate:
            print ('  rm ' + file)
        else:
            os.remove(file)

def vprint(msg):
    if args.verbose:
        print(msg)

def fwrite(file, list, prolog='', epilog=''):
    if args.simulate:
        print (' File %s' % file)
        print(prolog)
        for item in list:
            print (' %s' % item)
        print(epilog)
    else:
        with open(file, 'w') as f:
            f.write('%s\n' % GENERATED_HEADER)
            f.write('%s\n' % prolog)
            for item in list:
                f.write(' %s\n' % item)
            f.write('%s\n' % epilog)

def clean(name):
    vprint('Cleaning')
    for ext in AUXILIARY_EXTENSIONS:
        file = '%s.%s' % (PROCEEDINGS_FILE_NAME, ext)
        vprint(' rm %s' % file)
        removeIfExistis(file)
    vprint(' rm %s' % BIBLIOGRAPHY_FILE)
    removeIfExistis(BIBLIOGRAPHY_FILE)
    vprint(' rm %s' % GRAPHICS_FILE)
    removeIfExistis(GRAPHICS_FILE)
    vprint(' rm %s' % MAIN_FILE)
    removeIfExistis(MAIN_FILE)

# ==================================== #
# Core functions                       #
# ==================================== #

def compile():
    pdflatex_cmd = 'pdflatex %s%s' % (PROCEEDINGS_FILE_NAME, TEX_EXTENSION)
    biber_cmd = 'biber %s' % (PROCEEDINGS_FILE_NAME)
    if args.simulate:
        print (pdflatex_cmd)
        print (biber_cmd)
        print (pdflatex_cmd)
        print (pdflatex_cmd)
    else:
        os.system(pdflatex_cmd)
        os.system(biber_cmd)
        os.system(pdflatex_cmd)
        os.system(pdflatex_cmd)


def create_helper_files():
    folders = os.listdir(args.directory)

    vprint('Report Folders: %s' % folders)

    bib_list = []
    imp_list = []
    gra_list = []

    for dir in folders:
        bib = ADDBIB_STATEMENT % (args.directory, dir)
        imp = IMPORT_STATEMENT % (args.directory, dir, args.report)
        gra = GRAPHICS_STATMENT % (args.directory, dir)
        vprint(' Bib: %s' % bib)
        vprint(' Imp: %s' % imp)
        vprint(' Gra: %s' % gra)
        bib_list.append(bib)
        imp_list.append(imp)
        gra_list.append(gra)

    fwrite(BIBLIOGRAPHY_FILE, bib_list)
    fwrite(MAIN_FILE, imp_list)
    fwrite(GRAPHICS_FILE, gra_list, GRAPHICS_PROLOG, GRAPHICS_EPILOG)


# ==================================== #
# Main                                 #
# ==================================== #

if __name__== "__main__":
    args = parser.parse_args()
    vprint('Directory: %s ' % args.directory)

    if args.clean:
        clean(PROCEEDINGS_FILE_NAME)

    if args.clean_only:
        clean(PROCEEDINGS_FILE_NAME)
        exit(0)


    # folders = filter(lambda x: os.path.isdir(x), os.listdir(args.directory))

    if not args.pdf:
        if args.directory == None:
            parser.print_help()
            exit(1)
        create_helper_files()


    # pdflatex, biber, pdflatex, pdflatex

    if args.no_compile:
        exit(0)

    compile()
