module Main (main) where

import qualified Options
import Utility (exitFailureMsg, )

import qualified System.Process as Proc
import Distribution.Simple.Utils (setFileOrdinary, )

import qualified Data.List.HT as ListHT
import qualified Data.Char as Char
import Text.Printf (printf, )

import qualified Control.Monad.Exception.Synchronous as Exc
import qualified Control.Monad.Trans.Class as MT


callLLVMConfig :: Options.T -> String -> IO String
callLLVMConfig flags arg =
   fmap (ListHT.dropWhileRev Char.isSpace) $
   Proc.readProcess (Options.llvmConfigPath flags) [arg] ""

createPkgConfig :: Options.T -> IO String
createPkgConfig flags = do
   fullVersion <- callLLVMConfig flags "--version"
   let version = takeWhile (\c -> Char.isDigit c || c=='.') fullVersion
   libdir <- callLLVMConfig flags "--libdir"
   includedir <- callLLVMConfig flags "--includedir"
   return $ unlines $
      "Name: LLVM" :
      "Description: Low-level Virtual Machine compiler framework" :
      printf "Version: %s" version :
      "URL: http://www.llvm.org/" :
      "Requires:" :
      "Conflicts:" :
      printf "Libs: -L%s -lLLVM-%s" libdir version :
      printf "Cflags: -I%s" includedir :
      []

run :: Options.T -> IO ()
run flags = do
   content <- createPkgConfig flags
   if Options.install flags
     then
        let path = Options.installPath flags
        in  writeFile path content >> setFileOrdinary path
     else putStr content

main :: IO ()
main =
   Exc.resolveT exitFailureMsg $
      MT.lift . run =<< Options.get
