{-# LANGUAGE OverloadedStrings #-}
-- Copyright 2020 United States Government as represented by the Administrator
-- of the National Aeronautics and Space Administration. All Rights Reserved.
--
-- Disclaimers
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may
-- not use this file except in compliance with the License. You may obtain a
-- copy of the License at
--
--      https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
--
-- | Auxiliary functions for working with directories.
module System.Directory.Extra
    ( copyTemplate
    )
  where

-- External imports
import           Control.Monad             ( filterM, forM_ )
import           Data.Aeson                ( Value (..) )
import qualified Data.ByteString.Lazy      as B
import           Data.Text.Lazy            ( pack, unpack )
import           Data.Text.Lazy.Encoding   ( encodeUtf8 )
import           Distribution.Simple.Utils ( getDirectoryContentsRecursive )
import           System.Directory          ( createDirectoryIfMissing,
                                             doesFileExist )
import           System.FilePath           ( makeRelative, splitFileName,
                                             takeDirectory, (</>) )
import           Text.Microstache          ( compileMustacheFile,
                                             compileMustacheText,
                                             renderMustache )

-- | Copy a template directory into a target location, expanding variables
-- provided in a map in a JSON value, both in the file contents and in the
-- filepaths themselves.
copyTemplate :: FilePath -> Value -> FilePath -> IO ()
copyTemplate :: FilePath -> Value -> FilePath -> IO ()
copyTemplate FilePath
templateDir Value
subst FilePath
targetDir = do

  -- Get all files (not directories) in the template dir. To keep a directory,
  -- create an empty file in it (e.g., .keep).
  [FilePath]
tmplContents <- (FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (FilePath
templateDir FilePath -> FilePath -> FilePath
</>) ([FilePath] -> [FilePath])
-> ([FilePath] -> [FilePath]) -> [FilePath] -> [FilePath]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath -> Bool) -> [FilePath] -> [FilePath]
forall a. (a -> Bool) -> [a] -> [a]
filter (FilePath -> [FilePath] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [FilePath
"..", FilePath
"."])
                    ([FilePath] -> [FilePath]) -> IO [FilePath] -> IO [FilePath]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO [FilePath]
getDirectoryContentsRecursive FilePath
templateDir
  [FilePath]
tmplFiles <- (FilePath -> IO Bool) -> [FilePath] -> IO [FilePath]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM FilePath -> IO Bool
doesFileExist [FilePath]
tmplContents

  -- Copy files to new locations, expanding their name and contents as
  -- mustache templates.
  [FilePath] -> (FilePath -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [FilePath]
tmplFiles ((FilePath -> IO ()) -> IO ()) -> (FilePath -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \FilePath
fp -> do

    -- New file name in target directory, treating file
    -- name as mustache template.
    let fullPath :: FilePath
fullPath = FilePath
targetDir FilePath -> FilePath -> FilePath
</> FilePath
newFP
          where
            -- If file name has mustache markers, expand, otherwise use
            -- relative file path
            newFP :: FilePath
newFP = (ParseError -> FilePath)
-> (Template -> FilePath) -> Either ParseError Template -> FilePath
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (FilePath -> ParseError -> FilePath
forall a b. a -> b -> a
const FilePath
relFP)
                           (Text -> FilePath
unpack (Text -> FilePath) -> (Template -> Text) -> Template -> FilePath
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Template -> Value -> Text
`renderMustache` Value
subst))
                           Either ParseError Template
fpAsTemplateE

            -- Local file name within template dir
            relFP :: FilePath
relFP = FilePath -> FilePath -> FilePath
makeRelative FilePath
templateDir FilePath
fp

            -- Apply mustache substitutions to file name
            fpAsTemplateE :: Either ParseError Template
fpAsTemplateE = PName -> Text -> Either ParseError Template
compileMustacheText PName
"fp" (FilePath -> Text
pack FilePath
relFP)

    -- File contents, treated as a mustache template.
    ByteString
contents <- Text -> ByteString
encodeUtf8 (Text -> ByteString)
-> (Template -> Text) -> Template -> ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Template -> Value -> Text
`renderMustache` Value
subst)
                           (Template -> ByteString) -> IO Template -> IO ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO Template
compileMustacheFile FilePath
fp

    -- Create target directory if necessary
    let dirName :: FilePath
dirName = (FilePath, FilePath) -> FilePath
forall a b. (a, b) -> a
fst ((FilePath, FilePath) -> FilePath)
-> (FilePath, FilePath) -> FilePath
forall a b. (a -> b) -> a -> b
$ FilePath -> (FilePath, FilePath)
splitFileName FilePath
fullPath
    Bool -> FilePath -> IO ()
createDirectoryIfMissing Bool
True FilePath
dirName

    -- Write expanded contents to expanded file path
    FilePath -> ByteString -> IO ()
B.writeFile FilePath
fullPath ByteString
contents