import org.apache.tools.ant.filters.ReplaceTokens

/* Configure Latex Compiler */
def docsProjectRootDir = file("$projectDir")
println("The root dir of docs project is " + docsProjectRootDir)

def processTexDir = file("${layout.buildDirectory.get()}/processTeX")
println("The tex process dir is " + processTexDir)

def inputTexFile = "fuji.tex"
def outputTexDir = file("${layout.buildDirectory.get()}/outTeX")
println("The build output dir is " + outputTexDir)

def outputTexFile = "fuji.pdf"
println("The build output file name is " + outputTexFile)

def recreateDir(File dir) {
    if (dir.exists()) {
        println "Delete existing directory: $dir"
        dir.deleteDir()
    }
    println "Mkdir the directory: $dir"
    dir.mkdirs()
}

tasks.register('processLatex', Copy) {
    outputs.upToDateWhen { false }

    /* Copy the original docs dir, and process it. */
    from(docsProjectRootDir)
    into("${processTexDir}")
    include "**/*.tex"
    filter(ReplaceTokens, tokens: [
            'TOKEN_MOD_VERSION' : project.version.toString(),
            'TOKEN_PROJECT_ROOT': project.rootDir.absolutePath,
            'TOKEN_TEX_OUT_DIR' : outputTexDir.toString()
    ])


    doFirst {
        /* Clean the original builds. */
        recreateDir(processTexDir)
    }
}

tasks.register('compileLatex') {
    dependsOn(tasks.processLatex)

    /* Clean the original builds. */
    doFirst {
        recreateDir(outputTexDir)
    }

    /* Compile twice to ensure the TOC is generated. */
    doLast {
        2.times {
            exec {
                workingDir = processTexDir
                commandLine "pdflatex",
                        "-file-line-error",
                        "-interaction=nonstopmode",
                        "-synctex=1",
                        "-output-format=pdf",
                        "-output-directory=${outputTexDir}",
                        // Shell-escape for minted tex package.
                        "-shell-escape",
                        "${inputTexFile}"
                println("Compile TeX once.")
            }
        }
        println 'Finish the loop of compiling TeX.'

        println 'Copy the build outputs into the release dir.'
        copy {
            from("${outputTexDir}/${outputTexFile}")
            into("${docsProjectRootDir}/release")
        }
    }
}
