{-# LANGUAGE RecordWildCards #-}

module Licence (replace) where

import Configuration (Configuration (..))
import Control.Monad (unless)
import Control.Monad.Reader (ask, liftIO)
import Data.ByteString.Lazy (ByteString, writeFile)
import Distribution.SPDX.LicenseId (LicenseId (Unlicense), licenseId)
import Initialise.Types (Initialise)
import Network.HTTP.Client (responseBody)
import Network.HTTP.Simple (httpLBS, parseRequest)
import System.FilePath ((</>))
import Prelude hiding (writeFile)

replace :: FilePath -> Initialise ()
replace :: FilePath -> Initialise ()
replace FilePath
p = do
  Configuration {Year
FilePath
LicenseId
Text
URI
name :: Text
homepage :: URI
author :: Text
maintainer :: Text
licence :: LicenseId
path :: FilePath
year :: Year
name :: Configuration -> Text
homepage :: Configuration -> URI
author :: Configuration -> Text
maintainer :: Configuration -> Text
licence :: Configuration -> LicenseId
path :: Configuration -> FilePath
year :: Configuration -> Year
..} <- ReaderT Configuration IO Configuration
forall r (m :: * -> *). MonadReader r m => m r
ask
  Bool -> Initialise () -> Initialise ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (LicenseId
licence LicenseId -> LicenseId -> Bool
forall a. Eq a => a -> a -> Bool
== LicenseId
Unlicense) (Initialise () -> Initialise ()) -> Initialise () -> Initialise ()
forall a b. (a -> b) -> a -> b
$
    IO () -> Initialise ()
forall a. IO a -> ReaderT Configuration IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (FilePath -> ByteString -> IO ()
writeFile (FilePath
path FilePath -> FilePath -> FilePath
</> FilePath
p) (ByteString -> IO ()) -> IO ByteString -> IO ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< LicenseId -> IO ByteString
contents LicenseId
licence)

contents :: LicenseId -> IO ByteString
contents :: LicenseId -> IO ByteString
contents LicenseId
l = do
  Request
request <- FilePath -> IO Request
forall (m :: * -> *). MonadThrow m => FilePath -> m Request
parseRequest (FilePath -> IO Request) -> FilePath -> IO Request
forall a b. (a -> b) -> a -> b
$ FilePath
"https://spdx.org/licenses/" FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ LicenseId -> FilePath
licenseId LicenseId
l FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
".txt"
  Response ByteString -> ByteString
forall body. Response body -> body
responseBody (Response ByteString -> ByteString)
-> IO (Response ByteString) -> IO ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Request -> IO (Response ByteString)
forall (m :: * -> *).
MonadIO m =>
Request -> m (Response ByteString)
httpLBS Request
request