{-# 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" IO (Maybe String) -> (Maybe String -> IO [String]) -> IO [String]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Maybe String
Nothing -> do
      String -> IO ()
forall a (m :: * -> *). (Print a, MonadIO m) => a -> m ()
forall (m :: * -> *). MonadIO m => String -> m ()
putStrLn String
"mainnetEpochFiles: CARDANO_MAINNET_MIRROR variable is not set"
      IO [String]
forall a. IO a
exitFailure
    Just String
fpath -> do
      Bool
exists <- String -> IO Bool
doesDirectoryExist String
fpath
      if Bool
exists
        then
          [String] -> [String]
forall a. Ord a => [a] -> [a]
sort
            ([String] -> [String])
-> ([String] -> [String]) -> [String] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String
fpath String -> String -> String
</>)
            ([String] -> [String])
-> ([String] -> [String]) -> [String] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
"epoch" String -> String -> Bool
`isExtensionOf`)
            ([String] -> [String]) -> IO [String] -> IO [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO [String]
getDirectoryContents String
fpath
        else do
          String -> IO ()
forall a (m :: * -> *). (Print a, MonadIO m) => a -> m ()
forall (m :: * -> *). MonadIO m => String -> m ()
putStrLn
            (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
"mainnetEpochFiles: directory '"
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
fpath
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"' does not exist."
          IO [String]
forall a. IO a
exitFailure