packages feed

ymonad-0.1.0.0: src/ControlMain.hs

module Main where

import Control.Exception (bracketOnError, try)
import Network.Socket
import Network.Socket.ByteString qualified as NSB

main :: IO ()
main = do
  args <- getArgs
  case args of
    ["--socket", socketPath, "send", encoded] -> sendCommand socketPath encoded
    otherArgs -> die ("usage: ymonadctl --socket /path/to/ymonad.sock send '<command>'; got: " <> show otherArgs)

sendCommand :: FilePath -> String -> IO ()
sendCommand socketPath encoded = do
  result <-
    ( try
        ( bracketOnError
            (socket AF_UNIX Stream defaultProtocol)
            close
            ( \sock -> do
                connect sock (SockAddrUnix socketPath)
                NSB.sendAll sock (encodeUtf8 (toText encoded))
                close sock
            )
        ) ::
        IO (Either SomeException ())
    )
  case result of
    Left ex ->
      die
        ( "Failed to send command to YMonad control socket at "
            <> socketPath
            <> ": "
            <> displayException ex
        )
    Right () -> pass