{- |
   Support library for users of the installation script in
   hsinstall. When your project has data files in a @resources@
   directory, this library can be used to locate those files
   at runtime.
-}
module HSInstall.Resources
   ( getRsrcDir )
   where

import System.Directory ( doesDirectoryExist )
import System.Environment ( getExecutablePath )
import System.FilePath ( (</>), takeDirectory, takeFileName )


{- |
   Get the path to the resources, relative to where the binary was
   installed and executed from. The argument passed here is expected
   to be the @getDataDir@ generated by Cabal at compile time in the
   @Paths_YOUR_PROJECT@ module.

   Usage:

   @
      import HSInstall ( getRsrcDir )
      import Paths_YOUR_PROJECT ( getDataDir )

      resourcesDir <- getRsrcDir getDataDir
   @
-}
getRsrcDir :: IO FilePath -> IO FilePath
getRsrcDir cabalDataDir = do
  appDir <- takeFileName <$> cabalDataDir
  rsrcPath <- ( </> "share" </> appDir </> "resources" )
    . takeDirectory . takeDirectory <$> getExecutablePath

  rsrcPathExists <- doesDirectoryExist rsrcPath
  if rsrcPathExists
    then return rsrcPath
    else fail "Unable to find resources directory"