-- Link the latest version of the documentation for each package

import PublicFile		( localFile, slash )
import Util			( availablePackages, availableVersions,
				  packageDir )

import Control.Monad		( forM_ )
import Data.Version		( showVersion )
import Distribution.Text	( display )
import Distribution.Package     ( PackageName, PackageIdentifier(..) )
import Distribution.Version     ( Version )

import System.Directory		( doesFileExist )

main :: IO ()
main = do
	pkgs <- availablePackages
	forM_ pkgs $ \ pkg -> do
		vs <- availableVersions pkg
		mb_v <- findFirst (hasDocs pkg) (reverse vs)
		maybe (return ())
			(\ v -> putStrLn $ display pkg ++ " " ++ showVersion v)
			mb_v

findFirst :: (a -> IO Bool) -> [a] -> IO (Maybe a)
findFirst p = foldr check (return Nothing)
  where check x y = do
		b <- p x
		if b then return (Just x) else y

hasDocs :: PackageName -> Version -> IO Bool
hasDocs pkg v = doesFileExist (localFile index)
  where
	index = pkgDir `slash` "doc" `slash` "html" `slash` "doc-index.html"
	pkgDir = packageDir (PackageIdentifier pkg v)
