module HSH.Helpers.FileManip where

import System.Directory 
import System.FilePath (takeDirectory)
import qualified Data.ByteString.Char8 as B
import HSH
import Text.StringTemplate.Helpers
import HSH.Helpers.UnixUsers

-- createDirectoryOwned

-- write a file, creating parent directories if necessary
writeFileForceB = writeFileForce' B.writeFile
writeFileForce = writeFileForce' writeFile
writeFileForce' w fp contents = do
  createDirectoryIfMissing True (takeDirectory fp)
  w fp contents

-- wrapper over ln -fs
data SymlinkArgs = SymLinkArgs{target::String, link::String}
  deriving Show
symlink slArgs = runIO $ render1 [("target",target slArgs),("link",link slArgs)] "ln -fs $target$ $link$" 

-- I took this out because I don't like the behavior of doesFileExist when it comes to symlinks
-- If  symlink exists, but it's to a directlry, this test is false
-- Or if it's to a nonexisting file, also false.
-- yet, removeFile will work anyway, which seems contradictory
-- ideally there should be functions removeSymlink, doesSymLink exist, and generally behavior around
-- symlinks should be better documented
removeFileIfExists f = do
  e <- doesFileExist f
  if e 
    then removeFile f
    else return ()