{- 
   Checkatom.hs is a script to get atom information from the ebuilds in a 
   specific category/package directory  inside the portage tree.
   
   compile: ghc -o checkatom Checkatom.hs
   use: checkatom <atom1> <atom2> ... <atomN>  category/package.
   example: ./checkatom depend dev-lang/ghc 
   to get the depend atom information for all the ebuilds inside dev-lang/ghc
   
   Luis F. Araujo <araujo@gentoo.org>
   Copyright 2005 
-}

module Main
    where

import System
import Directory
import Char
import Text.Regex

portage :: String
portage = "/usr/portage/"

infix 3 ??
(??) :: [a] -> Int -> a
xs ?? n = xs !! ((length xs) - n)

getAtoms :: [String] -> [String]
getAtoms (x:[]) = []
getAtoms (x:xs) = (map toUpper x) : getAtoms xs

findString :: String -> String -> Bool
findString [] _ = True
findString (x:xs) (y:ys) = if x == y 
			   then findString xs ys
			   else False
findString _ "" = False

findEbuild :: [String] -> [String]
findEbuild [] = []
findEbuild (x:xs) = case (matchRegexAll (mkRegex ".*\\.ebuild") x) of
		        { Just(_,name,_,_) -> name : findEbuild xs; 
			  Nothing -> findEbuild xs }

parseFile :: FilePath -> IO [String]
parseFile f = readFile f >>= (\s -> return(lines s))

atomLines :: [String] -> String -> String
atomLines [] _ = []
atomLines (x:xs) atom = if findString atom x 
		       then collect (x:xs)
		       else atomLines xs atom
			   where
			   collect n = case n of
					      (y:ys) -> if (y ?? 1) == '\"' 
  							then y ++ "\n"
							else y ++ "\n" ++ collect ys

iterOverFile :: String -> [String] -> [String] -> IO ()
iterOverFile _ _ [] = putStrLn " "
iterOverFile p a (x:xs) = parseFile (p ++ "/" ++ x) >>= (\s -> return(concatMap (atomLines s) a)) >>=
			(\s -> do { putStrLn ("**" ++ x ++ "**"); putStrLn s }) >> iterOverFile p a xs


main = do 
       args <- getArgs
       category <- return(args ?? 1)
       path <- return(portage ++ category)
       files <- getDirectoryContents path
       ebuilds <- return(findEbuild files)
       iterOverFile path (getAtoms args) ebuilds