import Development.Shake
import Development.Shake.FilePath

target :: FilePath
target = "candidature"

buildDir :: FilePath
buildDir = "_build"

fullTarget :: FilePath
fullTarget = buildDir </> target <.> "pdf"

pdflatexCmd :: [String]
pdflatexCmd = ["xelatex", "-halt-on-error", "-output-directory=" ++ buildDir, target]

-- | Filters out the files which contain '#'.
noEmacsFiles :: [FilePath] -> [FilePath]
noEmacsFiles = filter ('#' `notElem`)

main :: IO ()
main = shakeArgs shakeOptions { shakeFiles = buildDir } $ do
  want [ fullTarget ]

  fullTarget %> \out -> do
    src <- getDirectoryFiles "" ["*.tex", "*.sty"]
    need $ (out -<.> "bbl") : noEmacsFiles src

    cmd pdflatexCmd

  fullTarget -<.> "bbl" %> \out -> do
    bibs <- getDirectoryFiles "bib" ["*.bib"]
    need $ map ("bib" </>) $ noEmacsFiles bibs

    exists <- doesFileExist $ fullTarget -<.> "aux"
    if not exists
      then cmd pdflatexCmd
      else return ()

    cmd ["biber", dropExtension out]

  phony "clean" $ do
    removeFilesAfter "_build" ["//*"]