import System.Process
import System.IO
import Text.Regex
import Data.Char
import Data.List
import System
import Control.Monad

runhaskell = "c:/ghc/ghc-6.9.20071130/bin/runhaskell.exe"

main = do
  stage "configure"
  stage "build"

stage s = do
  putStrLn $ "\n------------------------------- stage: "++s
  (i,o,e,p) <- runInteractiveProcess runhaskell ["Setup",s] Nothing Nothing
  putStrLn "-- stdout"
  hGetContents o >>= putStrLn 
  putStrLn "-- stderr"
  errors <- hGetContents e
  putStrLn errors
  putStrLn "-- hints"
  hints rules $ squashSpaces errors
  status <- waitForProcess p
  case status of { ExitSuccess -> return (); _ -> error $ "[failure in stage "++s++"]" }

-- some example rules

rules = 
  [(confHook,
    \_->do putStrLn "the type of configure hooks has changed (<url>)."
           putStrLn "  please ask package maintainer <email> to update Setup.hs")
  ,(missingDependency,
    \[p,v]->if (p `elem` old_base) 
            then do
              putStrLn $ "the base package has been split up (<url>)."
              putStrLn $ "  please contact package maintainer: <email> "
              putStrLn $ "  meanwhile, add dependency: "++p++v
            else do
              putStrLn $ "the package dependencies seem incomplete."
              putStrLn $ "  please contact package maintainer: <email> "
              putStrLn $ "  meanwhile, try adding dependency: "++p++v)
  ]
  where old_base = ["array","bytestring","packedstring","containers"
                   ,"random","pretty","process","directory","old-time"
                   ,"old-locale" {- ,"time" -} ]

typemismatch a b = "Couldn't match expected type `"++a++"' against inferred type `"++b++"'"

confHook = mkRegex $ escape $ typemismatch 
  "(Either GenericPackageDescription PackageDescription, HookedBuildInfo)"
  "PackageDescription"

missingDependency = mkRegex $ 
  "Could not find module `[^']*': it is a member of package ([^0-9]*)(-[0-9.]*), which is hidden"

-- auxiliaries

hints [] text              = putStrLn ""
hints ((pat,hint):hs) text = maybe (hints hs text) 
                                   (\l->hint l>>hints hs text)
                                   (matchRegex pat text)

squashSpaces ""  = ""
squashSpaces (a:b) 
  | not (isSpace a) = a:squashSpaces b
squashSpaces str    = case span isSpace str of 
                        (a,b) -> [' '|not (null a)]++squashSpaces b

escape ""     = ""
escape (c:cs) = ['\\'| c `elem` "()" ] ++ (c:escape cs)
