# Usage: snakemake filename.pdf
import datetime
import os
import pathlib

ruleorder:  tex2pdf_with_bib > tex2pdf_without_bib

bib_filename = 'cv/pubs.bib'
bib_path = pathlib.Path(bib_filename)
time_filename = 'timestamp.txt'
time_path = pathlib.Path(time_filename)
now = datetime.datetime.now()
update_frequency = datetime.timedelta(days = 7)
timestamp = datetime.datetime.fromtimestamp(bib_path.stat().st_mtime)
if (now - update_frequency) > timestamp:
    time_path.touch(exist_ok = True)

rule targets:
    input:
        expand("docs/{name}.pdf", 
               name=['vitae_KLS', 'sound'])

rule copy_bib:
    input:
        bib='cv/pubs.bib'
    output:
        bib='cv_KLS.bib'
    shell:
        """
        cp {input.bib} {output.bib}
        """

rule tex2pdf_with_bib:
    input:
        tex='{name}.tex',
        bib='{name}.bib',
        bst='kls.bst'
    output:
        pdf='docs/{name}.pdf'
    shell:
        """
        xelatex {wildcards.name}
        bibtex {wildcards.name}
        xelatex {wildcards.name}
        xelatex {wildcards.name}
        mv {wildcards.name}.pdf {output.pdf}
        rm -f *.out *.log *.aux *.bbl *.blg *.synctex.gz *.fls *.flx *.fdb_latexmk
        """

rule tex2pdf_without_bib:
    input:
        '{name}.tex'
    output:
        pdf='docs/{name}.pdf'
    shell:
        """
        xelatex {wildcards.name}
        mv {wildcards.name}.pdf {output.pdf}
        rm -f *.out *.log *.aux *.bbl *.blg *.synctex.gz *.fls *.flx *.fdb_latexmk
        """

rule texclean:
    shell:
        "rm -f cv_KLS.pdf *.out *.log *.aux *.bbl *.blg *.synctex.gz *.fls *.flx *.fdb_latexmk "

checkpoint fetch_yaml_contents:
    input:
        txt=time_filename
    output:
        outdir=directory('cv/')
    shell:
        """
        git fetch website
        git checkout website/main -- cv/
        """

def list_yaml_files(wildcards):
    checkpoint_output = checkpoints.fetch_yaml_contents.get(**wildcards).output.outdir
    new_wildcards = glob_wildcards("cv/{file}.yml")
    yaml_files = expand("cv/{file}.yml", file = new_wildcards.file)
    return yaml_files

rule render_vitae:
    input:
        Rmd='vitae.Rmd',
        bib='cv/pubs.bib',
        tex='preamble.tex',
        yml=list_yaml_files
    output:
        pdf='docs/vitae_KLS.pdf'
    conda: "envs/vitae.yml"
    shell:
        """
        R -e "rmarkdown::render('{input.Rmd}', output_file = '{output.pdf}')"
        """

rule vitae_clean:
    shell:
        "rm -f moderncv* tweaklist.sty vitae*.log vitae*.tex vitae*.pdf"
