module Aura.Shell where
import Aura.Types
import RIO
import qualified RIO.ByteString as B
import qualified RIO.Map as M
import qualified RIO.Text as T
import System.Process.Typed (proc, runProcess)
csi :: [Int] -> ByteString -> ByteString
csi args code = "\ESC[" <> B.intercalate ";" (map (encodeUtf8 . textDisplay) args) <> code
cursorUpLineCode :: Int -> ByteString
cursorUpLineCode n = csi [n] "F"
getTrueUser :: Environment -> Maybe User
getTrueUser env | isTrueRoot env = Just $ User "root"
| hasRootPriv env = User <$> M.lookup "SUDO_USER" env
| otherwise = User <$> M.lookup "USER" env
isTrueRoot :: Environment -> Bool
isTrueRoot env = M.lookup "USER" env == Just "root" && not (M.member "SUDO_USER" env)
hasRootPriv :: Environment -> Bool
hasRootPriv env = M.member "SUDO_USER" env || isTrueRoot env
getEditor :: Environment -> FilePath
getEditor = maybe "vi" T.unpack . M.lookup "EDITOR"
getLocale :: Environment -> Text
getLocale env = fromMaybe "C" . asum $ map (`M.lookup` env) ["LC_ALL", "LC_MESSAGES", "LANG"]
chown :: MonadIO m => User -> FilePath -> [String] -> m ()
chown (User usr) pth args = void . runProcess $ proc "chown" (args <> [T.unpack usr, pth])
hideCursor :: IO ()
hideCursor = B.putStr hideCursorCode
showCursor :: IO ()
showCursor = B.putStr showCursorCode
hideCursorCode :: ByteString
hideCursorCode = csi [] "?25l"
showCursorCode :: ByteString
showCursorCode = csi [] "?25h"
raiseCursorBy :: Int -> IO ()
raiseCursorBy = B.putStr . cursorUpLineCode