summaryrefslogtreecommitdiff
path: root/Main.hs
blob: 4df44267e81d3e933fbfd4abda5c9f9f3992335c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{-# LANGUAGE NoImplicitPrelude   #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where

import           Rebase.Prelude
import           System.Directory     (createDirectoryIfMissing, renameFile)
import           System.FilePath      (takeFileName, (</>))
import           System.FSNotify      (Event (..), watchDir, withManager)
import           System.Process.Typed (proc, runProcess)

verbose :: Bool
verbose = True

pdfDirectory, seenDir, pdfPrinterExecutable :: FilePath
pdfDirectory         = "."
seenDir              = pdfDirectory </> "seen"
pdfPrinterExecutable = "PDFtoPrinter.exe"

main :: IO ()
main = do
  createDirectoryIfMissing False seenDir
  withManager $ \mgr -> do
    void $ watchDir mgr pdfDirectory (const True) handleEvent
    forever $ threadDelay 1000000

handleEvent :: Event -> IO ()
handleEvent (Added f _) | (".pdf" `isSuffixOf` f) = handleNewPdf f
handleEvent x           = when verbose $ print x

handleNewPdf :: FilePath -> IO ()
handleNewPdf f =
  -- Note: there is no sense in checking the return result, as PDFtoPrinter.exe
  -- returns success even when it fails to parse the PDF.
  runProcessVerbose pdfPrinterExecutable [f] >>
  moveFileIntoDir f seenDir


runProcessVerbose :: FilePath -> [String] -> IO ExitCode
runProcessVerbose exe args = do
  when verbose $ putStrLn $ "+ " ++ exe ++ " " ++ unwords args
  runProcess (proc exe args)

moveFileIntoDir :: FilePath -> FilePath -> IO ()
moveFileIntoDir f d = renameFile f $ d </> takeFileName f