{-# LANGUAGE LambdaCase #-}

module Test.Cardano.Mirror (
  mainnetEpochFiles,
)
where

import Cardano.Prelude
import System.Directory (doesDirectoryExist, getDirectoryContents)
import System.Environment (lookupEnv)
import System.FilePath (isExtensionOf, (</>))

-- Failing here (with 'exitFailure') is fine because this function is only ever
-- used to test maiinnet validaton. It is never used in production code.
mainnetEpochFiles :: IO [FilePath]
mainnetEpochFiles :: IO [String]
mainnetEpochFiles =
  String -> IO (Maybe String)
lookupEnv String
"CARDANO_MAINNET_MIRROR" forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Maybe String
Nothing -> do
      forall a (m :: * -> *). (Print a, MonadIO m) => a -> m ()
putStrLn String
"mainnetEpochFiles: CARDANO_MAINNET_MIRROR variable is not set"
      forall a. IO a
exitFailure
    Just String
fpath -> do
      Bool
exists <- String -> IO Bool
doesDirectoryExist String
fpath
      if Bool
exists
        then
          forall a. Ord a => [a] -> [a]
sort
            forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String
fpath String -> String -> String
</>)
            forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. forall a. (a -> Bool) -> [a] -> [a]
filter (String
"epoch" String -> String -> Bool
`isExtensionOf`)
            forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO [String]
getDirectoryContents String
fpath
        else do
          forall a (m :: * -> *). (Print a, MonadIO m) => a -> m ()
putStrLn
            forall a b. (a -> b) -> a -> b
$ String
"mainnetEpochFiles: directory '"
            forall a. [a] -> [a] -> [a]
++ String
fpath
            forall a. [a] -> [a] -> [a]
++ String
"' does not exist."
          forall a. IO a
exitFailure