{-# LANGUAGE RecordWildCards #-}

-- Armor.hs: hOpenPGP-tools common ASCII de-Armor function
-- Copyright © 2012-2026  Clint Adams
--
-- vim: softtabstop=4:shiftwidth=4:expandtab
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as
-- published by the Free Software Foundation, either version 3 of the
-- License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

module HOpenPGP.Tools.Common.Armor
    ( doDeArmor
    ) where

import qualified Codec.Encryption.OpenPGP.ASCIIArmor as AA
import Codec.Encryption.OpenPGP.ASCIIArmor.Types (Armor (..))
import qualified Data.ByteString.Lazy as BL
import Data.Conduit (runConduitRes, (.|))
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import System.IO (stdin)

doDeArmor :: IO ()
doDeArmor = do
    a <- runConduitRes $ CB.sourceHandle stdin .| CL.consume
    let lbs = BL.fromChunks a
    case BL.uncons lbs of
        Just (firstByte, _)
            | firstByte >= 0x80 -> BL.putStr lbs
            | otherwise ->
                case (AA.decode (BL.toStrict lbs) :: Either String [Armor]) of
                    Right msgs -> BL.putStr $ BL.concat [bs | Armor _ _ bs <- msgs]
                    Left _ -> BL.putStr lbs
        Nothing -> pure ()
