-- | Call ghc-pkg dump with appropriate flags and stream to the given @Sink@, for a single database
ghcPkgDump
    :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m)
    => EnvOverride
    -> WhichCompiler
    -> [Path Abs Dir] -- ^ if empty, use global
    -> Sink ByteString IO a
    -> m a
ghcPkgDump menv wc mpkgDbs sink = do
    case reverse mpkgDbs of
        (pkgDb:_) -> (createDatabase menv wc) pkgDb -- TODO maybe use some retry logic instead?
        _ -> return ()
    a <- sinkProcessStdout Nothing menv (ghcPkgExeName wc) args sink
    return a
  where
    args = concat
        [ case mpkgDbs of
            [] -> ["--global", "--no-user-package-db"]
            _ -> ["--user", "--no-user-package-db"] ++ concatMap (\pkgDb -> ["--package-db", toFilePath pkgDb]) mpkgDbs
        , ["dump", "--expand-pkgroot"]
        ]

-- | Create a new, empty @InstalledCache@
ghcPkgDump
    :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m, MonadThrow m)
    => EnvOverride
    -> WhichCompiler
    -> [Path Abs Dir] -- ^ if empty, use global
    -> Sink ByteString IO a
    -> m a
ghcPkgDump menv wc mpkgDbs sink = do
    case reverse mpkgDbs of
        (pkgDb:_) -> (createDatabase menv wc) pkgDb -- TODO maybe use some retry logic instead?
        _ -> return ()
    a <- sinkProcessStdout Nothing menv (ghcPkgExeName wc) args sink
    return a
  where
    args = concat
        [ case mpkgDbs of
            [] -> ["--global", "--no-user-package-db"]
            _ -> ["--user", "--no-user-package-db"] ++ concatMap (\pkgDb -> ["--package-db", toFilePath pkgDb]) mpkgDbs
        , ["dump", "--expand-pkgroot"]
        ]

-- | Create a new, empty @InstalledCache@
ghcPkgDump menv wc mpkgDbs sink = do
    case reverse mpkgDbs of
        (pkgDb:_) -> (createDatabase menv wc) pkgDb -- TODO maybe use some retry logic instead?
        _ -> return ()
    a <- sinkProcessStdout Nothing menv (ghcPkgExeName wc) args sink
    return a
  where
    args = concat
        [ case mpkgDbs of
            [] -> ["--global", "--no-user-package-db"]
            _ -> ["--user", "--no-user-package-db"] ++ concatMap (\pkgDb -> ["--package-db", toFilePath pkgDb]) mpkgDbs
        , ["dump", "--expand-pkgroot"]
        ]

-- | Create a new, empty @InstalledCache@