module Betty.Pid ( writePidFile ) where

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

import ClassyPrelude.Yesod

import System.Directory     (createDirectoryIfMissing)
import System.IO            (IOMode (WriteMode), hPrint, withFile)
import System.Posix.Process (getProcessID)

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

-- Write PID to /opt/keter/var/betty.pid so that monitoring apps can
-- monitor.
writePidFile :: IO ()
writePidFile = do

    -- TODO: hardcoded app name, fix.
    let appDir  = "/opt/keter/var"
        pidFile = appDir </> "betty.pid"

    createDirectoryIfMissing True appDir

    pid <- getProcessID
    withFile pidFile WriteMode $ \h -> hPrint h pid

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

module Betty.Pid ( writePidFile ) where

------------------------------------------------------------------------
--
-- Write process ID somewhere in the filesystem so that monitoring
-- apps can monitor.  If "/opt/keter/var" is writable or can be
-- created, write betty.pid there; do not write anything otherwise.
--
-- TODO: Ignoring failures silently is not a good idea! Fix.
--
------------------------------------------------------------------------

import ClassyPrelude.Yesod

import System.Directory     (createDirectoryIfMissing)
import System.IO            (IOMode (WriteMode), hPrint, withFile)
import System.Posix.Process (getProcessID)

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

writePidFile :: IO ()
writePidFile = do

    let pidDir  = "/opt/keter/var"
        pidFile = pidDir </> "betty.pid"

    catchAny (do createDirectoryIfMissing True pidDir
                 pid <- getProcessID
                 withFile pidFile WriteMode $ \h -> hPrint h pid)
        (const $ return ())

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

Handle exceptions from IO; add comment.
Handle exceptions from IO; add comment.

`createDirectoryIfMissing` and `hPrint` can throw IO exception; ignore
and continue if any of that happens.

Silently failing here may not be a good idea (monit the monitoring app
may go haywire), but what this is function does is not that critical
for general use.
