{- |
  Resource location support library for software deployed with the hsinstall
  utility. Or, really, anything that roughly follows an FHS-like deployment
  structure.
-}
module HSInstall.Resources
   ( getRsrcDir )
   where

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


{- |
  Get a path to the application resources directory relative to the binary
  location. The argument passed here is expected to be the output of
  @getDataDir@ generated by Cabal at compile time in the @Paths_YOUR_PROJECT@
  module.

  Usage:

  @
    import HSInstall.Resources ( getRsrcDir )
    import Paths_PROJECTNAME ( getDataDir )

    resourcesDir <- getRsrcDir getDataDir
  @

  If your binary is at @\/foo\/bar\/usr\/bin\/BINARY@, this library will generate
  this path: @\/foo\/bar\/usr\/share\/PROJECTNAME-VERSION\/resources@
-}
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"