-- Canonicalize.hs: hOpenPGP key tool canonicalize subcommand
-- Copyright © 2013-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.Hokey.Canonicalize
  (
    doCanonicalize
  ) where

import Codec.Encryption.OpenPGP.Serialize ()
import Codec.Encryption.OpenPGP.Types
import Control.Lens (_2, mapped, over)
import Data.Binary (get, put)
import Data.Conduit ((.|), runConduitRes)
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.Conduit.OpenPGP.Keyring (conduitToTKsDropping)
import Data.Conduit.Serialization.Binary (conduitGet, conduitPut)
import Data.List (nub, sort)

import System.IO
  ( stdin
  , stdout
  )

doCanonicalize :: IO ()
doCanonicalize =
  runConduitRes $ CB.sourceHandle stdin .| conduitGet get .|
  conduitToTKsDropping .|
  CL.map canonicalize .|
  CL.map put .|
  conduitPut .|
  CB.sinkHandle stdout
  where
    canonicalize tk =
      tk
        { _tkuRevs = sort (_tkuRevs tk)
        , _tkuUIDs = indepthsort (_tkuUIDs tk)
        , _tkuUAts = indepthsort (_tkuUAts tk)
        , _tkuSubs = indepthsort (_tkuSubs tk)
        }
    indepthsort :: (Ord a, Ord b) => [(a, [b])] -> [(a, [b])]
    indepthsort = nub . sort . over (mapped . _2) sort
