{-# 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 (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
year :: Configuration -> Year
path :: Configuration -> FilePath
licence :: Configuration -> LicenseId
maintainer :: Configuration -> Text
author :: Configuration -> Text
homepage :: Configuration -> URI
name :: Configuration -> Text
year :: Year
path :: FilePath
licence :: LicenseId
maintainer :: Text
author :: Text
homepage :: URI
name :: Text
..} <- forall r (m :: * -> *). MonadReader r m => m r
ask
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (LicenseId
licence forall a. Eq a => a -> a -> Bool
== LicenseId
Unlicense) forall a b. (a -> b) -> a -> b
$
    forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (FilePath -> ByteString -> IO ()
writeFile (FilePath
p FilePath -> FilePath -> FilePath
</> FilePath
path) 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 <- forall (m :: * -> *). MonadThrow m => FilePath -> m Request
parseRequest forall a b. (a -> b) -> a -> b
$ FilePath
"https://spdx.org/licenses/" forall a. [a] -> [a] -> [a]
++ LicenseId -> FilePath
licenseId LicenseId
l forall a. [a] -> [a] -> [a]
++ FilePath
".txt"
  forall body. Response body -> body
responseBody forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *).
MonadIO m =>
Request -> m (Response ByteString)
httpLBS Request
request