{-# LANGUAGE CPP #-}

-----------------------------------------------------------------------------

-----------------------------------------------------------------------------

{- |
Module      :  Plugins.Monitors.PacmanUpdates
Copyright   :  (c) 2024 Enrico Maria De Angelis
            ,  (c) 2025 Alexander Pankoff
License     :  BSD-style (see LICENSE)

Maintainer  :  Enrico Maria De Angelis <enricomaria.dean6elis@gmail.com>
Stability   :  unstable
Portability :  unportable

A Pacman updates availablility plugin for Xmobar
-}
module Xmobar.Plugins.PacmanUpdates (PacmanUpdates (..)) where

import System.Exit (ExitCode (..))
import System.Process (readProcessWithExitCode)
import Xmobar.Plugins.Command (Rate)
import Xmobar.Run.Exec

data PacmanUpdates = PacmanUpdates (String, String, String, String) Rate
  deriving (Read, Show)

instance Exec PacmanUpdates where
  alias = const "pacman"
  rate (PacmanUpdates _ r) = r
  run (PacmanUpdates (z, o, m, e) _) = do
    (exit, stdout, _) <- readProcessWithExitCode "checkupdates" [] ""
    return $ case exit of
      ExitFailure 2 -> z -- ero updates
      ExitFailure 1 -> e
      ExitSuccess -> case length $ lines stdout of
        0 -> impossible
        1 -> o
        n -> m >>= \c -> if c == '?' then show n else pure c
      _ -> impossible
   where
    impossible = error "This is impossible based on pacman manpage"
