-----------------------------------------------------------------------------
-- |
-- Module      :  Plugins.Monitors.Load.Linux
-- Copyright   :  Finn Lawler
-- License     :  BSD-style (see LICENSE)
--
-- Author      :  Finn Lawler <flawler@cs.tcd.ie>
-- Maintainer  :  jao <mail@jao.io>
-- Stability   :  unstable
-- Portability :  unportable
--
-- A load average monitor for Xmobar.  Adapted from
-- Xmobar.Plugins.Monitors.Thermal by Juraj Hercek.
--
-----------------------------------------------------------------------------

module Xmobar.Plugins.Monitors.Load.Linux (fetchLoads) where

import Xmobar.Plugins.Monitors.Load.Common (Result(..))
import qualified Data.ByteString.Lazy.Char8 as B
import System.Posix.Files (fileExist)

-- | Parses the contents of a loadavg proc file, returning
-- the list of load averages
parseLoadAvgs :: B.ByteString -> Result
parseLoadAvgs :: ByteString -> Result
parseLoadAvgs =
  [Float] -> Result
Result ([Float] -> Result)
-> (ByteString -> [Float]) -> ByteString -> Result
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ByteString -> Float) -> [ByteString] -> [Float]
forall a b. (a -> b) -> [a] -> [b]
map (String -> Float
forall a. Read a => String -> a
read (String -> Float) -> (ByteString -> String) -> ByteString -> Float
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> String
B.unpack) ([ByteString] -> [Float])
-> (ByteString -> [ByteString]) -> ByteString -> [Float]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [ByteString] -> [ByteString]
forall a. Int -> [a] -> [a]
take Int
3 ([ByteString] -> [ByteString])
-> (ByteString -> [ByteString]) -> ByteString -> [ByteString]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [ByteString]
B.words (ByteString -> [ByteString])
-> (ByteString -> ByteString) -> ByteString -> [ByteString]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ByteString] -> ByteString
forall a. [a] -> a
head ([ByteString] -> ByteString)
-> (ByteString -> [ByteString]) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [ByteString]
B.lines

fetchLoads :: IO Result
fetchLoads :: IO Result
fetchLoads = do
  let file :: String
file = String
"/proc/loadavg"

  Bool
exists <- String -> IO Bool
fileExist String
file
  if Bool
exists then
    ByteString -> Result
parseLoadAvgs (ByteString -> Result) -> IO ByteString -> IO Result
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO ByteString
B.readFile String
file
    else
    Result -> IO Result
forall (m :: * -> *) a. Monad m => a -> m a
return Result
NA