-- | Verification of the socket recipient PID

module SocketActivation.CheckRecipient where

import Essentials

import Control.Monad.IO.Class (MonadIO (liftIO))
import Data.Either (Either)
import System.IO (IO)

import qualified Control.Monad as Monad
import qualified System.Posix.Process as Sys

import SocketActivation.Concepts (Error(WrongProcess), Recipient (recipientPID))
import SocketActivation.Env (getEnv')
import SocketActivation.IO (IO' (IO', run), throwError)

checkRecipient :: IO (Either Error ())
checkRecipient :: IO (Either Error ())
checkRecipient = IO' () -> IO (Either Error ())
forall a. IO' a -> IO (Either Error a)
run do
    Recipient
recipient <- IO (Either Error Recipient) -> IO' Recipient
forall a. IO (Either Error a) -> IO' a
IO' (IO (Either Error Recipient) -> IO' Recipient)
-> IO (Either Error Recipient) -> IO' Recipient
forall a b. (a -> b) -> a -> b
$ forall a. Env' a => IO (Either Error a)
getEnv' @Recipient
    IO (Either Error ()) -> IO' ()
forall a. IO (Either Error a) -> IO' a
IO' (IO (Either Error ()) -> IO' ()) -> IO (Either Error ()) -> IO' ()
forall a b. (a -> b) -> a -> b
$ Recipient -> IO (Either Error ())
checkRecipient' Recipient
recipient

checkRecipient' :: Recipient -> IO (Either Error ())
checkRecipient' :: Recipient -> IO (Either Error ())
checkRecipient' Recipient
recipient = IO' () -> IO (Either Error ())
forall a. IO' a -> IO (Either Error a)
run do
    ProcessID
myPid <- IO ProcessID -> IO' ProcessID
forall a. IO a -> IO' a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO ProcessID
Sys.getProcessID
    Bool -> IO' () -> IO' ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
Monad.unless (Recipient -> ProcessID
recipientPID Recipient
recipient ProcessID -> ProcessID -> Bool
forall a. Eq a => a -> a -> Bool
== ProcessID
myPid) (IO' () -> IO' ()) -> IO' () -> IO' ()
forall a b. (a -> b) -> a -> b
$ Error -> IO' ()
forall a. Error -> IO' a
throwError Error
WrongProcess