summaryrefslogtreecommitdiff
path: root/kiki.hs
blob: 451552cbbac572aeedacea59c0882293a128f915 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE ViewPatterns  #-}
{-# LANGUAGE PatternGuards  #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Main ( main ) where

import Control.Monad
import Data.ASN1.BinaryEncoding
import Data.ASN1.Encoding
import Data.ASN1.Types
import Data.Binary
import Data.Bits
import Data.Char
import Data.IORef
import Data.Int
import Data.List
import Data.Maybe
import Data.OpenPGP
import Data.Ord
import Data.String
import Text.Read
import Text.Show.Pretty as PP ( ppShow )
import Data.Text.Encoding
import System.Posix.Files
import Foreign.C.Types (CTime(..))
import System.Environment
import System.Exit
import System.IO (hPutStrLn,stderr)
import qualified Data.ByteString.Char8 as S8
import Data.ByteArray.Encoding
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import Crypto.Hash.Algorithms (RIPEMD160(..))
import Crypto.Hash as C
import Data.ByteArray (convert)
import qualified Data.ByteString      as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Data.Map as Map
import Control.Arrow   (first,second)
import Data.Monoid ( (<>) )
import Data.Binary.Put

import CommandLine
import Data.OpenPGP.Util (verify, fingerprint, fingerprintv, GenerateKeyParams(..))
import ScanningParser
import PEM
import DotLock
import KeyRing hiding (pemFromPacket)
import Base58
import qualified CryptoCoins
-- import Chroot
import qualified SSHKey as SSH
import qualified DNSKey as DNS
import Data.Time.Clock.POSIX ( posixSecondsToUTCTime )
import Kiki
import KeyDB
import Network.Socket (SockAddr)
import FunctorToMaybe

-- {-# ANN module ("HLint: ignore Eta reduce"::String) #-}
-- {-# ANN module ("HLint: ignore Use camelCase"::String) #-}

isCertificationSig :: SignatureOver -> Bool
isCertificationSig (CertificationSignature {}) = True
isCertificationSig _                           = True

fpmatch :: Maybe [Char] -> Packet -> Bool
fpmatch grip key =
    (==) Nothing
         (fmap (backend (show $ fingerprint key)) grip >>= guard . not)
 where
    backend xs ys = and $ zipWith (==) (reverse xs) (reverse ys)

subkeysForDomain "onion" subs = do
        (code,(top,sub), kind, hashed,claimants) <- subs
        guard ("tor" `elem` kind)
        guard (code .&. 0x2 /= 0)
        maybeToList $ derToBase32 <$> derRSA sub
subkeysForDomain "ssh-rsa.cryptonomic.net" subs = do
        (code,(top,sub), kind, hashed,claimants) <- subs
        guard ("ssh-server" `elem` kind)
        guard (code .&. 0x2 /= 0)
        RSAKey (MPI n) (MPI e) <- maybeToList $ rsaKeyFromPacket sub
        let blob = SSH.sshrsa e n
            sha1 = C.hashlazy blob :: C.Digest C.SHA1
            subdomain = convertToBase Base16 sha1
        [ S8.unpack subdomain ]
subkeysForDomain _ _ = []

checkSelfAuthenticating parsed subs = do
        let subdom0 = L.fromChunks [encodeUtf8 (uid_subdomain parsed)]
            len = L.length subdom0
            subdom = Char8.unpack subdom0
            match k = subdom == take (fromIntegral len) k
        guard (len >= 16)
        listToMaybe $ filter match $ subkeysForDomain (uid_topdomain parsed) subs

listKeys :: FingerprintStyle -> [Packet] -> [Char]
listKeys style pkts = listKeysFiltered style [] pkts

-- | listKeysFiltered
--    @grips    fingerprints of keys to show
--    @pkts     list of pgp packets
-- Build the display output
-- Operates in List Monad...
-- returns all output as a single string
listKeysFiltered :: Foldable t => FingerprintStyle -> t [Char] -> [Packet] -> [Char]
listKeysFiltered style grips pkts0 = do
    let pkts | null grips = pkts0
             | otherwise  = scrub pkts0
        scrub [] = []
        scrub xs =
            let ys = dropWhile (\p -> not (isKey p && not (is_subkey p)) || not (matchAnyGrip p)) xs
                (as,bs) = span (\p -> not (isKey p) || is_subkey p || matchAnyGrip p) ys
            in as ++ scrub bs
        fp = case style of
                FingerprintAuto -> \p -> show (fingerprint p)
                Fingerprint5    -> \p -> show (fingerprintv 5 p)
        masterkeys = filter (\k -> isKey k && not (is_subkey k)) pkts
        (certs,bs) = getBindings pkts
        as = accBindings bs
        defaultkind (k:_) hs = k
        defaultkind []    hs = fromMaybe "subkey"
                                     ( listToMaybe
                                     . mapMaybe (fmap usageString . keyflags)
                                     $ hs)
        kinds = map (\(_,_,k,h,_)->defaultkind k h) as
        kindwidth = maximum $ map length kinds
        kindcol = min 20 kindwidth
        code (c,(m,s),_,_,_) = (fingerprint_material m,-c)
        ownerkey (_,(a,_),_,_,_) = a
        sameMaster (ownerkey->a) (ownerkey->b) = fingerprint_material a==fingerprint_material b
        matchAnyGrip top = any (flip fpmatch top . Just) grips
        matchgrip _ | null grips = True
        matchgrip ((code,(top,sub), kind, hashed,claimants):_) | matchAnyGrip top = True
        matchgrip _ = False
        gs = filter matchgrip $ groupBy sameMaster (sortBy (comparing code) as)
        singles = filter (\k -> fp k `notElem` map fp parents) masterkeys -- \\ parents
          where parents = do
                    subs@((_,(top,_),_,_,_):_) <- gs
                    return top
        showsigs claimants = map (\k -> "      " ++ "^ signed: " ++ fp k) claimants
    subs0 <- map Left gs ++ map Right singles
    let (top,subs) = case subs0 of Left subs1@((_,(top0,_),_,_,_):_) -> (top0,subs1)
                                   Right top0                        -> (top0,[])
                                   Left [] -> error "groupBy returned an empty group?"
    let subkeys = do
            (code,(top,sub), kind, hashed,claimants) <- subs
            let ar = case code of
                        0 -> " ??? "
                        1 -> " --> "
                        2 -> " <-- "
                        3 -> " <-> "
                        _ -> error "Unknown signature scenario."
                formkind = take kindcol $ defaultkind kind hashed ++ repeat ' '
                -- torhash = fromMaybe "" $ derToBase32 <$> derRSA sub
                (netid,kind') = maybe (0x0,"bitcoin")
                                      (\n->(CryptoCoins.publicByteFromName n,n))
                                      $ listToMaybe kind
            unlines $
                concat  [ " "
                        -- , grip top
                        , ar
                        , formkind
                        , " "
                        , fp sub
                        , kcipher sub
                        -- , " " ++ (torhash sub)
                        -- , " " ++ (concatMap (printf "%02X") $ S.unpack (ecc_curve sub))
                        ] -- ++ ppShow hashed
                    : if isCryptoCoinKey sub
                        -- then ("      " ++ "B⃦ " ++ bitcoinAddress sub) : showsigs claimants
                        -- then ("      " ++ "BTC " ++ bitcoinAddress sub) : showsigs claimants
                        then ("      " ++ "¢ "++kind'++":" ++ bitcoinAddress netid sub) : showsigs claimants
                        else showsigs claimants
        kcipher k = if isSecretKey k then " " ++ ciphername (symmetric_algorithm k)
                                     else ""
        uid = {- fromMaybe "" . listToMaybe $ -} do
            (keys,sigs) <- certs
            sig <- sigs
            guard (isCertificationSig sig)
            guard (topkey sig == top)
            let issuers = do
                    sig_over <- signatures_over sig
                    i <- maybeToList $ signature_issuer sig_over
                    let sigkeyid i | version top == 5 = take 16 i
                                   | otherwise        = reverse . take 16 . reverse $ i
                    maybeToList $ find_key (matchpr (auto_fp_version sig_over) i) (Message keys) (sigkeyid i)
                (primary,secondary) = partition (==top) issuers

            -- trace ("PRIMARY: "++show (map fingerprint primary)) $ return ()
            -- trace ("SECONDARY: "++show (map fingerprint secondary)) $ return ()
            guard (not (null primary))

            let UserIDPacket uid = user_id sig
                parsed = parseUID uid
                ar = maybe " --> " (const " <-> ") $ do
                        guard ( uid_realname parsed `elem` ["","Anonymous"])
                        guard (     uid_user parsed == "root" )
                        checkSelfAuthenticating parsed subs
            unlines $  (" " ++ ar ++ "@" ++ " " ++ uid_full parsed) : showsigs secondary
        -- (_,sigs) = unzip certs
    "master-key " ++ fp top ++ kcipher top ++ "\n" ++ uid ++"  ...\n" ++ subkeys ++ "\n"


{-
 - modify a UID to test the verify function properly
 - fails
modifyUID (UserIDPacket str) = UserIDPacket str'
 where
    (fstname,rst) = break (==' ') str
    str' = mod fstname ++ rst
    mod "Bob" = "Bob Slacking"
    mod x     = x
modifyUID other              = other
-}

readPublicKey :: Char8.ByteString -> RSAPublicKey
readPublicKey bs = RSAKey (MPI n) (MPI e)
 where
    (n,e) = fromMaybe (error "Unsupported key format")
                $ SSH.blobkey bs

-- | Returns the given list with its last element modified.
toLast :: (x -> x) -> [x] -> [x]
toLast f []  = []
toLast f [x] = [f x]
toLast f (x:xs) = x : toLast f xs

-- partitionStaticArguments :: Ord a => [(a, Int)] -> [a] -> ([[a]], [a])
partitionStaticArguments :: [(String, Int)]
                            -> [String] -> ([[String]], [String])
partitionStaticArguments specs args = psa args
 where
    smap = Map.fromList specs
    psa [] = ([],[])
    psa (a:as) =
      case Map.lookup a smap of
        Nothing | (k,'=':v) <- break (=='=') a
                , Just 1 <- Map.lookup k smap
            -> first ([k,v]:) $ psa as
        Nothing -> second (a:) $ psa as
        Just n  -> first ((a:take n as):) $ psa (drop n as)

show_wk :: FingerprintStyle
           -> FilePath
           -> Maybe [Char] -> KeyDB -> IO ()
show_wk style secring_file grip db = do
    -- printf "show_wk(%s,%s,%s)\n" (show secring_file) (show grip) (show db)
    let gripmatch (KeyData p _ _ _) =
            Map.member secring_file (locations p)
            || Map.member "&secret" (locations p)
        Message sec = flattenFiltered False gripmatch db
    putStrLn $ listKeysFiltered style (maybeToList grip) sec

debug_dump :: FilePath -> p -> KeyDB -> IO ()
debug_dump secring_file grip db = do
    let gripmatch (KeyData p _ _ _) =
            Map.member secring_file (locations p)
            || Map.member "&secret" (locations p)
        Message sec = flattenFiltered False gripmatch db
    mapM_ print sec

show_all :: FingerprintStyle -> KeyDB -> IO ()
show_all style db = do
    let Message packets = flattenFiltered True (const True) db
    putStrLn $ listKeys style packets

show_packets :: (Eq a, IsString a) =>
                [a] -> KeyDB -> IO ()
show_packets puborsec db = do
    let Message packets = flattenFiltered (case puborsec of { "sec":_ -> False; _ -> True })
                                          (const True)
                                          db
    forM_ packets $ putStrLn . showPacket

show_whose_key :: Maybe RSAPublicKey -> KeyDB -> IO ()
show_whose_key input_key db =
    flip (maybe $ return ()) input_key $ \input_key -> do
    let ks = whoseKey input_key db
    case ks of
        [KeyData k _ uids _] -> do
            putStrLn $ show $ fingerprint (packet k)
            mapM_ putStrLn $ unUidString <$> Map.keys uids
        (_:_) -> error "ambiguous"
        [] -> return ()

show_dns :: [Char] -> String -> KeyDB -> IO ()
show_dns keyspec wkgrip db = either warn putStrLn $ show_pem' keyspec wkgrip db dnsPresentationFromPacket

dnsPresentationFromPacket :: Monad m => Packet -> m String
dnsPresentationFromPacket k = do
    let RSAKey (MPI n) (MPI e)  = fromJust $ rsaKeyFromPacket k
        dnskey = DNS.RSA n e
        bin = runPut (DNS.putRSA dnskey)
        qq  = S8.unpack $ convertToBase Base64 (L.toStrict bin)
        ttl = 24*60*60 -- 24 hours in seconds
        flags = 256 -- (ZONE-key = bit7) TODO: is this a zone key or a key-signing key?
        algo = 8 -- RSASHA256 -- TODO: support other algorithm
    return $ unwords
        ["."
        ,show ttl
        ,"IN"
        ,"DNSKEY"
        ,show flags
        ,"3" -- protocol MUST be 3 (RFC 4034)
        ,show algo
        ,qq
        ]

show_id :: FingerprintStyle -> String -> p -> KeyDB -> IO ()
show_id style keyspec wkgrip db = do
    let s = parseSpec "" keyspec
    let ps = do
            (_,k) <- filterMatches (fst s) (kkData db)
            mp <- flattenTop "" True k
            return $ packet mp
    -- putStrLn $ "show key " ++ show s
    putStrLn $ listKeys style ps

show_wip :: [Char] -> String -> KeyDB -> IO ()
show_wip keyspec wkgrip db = do
    let s = parseSpec wkgrip keyspec
    flip (maybe $ void (warn (keyspec ++ ": not found")))
         (selectSecretKey s db)
         $ \k -> do
    let nwb = maybe 0x80 CryptoCoins.secretByteFromName $ snd s
    putStrLn $ walletImportFormat nwb k

show_torhash :: FilePath -> p -> IO ()
show_torhash pubkey _ = do
    bs <- Char8.readFile pubkey
    let -- parsekey :: ((MPI -> MPI -> Packet) -> _ -> b) -> Char8.ByteString -> Maybe b
        parsekey f dta  = do
            let mdta = fmap L.fromStrict $ functorToMaybe $ convertFromBase Base64 (Char8.toStrict dta)
            e <- decodeASN1 DER <$> mdta
            asn1 <- either (const Nothing) (Just) e
            k <- either (const Nothing) (Just . fst) (fromASN1 asn1)
            return $ f (packetFromPublicRSAKey pgpver (error "torhash timestmap?")) k

        pgpver = 4 :: Word8

        addy :: String -> String
        addy hsh = take 16 hsh ++ ".onion " ++ hsh
        pkcs1 = fmap ( parsekey (\f (RSAKey n e)  -> f n e) . pemBlob )
                     $ pemParser (Just "RSA PUBLIC KEY")
        pkcs8 = fmap ( parsekey (\f (RSAKey8 n e) -> f n e) . pemBlob )
                     $ pemParser (Just "PUBLIC KEY")
        cert = fmap (fmap pcertKey . parseCertBlob pgpver False . pemBlob)
                     $ pemParser (Just "CERTIFICATE")
        keys = catMaybes $ scanAndParse (pkcs1 <> pkcs8 <> cert) $ Char8.lines bs
    mapM_ (putStrLn . addy . torhash) keys

show_cert :: [Char] -> String -> KeyDB -> IO ()
show_cert keyspec wkgrip db = do
    let s = parseSpec wkgrip keyspec
    case selectPublicKeyAndSigs s db of
        [] -> void $ warn (keyspec ++ ": not found")
        [(_,k,sigs)] -> do
            {-
            let rsa = pkcs8 . fromJust $ rsaKeyFromPacket k
                der = encodeASN1 DER (toASN1 rsa [])
                qq  = Base64.encode (L.unpack der)
            putStrLn $ writePEM "PUBLIC KEY (TODO: CERT)" qq -- ("TODO "++show keyspec)
            -}
            let cs = mapMaybe x509cert $ (sigs >>= hashed_subpackets)
                ds = map decodeBlob $ map (ParsedCert k (posixSecondsToUTCTime $ fromIntegral $ timestamp k)) cs
                qqs = map (S8.unpack . convertToBase Base64 . L.toStrict) ds
                pems = map (writePEM PemCertificate) qqs
            forM_ pems putStrLn
        _ -> void $ warn (keyspec ++ ": ambiguous")

{-
show_cert certfile _ = do
    bs <- Char8.readFile certfile
    let dta = scanAndParse (fmap pemBlob $ pemParser $ Just "CERTIFICATE") $ Char8.lines bs
        mdta = do
            dta <- listToMaybe dta
            L.pack <$> Base64.decode (Char8.unpack dta)
    let c = mdta >>= parseCertBlob True
        d = mdta >>= parseCertBlob False
        -- e = mdta >>= parseCertBlob 2
        -- b64 = Base64.encode . S.unpack
        b64L = Base64.encode . L.unpack
        -- hex = Base16.encode . S.unpack
        hexL = Base16.encode . L.unpack
    putStrLn $ maybe "" (fingerprint . pcertKey) c
    putStrLn $ maybe "" (torhash . pcertKey) c
    putStrLn ""
    putStrLn ""
    putStrLn $ maybe "" (("key = " ++) . show . pcertKey) c
    putStrLn ""
    putStrLn $ maybe "" (("small blob length = " ++) . show . L.length . pcertBlob) c
    putStrLn $ maybe "" (("small blob = " ++) . b64L . pcertBlob) c
    putStrLn $ maybe "" (("   decoded = " ++) . b64L . decodeBlob) c
    putStrLn ""
    putStrLn $ maybe "" (("  big blob length = " ++) . show . L.length . pcertBlob) d
    putStrLn $ maybe "" (("  big blob = " ++) . b64L . pcertBlob) d
    putStrLn $ maybe "" (("   decoded = " ++) . b64L . decodeBlob) d
    {-
    putStrLn ""
    putStrLn $ maybe "" ((" gzip blob length = " ++) . show . L.length . pcertBlob) e
    putStrLn ""
    putStrLn $ maybe "" ((" gzip blob = " ++) . b64L . pcertBlob) e
    -}
    -- ASN1 starts:
    --   1  2  3  4  5  6  7  8
    --   cl....pc.tag..........
    -- Start Sequence tag = 0x10
    -- Start Sequence cl = 0
    let v = encodeASN1 DER [Start Sequence]
    putStrLn ""
    putStrLn $ "prefix = " ++ hexL v
    return ()
-}

cannonical_eckey :: (Integral b1, Integral b2) =>
                    b1 -> b2 -> [Word8]
cannonical_eckey x y = 0x4:pad32(numToBytes x) ++ pad32(numToBytes y) :: [Word8]
 where
  numToBytes n = reverse $ unfoldr getbyte n
    where
        getbyte d = do
            guard (d/=0)
            let (q,b) = d `divMod` 256
            return (fromIntegral b,q)
  pad32 xs = replicate zlen 0 ++ xs
    where
        zlen = 32 - length xs


bitcoinAddress :: Word8 -> Packet -> String
bitcoinAddress network_id k = address
    where
            Just (MPI x) = lookup 'x' (key k)
            Just (MPI y) = lookup 'y' (key k)
            pub = cannonical_eckey x y
            hsh = S.cons network_id . ripemd160 . sha256 . S.pack $ pub
            sha256 x = convert (C.hash x :: Digest SHA256) :: S.ByteString
            ripemd160 x = convert (C.hash x :: Digest RIPEMD160) :: S.ByteString
            address = base58_encode hsh

whoseKey :: RSAPublicKey -> KeyDB -> [KeyData]
whoseKey rsakey db = filter matchkey (keyData db)
 where
    matchkey (KeyData k _ _ subs) =
        any (ismatch k) $ Map.elems subs

    ismatch k (SubKey mp sigs) =
          Just rsakey == rsaKeyFromPacket (packet mp)
       && any (check (packet k) (packet mp)) sigs

    check k sub (sig,_) = not . null $ do
        s <- signatures . Message $ [k,sub,packet sig]
        fw <- signatures_over $ verify (Message [k]) s
        subsig <- mapMaybe backsig (unhashed_subpackets $ packet sig)
        subsig_so <- signatures (Message [k,sub,subsig])
        guard (  isSubkeySignature subsig_so
              && isSameKey (topkey subsig_so) k
              && isSameKey (subkey subsig_so) sub )
        s2 <- signatures . Message $ [k,sub,subsig]
        signatures_over $ verify (Message [sub]) s2

    isSameKey a b = sort (key apub) == sort (key bpub)
     where
        apub = secretToPublic a
        bpub = secretToPublic b



kiki_usage :: Export -> Import -> Secret -> String -> IO ()
kiki_usage ((== Export) -> bExport) ((== Import) -> bImport) ((== Secret) -> bSecret) cmd = putStr $
        case cmd of
         "show" -> unlines $
            ["kiki show [options...]"
            ,""
            ,"     show displays information about keys stored in the data files which resides in"
            ,"     the home directory (see --homedir)."
            ,""
            ,"     The files pubring.gpg and subring.gpg in the directory specified by the "
            ,"     --homedir option are implicitly included in the keyring set."
            ,""
            ,"Options: "
            ] ++ commonOptions ++
                ["     --working"
                ,"           Show fingerprints for the working key (which will be used to"
                ,"           make signatures) and all its subkeys and UID.  This action is"
                ,"           inferred when no options are supplied."
                ,""
                ,"     --key SPEC"
                ,"           Show fingerprints for the specified key and all its subkeys"
                ,"           and UID. (See 'kiki help spec' for more information.)"
                ,""
                ,"     --all Show fingerprints and UIDs and usage tags for all known keys."
                ,""
                ,"     --whose-key"
                ,"           Shows the fingerprint and UIDs of the key that owns the one that"
                ,"           is input on stdin in ssh-rsa format."
                ,""
                ,"     --dns SPEC"
                ,"           Outputs the DNSKEY presentation format (RFC4034) of the public key"
                ,"           corresponding to SPEC."
                ,"           (See 'kiki help spec' for more information.)"
                ,""
                ,"     --pem SPEC"
                ,"           Outputs the PKCS #8 public key corresponding to SPEC."
                ,"           (See 'kiki help spec' for more information.)"
                ,""
                ,"     --cert SPEC"
                ,"           Outputs X509 certificates associated with the key SPEC."
                ,"           (See 'kiki help spec' for more information.)"
                ,""
                ,"     --ssh SPEC"
                ,"           Outputs the ssh-rsa blob for the specified public key."
                ,"           (See 'kiki help spec' for more information.)"
                ,""
                ,"     --wip SPEC"
                ,"           Outputs the secret crypto-coin key in Wallet Input Format."
                ,"           (See 'kiki help spec' for more information.)"
                ,""
                ,"     --torhash FILE"
                ,"           Outputs tor address and base32 hash of the PEM-format key in"
                ,"           the given file."
                ,""
                ,"     --dump     For debugging, a thorough info dump of your secret keyring."
                ,""
                ,"     --help     Shows this help screen."
                ,""
                ]
         "sync-secret" -> unlines $
            ["kiki sync-secret [KEYSPEC ...]"
            ,"kiki sync-secret FLAGS [--pems KEYSPEC ...] [--keyrings FILE ...] [--hosts FILE ...]"
            ,"                       [--wallets FILE ...]"
            ,""
            ,"     sync-secret syncs the information inside your OpenGPG keyring with information"
            ,"     in other files. Information flows both in and out of your keyring. This one command"
            ,"     is powerful enough to impliment all the functionality of kiki commands in the import-*,"
            ,"     export-*, and sync-* families. Those other commands are mainly added to facilitate"
            ,"     a redundant safe gaurd which restricts the flow of information in such a way that is"
            ,"     theoretically less error prone."
            ,""
            ,"     sync-secret works by first creating a combined database containing all information"
            ,"     and then updating all files (including OpenGPG files, as well as files specified as"
            ,"     arguments to the options --keyrings, --wallets, and --hosts) with information from"
            ,"     from that combined database."
            ,""
            ,"     Master keys in keyring files are fleshed out with all known subkeys"
            ,"     in any file in which they appear. Ordinarily, if a file does not contain the master key"
            ,"     already, it will not be added. However, in the case of --import or --import-if-authentic"
            ,"     new master keys may be added to your OpenGPG keyring."
            ,""
            ,"     Cryptocoin keys in wallet files are fleshed out with all CryptoCoin subkeys of the working"
            ,"     key. The working key is updated with new CryptoCoin subkeys from all specified wallets."
            ,"     Ordinarily, only one wallet is specified on the command line. If multiple wallets are"
            ,"     specified, they will all have the same keys after the the operation completes."
            ,""
            ,"     The --hosts option is experimental and may be removed in the future. Any files given"
            ,"     as arguments to this option will be assumed to be in the format of /etc/hosts, and will"
            ,"     be updated with any hostname information currently stored within your OpenGPG keyring."
            ,"     Additionally, if the file has hostnames for the ip corresponding to a master key, then"
            ,"     then the masterkey is updated with unsigned annotations recording the additional hostnames."
            ,"     Warning: this effects all master keys, regardless of whether they have secret key"
            ,"     information, hence the annotations being unsigned."
            ,""
            ,"     The files pubring.gpg and secring.gpg in the directory specified by the"
            ,"     --homedir option are implicitly included in the keyring set even if they"
            ,"     are not included after the --keyrings option."
            ,""
            ,"     If KEYSPEC arguments appear prior to any of --keyrings, --wallets, or --hosts,"
            ,"     then they are interpretted as if arguments to --pems."
            ,""
            ] ++ syncflags ++ specifyingFiles
         "sync-public" -> unlines $
            ["kiki sync-public [options...]"
            ,""
            ,"     sync-public merges a set of key files into a combined database and then"
            ,"     uses the database to update all the input files, those inside and outside of"
            ,"     of the home directory (see --homedir), to have the most complete information."
            ,""
            ,"     The files pubring.gpg and secring.gpg in the directory specified by the "
            ,"     --homedir option are implicitly included in the keyring set. However, the"
            ,"     difference betwen this command and sync-secret is that no secret keys are"
            ,"     modified by this command regardless of input. Export of secret keys is"
            ,"     possible using this command, but will only occur if the secret master key"
            ,"     is already in the external file. (TODO, remove this capacity entirely)"
            ,""
            ,"     Subkeys that are imported with kiki are given an annotation \"usage@\" which"
            ,"     indicates what the key is for.  This tag can be used as a SPEC to select a"
            ,"     particular key.  Master keys may be specified by using fingerprints or by"
            ,"     specifying a substring of an associated UID."
            ,""
            ,"     (See 'kiki help spec' for more information.)"
            ] ++ syncflags ++ specifyingFiles
         "import-secret" -> unlines $
            ["kiki import-secret [options...]"
            ,""
            ,"     import-secret uses a set of key files to update your keyring.  It does not"
            ,"     alter any files outside of the home directory (see --homedir)."
            ,""
            ,"     The files pubring.gpg and secring.gpg in the directory specified by the "
            ,"     --homedir option are implicitly included in the keyring set. Unlike the"
            ,"     sync-secret command, information will flow into these files, but not out"
            ,"     of them."
            ,""
            ,"     Subkeys that are imported with kiki are given an annotation \"usage@\" which"
            ,"     indicates what the key is for.  This tag can be used as a SPEC to select a"
            ,"     particular key.  Master keys may be specified by using fingerprints or by"
            ,"     specifying a substring of an associated UID."
            ,""
            ,"     (See 'kiki help spec' for more information.)"
            ] ++ syncflags ++ specifyingFiles
         "import-public" -> unlines $
            ["kiki import-public [options...]"
            ,""
            ,"     import-public uses a set of key files to update your keyring.  It does not"
            ,"     alter any files outside of the home directory (see --homedir). Nor does it"
            ,"     alter your secring.gpg file."
            ,""
            ,"     The files pubring.gpg and secring.gpg in the directory specified by the "
            ,"     --homedir option are implicitly included in the keyring set. However, the"
            ,"     difference betwen this command and import-secret is that no secret keys are"
            ,"     modified by this command regardless of input. Export of secret keys is"
            ,"     possible using this command, but will only occur if the secret master key"
            ,"     is already in the external file. (TODO, remove this capacity entirely)"
            ,""
            ,"     Subkeys that are imported with kiki are given an annotation \"usage@\" which"
            ,"     indicates what the key is for.  This tag can be used as a SPEC to select a"
            ,"     particular key.  Master keys may be specified by using fingerprints or by"
            ,"     specifying a substring of an associated UID."
            ,""
            ,"     (See 'kiki help spec' for more information.)"
            ] ++ syncflags  ++ specifyingFiles
         "export-secret" -> unlines $
            ["kiki export-secret [options...]"
            ,""
            ,"     export-secret updates a set of key files using information from your keyring."
            ,""
            ,"     The files pubring.gpg and secring.gpg in the directory specified by the"
            ,"     --homedir option are implicitly included in the keyring set. Unlike with the"
            ,"     sync-secret command, information only flows out of these files and not in to"
            ,"     them. Barring this however, the usage and behavior of export-secret is similar"
            ,"     to that of sync-secret."
            ,""
            ,"     (See 'kiki help spec' for more information.)"
            ,""
            ] ++ syncflags ++  specifyingFiles
         "export-public" -> unlines $
            ["kiki export-public [options...]"
            ,""
            ,"     export-public updates a set of key files using information from your keyring."
            ,""
            ,"     The files pubring.gpg and secring.gpg in the directory specified by the "
            ,"     --homedir option are implicitly included in the keyring set. However, the"
            ,"     difference betwen this command and export-secret is that no secret keys are"
            ,"     exported by this command regardless of input."
            ,""
            ,"     (See 'kiki help spec' for more information.)"
            ,""
            ] ++ syncflags ++ specifyingFiles
         "spec" -> unlines keyspec
         x -> "Undocumented command "++show x++"."
        where
            commonOptions :: [String]
            commonOptions =
                ["     --help"
                ,"                Gives usage information"
                ,""
                ,"     --trace-verify"
                ,"                For debugging, stderr traces for every signature verification."
                ,""
                ,"     --fingerprint=5"
                ,"                Use SHA256-based (PGP v5) fingerprints even for PGP v4 key packets."
                ,""
                ] ++ documentHomeDir ++ [""]
                  ++ documentPassphraseFDFlag bExport bImport bSecret
            showwk :: [String]
            showwk =
                ["     --show-wk"
                ,"                After the operation completes, output the possibly modified"
                ,"                working key identity information."
                ,""
                ]
            syncflags :: [String]
            syncflags =
                [""
                ,"Flags:"] ++ commonOptions
                           ++ showwk
                           ++ documentImportFlag            bExport bImport bSecret
                           ++ documentImportIfAuthenticFlag bExport bImport bSecret
                           ++ documentAutoSignFlag          bExport bImport bSecret
            specifyingFiles :: [String]
            specifyingFiles =
                    ["SPECIFYING FILES:"
                    ] ++ documentKeyPairsOption bExport bImport bSecret
                      ++ documentKeyRingsOption bExport bImport bSecret
                      ++ documentWalletsOption  bExport bImport bSecret
                      ++ documentHostsOption    bExport bImport bSecret
            keyspec :: [String]
            keyspec = -- unlines $
                 ["Specifying keys on the kiki command line:"
                 ,""
                 ,"  SPEC ::= MASTER/SUBKEY"
                 ,""
                 ,"  SPEC indicates a specific key in the keyring, in it's longest incarnation,"
                 ,"  it is of the form MASTER/SUBKEY where MASTER and SUBKEY are documented below."
                 ,"  If kiki can infer the key unambiguously, either via the command in question or"
                 ,"  the contents of the keyring, then it is permissable to ommit either MASTER or"
                 ,"  SUBKEY, in which case the slash may also be ommitted unless it is used via its"
                 ,"  position to indicate whether a SUBKEY or MASTER is intended."
                 ,""
                 ,"  MASTER may be any of"
                 ,"     * The tail end (or, for v5, front end) of a fingerprint prefixed by 'fp:'"
                 ,"     * A sub-string of a user id (without slashes) prefixed by 'u:'"
                 ,"     * 40 characters of hexidecimal (kiki will assume this to be a fingerprint)"
                 ,"     * A sub-string of a user id (without slashes, the prefix 'u:' is optional)"
                 ,""
                 ,"  SUBKEY may be any of"
                 ,"     * The tail end (or, for v5, front end) of a fingerprint prefixed by 'fp:'"
                 ,"     * An exact match of a usage tag prefixed by 't:'"
                 ,"     * 40 characters of hexidecimal (kiki will assume this to be a fingerprint)"
                 ,"     * An exact match of a usage tag (The prefix 't:' is optional)"
                 ,""
                 ,"     In parsing the spec, kiki will attempt to match the string to one of the"
                 ,"     above formats, in the order presented."
                 ,""
                 ,"  Examples of valid SPEC strings:"
                 ,""
                 ,"      fp:4A39F/tor"
                 ,"      u:joe/tor"
                 ,"      u:joe/t:tor"
                 ,"      u:joe/fp:4abf30"
                 ,"      joe/tor"
                 ,"      5E24CD442AA6965D2012E62A905C24185D5379C2"
                 ]

documentHomeDir :: [String]
documentHomeDir =
                ["     --homedir DIR"
                ,"                Where to find the files secring.gpg and pubring.gpg. The"
                ,"                default location is taken from the environment variable"
                ,"                GNUPGHOME. If this environment variable is not set and no"
                ,"                directory is specified using this option then a hardcoded"
                ,"                default of ~/.gnupg is assumed. "
                ,""
                ,"                WARNING: Confusingly, this is *not* your home directory as"
                ,"                given by the HOME environment variable. The option is named"
                ,"                or rather misnamed in a fashion similar to the gpg option with"
                ,"                exactly the same functionality."
                ]

documentPassphraseFDFlag :: IsString a =>
                            p1 -> p2 -> Bool -> [a]
documentPassphraseFDFlag bExport bImport bSecret =
    if bSecret then
                ["     --passphrase-fd FD"
                ,"                The file descripter from which to read a passphrase. If FD is"
                ,"                0, then the passphrase is inputted via stdin. Note that this"
                ,"                requires the user to issue CTRL-D to send EOF, so that kiki"
                ,"                knows to continue."
                ,""]
               else []

documentImportFlag :: IsString a =>
                      p1 -> Bool -> p2 -> [a]
documentImportFlag bExport bImport bSecret =
    if bImport  then
                    ["     --import   Add master keys to pubring.gpg.  Without this option, only UID"
                    ,"                and subkey data is updated. "
                    ,""]
                else []

documentImportIfAuthenticFlag :: IsString a =>
                                 p1 -> Bool -> p2 -> [a]
documentImportIfAuthenticFlag bExport bImport bSecret =
    if bImport  then
                    ["     --import-if-authentic"
                    ,"                Add signed master keys to pubring.gpg.  Like --import except that"
                    ,"                only keys with signatures from the working key (--show-wk) are"
                    ,"                imported."
                    ,""]
                else []

documentAutoSignFlag :: IsString a =>
                        p1 -> p2 -> p3 -> [a]
documentAutoSignFlag bExport bImport bSecret =
                    ["     --autosign Sign all cross-certified tor-style UIDs."
                    ,"                A tor-style UID is of the form:"
                    ,"                        Anonymous <root@HOSTNAME.onion>"
                    ,"                It is considered cross certified if there exists a cross-certified"
                    ,"                'tor' subkey corresponding to the address HOSTNAME.onion."
                    ,""]
documentKeyPairsOption :: Bool -> Bool -> Bool -> [String]
documentKeyPairsOption bExport bImport bSecret =
            ["    --pems [KEYSPEC ...]"
            ] ++ case (bExport,bImport,bSecret) of
                (True,True,True) -> -- sync-secret
                    ["                This option specifies the paths of such private PEM files which"
                    ,"                either currently contain keys to be imported, or lack keys to"
                    ,"                be exported. If your working key has no subkey with the given"
                    ,"                tag, and the file is empty or does not exist, and a shell"
                    ,"                command is specified in braces, then the shell command will be"
                    ,"                executed in a modified environment with the expectation of"
                    ,"                creating the PEM file for import."
                    ,""
                    ] ++ afterSecond
                (True,True,False) -> -- sync-public NOT-IMPLEMENTED
                    ["                This option specifies the paths of PEM files, of both the"
                    ,"                public and private variety, which either currently contain"
                    ,"                public keys to be imported, or lack public keys to be exported."
                    ,"                If your working key has no subkey with the given tag, and the"
                    ,"                file is empty or does not exist, and a shell command is"
                    ,"                specified in braces, then the shell command will be executed in"
                    ,"                a modified environment with the expectation of creating the PEM"
                    ,"                file for import. Unlike the sync-secret command, this command"
                    ,"                leaves no possibility of secret key information leaking from"
                    ,"                your OpenGPG keyring into specified files."
                    ,""
                    ] ++ afterSecond
                (False,True,True) -> -- import-secret
                    ["                This option specifies the paths of such private PEM files which"
                    ,"                contain keys to be imported.  If your working key has no subkey"
                    ,"                with the given tag, and the file is empty or does not exist,"
                    ,"                and a shell command is specified in braces, then the shell"
                    ,"                command will be executed in a modified environment with the"
                    ,"                expectation of creating the PEM file for import. Files external"
                    ,"                to your OpenGPG keyring will not be modified by this command."
                    ,""
                    ] ++ afterSecond
                (False,True,False) -> -- import-public NOT-IMPLEMENTED
                    ["                This option specifies the paths of PEM files, of both the"
                    ,"                public and private variety, which currently contain keys to"
                    ,"                be imported.  If your working key has no subkey with the"
                    ,"                given tag, and the file is empty or does not exist, and a"
                    ,"                shell command is specified in braces, then the shell command"
                    ,"                will be executed in a modified environment with the"
                    ,"                expectation of creating the PEM file for import. Files"
                    ,"                external to your OpenGPG keyring will not be modified by"
                    ,"                this command.  Unlike the import-secret command, this"
                    ,"                command leaves no possibility of secret key information"
                    ,"                leaking from your OpenGPG keyring.  "
                    ,""
                    ] ++ afterSecond
                (True,False,True) -> -- export-secret
                    ["                This option specifies the paths of PEM files, of the private or"
                    ,"                public variety, which lack information to be exported. Note that"
                    ,"                files currently in the public format may be overwritten to update"
                    ,"                them to the private format which holds both public and private"
                    ,"                key information."
                    ,""
                    ] ++ afterSecond
                (True,False,False) -> -- export-public
                    ["                This option specifies the paths of PEM files, of the private or"
                    ,"                public variety, which lack public keys to be exported.  Unlike"
                    ,"                the export-secret command, this command leaves no possibility"
                    ,"                of secret key information leaking from your OpenGPG keyring"
                    ,"                into the specified files."
                    ,""
                    ] ++ afterSecond
                _ -> afterSecond
    where afterSecond =
            ["                Subkeys that are imported with kiki are given an annotation"
            ,"                \"usage@\" which indicates what the key is for.  This tag can"
            ] ++ if bImport then n000Import else n000Export
          n000Import =
            ["                be used as a SPEC to select a particular key. If a specifed PEM"
            ,"                file contains a novel key for an existing tag, it will imported,"
            ,"                and you will have multiple keys with the same tag."
            ,""
            ,"                Each KEYSPEC specifies that a key should match the content and"
            ,"                timestamp of an external file which is in the PKCS #1 private"
            ,"                RSA key format." -- " or in the PKCS #8 public key format."
            ] ++ n0
          n000Export =
            ["                be used as a SPEC to select a particular key."
            ,""
            ,"  (TODO: check) Each KEYSPEC specifies that a key should match the content and"
            ,"                timestamp of an indicated external file which is either in PKCS #1"
            ,"                private RSA key format or in PKCS #8 public key format (provided"
            ,"                that the file already exists). If the file does not exist, it"
            ] ++ (if bSecret then n00Secret else n00Public) ++ n0
          n00Secret =
            ["                will be created and have PKCS #1 Private RSA Key format."
            ]
          n00Public =
            ["                will be created and have PKCS #8 Public Key format."
            ]

          n0 =
            [""
            ,"                If there is only one master key in your keyring and only one"
            ,"                key is used for each purpose, then it is possible for SPEC in"
            ,"                this case to merely be a tag which offers information about"
            ,"                what this key is used for, for example, any of `tor',"
            ,"                `ssh-client', `ssh-host', or `strongswan' will do."
            ,""
            ,"                KEYSPEC ::= tag '=' file"
            ] ++ if bImport then "                          | tag '=' file  '{' <shell command to create key file> '}'":next
                            else next
          next =
            [""
            ,"                Or in more complicated cases,"
            ,""
            ,"                KEYSPEC ::= SPEC '=' file"
            ] ++ if bImport then "                          | SPEC '=' file  '{' <shell command to create key file> '}'":next'
                            else next'
          next' =
            [""
            ,"                where the format of SPEC is documented in 'kiki help spec'."
            ] ++ next''
          next'' = if bImport then timeStamps ++ next''' else next'''
          timeStamps =
            [""
            ,"                Your OpenGPG keyring contains time stamps for each subkey."
            ,"                Timestamps of newly imported keys will reflect the mtimes of"
            ,"                the files from which they were imported.  In the case that the"
            ,"                key already exists in your OpenGPG keyring as well as in one of"
            ,"                the specified files, the timestamp in your OpenGPG keyring is"
            ,"                not updated."]
          next'''=
            [""
            ,"                Note that this option is implicit if no options documented in"
            ,"                this section were specified.  See 'kiki help spec' for more"
            ,"                information."
            ,""
            ,"                (See 'kiki help spec' for more information.)"
            ,""
            ]

documentKeyRingsOption :: Bool -> Bool -> Bool -> [String]
documentKeyRingsOption bExport bImport bSecret =
            ["    --keyrings [FILE ...]"
            ,"                These files are PGP keyring files.  The format is similar to"
            ,"                that of the GNU GPG state files: pubring.gpg and secring.gpg."
            ,"                Those files needn't be specified here as they are included"
            ,"                implicitly."
            ,""
            ]

documentWalletsOption :: Bool -> Bool -> Bool -> [String]
documentWalletsOption bExport bImport False = []
documentWalletsOption bExport bImport True =
              ["    --wallets  [FILE ...]"
              ,"                Provide wallet files with secret crypto-coin keys in Wallet"
              ,"                Import Format.  The keys will be treated as subkeys of your"
              ,"                current working key (the one shown by --show-wk)."
              ,""]

documentHostsOption :: Bool -> Bool -> Bool -> [String]
documentHostsOption bExport bImport bSecret =
            ["    --hosts    [FILE ...]"
            ,"                EXPERIMENTAL! May be removed in the future.  This option"
            ,"                specifies files from which to read or write hostname aliases."
            ,"                The format is the same as /etc/hosts on unix systems.  WARNING:"
            ,"                hostname aliases may be imported into the gpg keyring files,"
            ,"                but they are currently NOT signed and may be altered in"
            ,"                transit."
            ,""]


commonArgSpec :: [(String,Int)]
commonArgSpec = [ ("--homedir",1)
                , ("--passphrase-fd",1)
                , ("--fingerprint",1)
                , ("--help",0)
                ]

-- |
-- Arguments:
--
--   * option-count pairs - List of option names paired with number of expected values to follow them.
--
--   * polyvariadic options - List of option names that can take any number of arguments.
--
--   * default polyvariadic - Implicit polyvariadic option if no other option is specified.
--
--   * arguments - list of arguments to be parsed.
--
-- Returns:
--
--   * (non-variadic only) options and corresponding arguemnts in list of lists form.
--
--   * (variadic only) map of option name to argument lists.
--
processArgs :: [(String,Int)] -> [String] -> String -> [String] -> ([[String]],Map.Map String [String])
processArgs sargspec polyVariadicArgs defaultPoly args_raw = (sargs,margs)
    where
        (args,trail1) = break (=="--") args_raw
        trail = drop 1 trail1
        sargspec' = commonArgSpec ++ sargspec
        (sargs,margs) =
                (sargs, foldl' (\m (k:xs)->Map.alter (appendArgs k xs) k m)
                               Map.empty
                               gargs)
                    where (sargs,vargs) = partitionStaticArguments sargspec' args
                          argspec = map fst sargspec' ++ polyVariadicArgs
                          args' = if null defaultPoly || map (take 1) (take 1 vargs) == ["-"]
                                    then vargs
                                    else defaultPoly:vargs
                          -- grouped args
                          gargs = (sargs ++)
                                  . toLast (++trail)
                                  . groupBy (\_ s-> take 1 s /= "-")
                                  $ args'
                          appendArgs k xs opt =
                            if k `elem` argspec
                              then Just . maybe xs (++xs) $ opt
                              else error . unlines $ [ "unrecognized option "++k
                                                     , "Use --help for usage." ]

parseCommonArgs :: (Ord k, IsString k) =>
                   Map.Map k [[Char]] -> CommonArgsParsed
parseCommonArgs margs = CommonArgsParsed
    { cap_homespec = homespec
    , cap_passfd   = passfd
    , cap_fpstyle  = style }
    where
        passphrase_fd = concat <$> Map.lookup "--passphrase-fd" margs
        homespec = join . take 1 <$> Map.lookup "--homedir" margs
        style = maybe FingerprintAuto read $ join . take 1 <$> Map.lookup "--fingerprint" margs
        passfd = fmap (FileDesc . read) passphrase_fd

parseKeySpecs :: [String] -> [Maybe (String,String,String)]
parseKeySpecs = map $ \specfile -> do
    let (spec,efilecmd) = break (=='=') specfile
    guard $ take 1 efilecmd=="="
    let filecmd = drop 1 efilecmd
    let (file,bcmdb0) = break (=='{') filecmd
        bcmdb = if null bcmdb0 then "{}" else bcmdb0
    guard $ take 1 bcmdb=="{"
    let bdmcb = (dropWhile isSpace . reverse) bcmdb
    guard $ take 1 bdmcb == "}"
    let cmd = (drop 1 . reverse . drop 1) bdmcb
    Just (spec,file,cmd)

data Export = Export | NoExport deriving Eq
data Import = Import | NoImport deriving Eq
data Secret = Secret | NoSecret deriving Eq
-- Flag-specific options
--  bSecret: --pems and --wallets
--  bImport: --import and --import-if-authentic
sync :: Export -> Import -> Secret -> String -> [String] -> IO ()
sync bExport bImport bSecret cmdarg args_raw = do
    let (sargs,margs) = processArgs sargspec polyVariadicArgs "--pems" args_raw
        sargspec = [ ("--show-wk",0)
                   , ("--autosign",0)
                   {-, ("--show-all",0)
                   , ("--show-whose-key",0)
                   , ("--show-key",1)
                   , ("--show-pem",1)
                   , ("--show-ssh",1)
                   , ("--show-wip",1) -}
                   ]
                   ++ do guard (bImport == Import)
                         [ ("--import",0), ("--import-if-authentic",0) ]
        polyVariadicArgs = ["--keyrings"
                           ,"--hosts"
                           ,"--pems"]
                           ++ do guard (bSecret == Secret)
                                 [ "--wallets" ]
    -- putStrLn $ "margs = " ++ show (Map.assocs margs)
    unkeysRef <- newIORef Map.empty
    pwRef <- newIORef Nothing
    let keypairs0 = parseKeySpecs specs -- [Maybe (usage,path,cmd)]
        specs     = fromMaybe [] $ Map.lookup "--pems" margs
        keyrings_ = fromMaybe [] $ Map.lookup "--keyrings" margs
        wallets   = fromMaybe [] $ Map.lookup "--wallets" margs
        passphrase_fd = concat <$> Map.lookup "--passphrase-fd" margs

    -- Report first encountered error in Specs
    forM_ (take 1 $ filter (isNothing . fst)
                  $ zip keypairs0 specs      ) $ \(_,badspec) -> do
        warn $ "Syntax error in key pair specification " ++ show badspec
        exitFailure

    input_key <- maybe (return Nothing)
                       (const $ fmap (Just . readPublicKey) Char8.getContents)
                    $ Map.lookup "--show-whose-key" margs
    moreSync keypairs0 margs passphrase_fd bExport bImport bSecret cmdarg keyrings_ wallets sargs

moreSync :: [Maybe (String, String, String)] -> Map.Map String [FilePath] -> Maybe String -> Export -> Import -> Secret
  -> String -> [FilePath] -> [FilePath] -> [[String]] -> IO ()
moreSync keypairs0 margs passphrase_fd bExport bImport bSecret cmdarg keyrings_ wallets sargs = do
    let keypairs = catMaybes keypairs0
        homespec = join . take 1 <$> Map.lookup "--homedir" margs
        style = fromMaybe FingerprintAuto $ do
            fs <- Map.lookup "--fingerprint" margs
            readMaybe $ concat $ take 1 fs
        passfd = fmap (FileDesc . read) passphrase_fd
        -- reftyp is used as value for 'fill field' in StreamInfo, walts and rings
        reftyp | bExport == Export = KF_Subkeys -- export to rings when they have master present
               | otherwise = KF_None -- export nothing

        pems = flip map keypairs
                $ \(usage,path,cmd) ->
                    let cmd' = mfilter (not . null) (Just cmd)
                    in if bExport == Export
                        then (ArgFile path, StreamInfo { fill = KF_Match usage
                                                       , spill = KF_Match usage
                                                       , typ = if "dns-" `isPrefixOf` usage
                                                                    then DNSPresentation
                                                                    else PEMFile
                                                       , access = if (bSecret == Secret) then Sec else Pub
                                                       , initializer = maybe NoCreate External cmd'
                                                       , transforms = []
                                                       } )
                        else if isNothing cmd'
                                then ( ArgFile path
                                     , (buildStreamInfo KF_None PEMFile)
                                        { spill = KF_Match usage })
                                else error "Unexpected PEM file initializer."
        walts = map (\fname -> ( ArgFile fname , (buildStreamInfo reftyp WalletFile) { access = Sec })) wallets
        rings = map (\fname -> ( ArgFile fname , buildStreamInfo reftyp KeyRingFile )) keyrings_
        hosts = maybe [] (map decorate) $ Map.lookup "--hosts" margs
                    where decorate fname = (ArgFile fname, buildStreamInfo reftyp Hosts)
        pubfill = maybe KF_Subkeys id   -- Note: --import overrides --import-if-authentic
                        $ mplus import_f importifauth_f
            where
                import_f       = fmap (const KF_All) $ Map.lookup "--import" margs
                importifauth_f = fmap (const KF_Authentic) $ Map.lookup "--import-if-authentic" margs
        kikiOp = KeyRingOperation
            { opFiles = Map.fromList $
                [ ( HomeSec, buildStreamInfo (if (bSecret == Secret) && (bImport == Import) then KF_All
                                                                    else KF_None)
                                             KeyRingFile )
                , ( HomePub, buildStreamInfo (if (bImport == Import) then pubfill
                                                         else KF_None)
                                             KeyRingFile )
                ]
                ++ rings
                ++ pems
                ++ if (bSecret == Secret) then walts else []
                ++ hosts
            , opPassphrases = withAgent $ do pfile <- maybeToList passfd
                                             return $ PassphraseSpec Nothing Nothing pfile
            , opTransforms = maybe [] (const [Autosign]) $ Map.lookup "--autosign" margs
            , opHome = homespec
            }
    let usage f = maybe f (const $ kiki_usage bExport bImport bSecret cmdarg) $ Map.lookup "--help" margs
    usage $ moreMoreSync style kikiOp sargs

moreMoreSync :: FingerprintStyle -> KeyRingOperation -> [[String]] -> IO ()
moreMoreSync style kikiOp sargs = do
    KikiResult rt report <- runKeyRing kikiOp

    case rt of
      KikiSuccess rt -> do -- interpret --show-* commands.
            let grip = rtGrip rt
            let shspec = Map.fromList [("--show-wk", const $ show_wk style (rtSecring rt) grip)
                                      {-,("--show-all",const show_all)
                                      ,("--show-whose-key", const $ show_whose_key input_key)
                                      ,("--show-key",\[x] -> show_id x $ fromMaybe "" grip)
                                      ,("--show-pem",\[x] -> show_pem x $ fromMaybe "" grip)
                                      ,("--show-ssh",\[x] -> show_ssh x $ fromMaybe "" grip)
                                      ,("--show-wip",\[x] -> show_wip x $ fromMaybe "" grip)-}
                                      ]
                shargs = mapMaybe (\(x:xs) -> (,xs) <$> Map.lookup x shspec) sargs

            forM_ shargs $ \(cmd,args) -> cmd args (rtKeyDB rt)
      err -> putStrLn $ errorString err

    forM_ report $ \(fname,act) -> do
        putStrLn $ fname ++ ": " ++ reportString act


doTransform :: [String] -> ([String]->[Transform]) -> IO ()
doTransform args mktrans = do
    let (_,margs) = processArgs sargspec polyVariadicArgs "---" args
            where sargspec = []
                  polyVariadicArgs = ["---"]
        passfd = fmap (FileDesc . read) passphrase_fd
            where passphrase_fd = concat <$> Map.lookup "--passphrase-fd" margs
        targs = fromMaybe [] $ Map.lookup "---" margs
        homespec = join . take 1 <$> Map.lookup "--homedir" margs
        ts = mktrans targs
        kikiOp = KeyRingOperation
            { opFiles = Map.fromList $
                [ ( HomeSec, buildStreamInfo KF_All KeyRingFile )
                , ( HomePub, buildStreamInfo KF_All KeyRingFile )
                ]
            , opPassphrases = withAgent $ do pfile <- maybeToList passfd
                                             return $ PassphraseSpec Nothing Nothing pfile
            , opTransforms = ts
            , opHome = homespec
            }
    KikiResult rt report <- if null ts then return $ KikiResult OperationCanceled []
                                       else runKeyRing kikiOp
    forM_ report $ \(fname,act) -> do
        putStrLn $ fname ++ ": " ++ reportString act
    case rt of
      KikiSuccess _ -> return ()
      err -> putStrLn $ errorString err

kiki :: String -> [String] -> IO ()
kiki "sync-secret" args_raw   = sync Export Import Secret "sync-secret" args_raw
kiki "sync-public" args_raw   = sync Export Import NoSecret "sync-public" args_raw
kiki "import-secret" args_raw = sync NoExport Import Secret "import-secret" args_raw
kiki "import-public" args_raw = sync NoExport Import NoSecret "import-public" args_raw
kiki "export-secret" args_raw = sync Export NoImport Secret "export-secret" args_raw
kiki "export-public" args_raw = sync Export Import NoSecret "export-public" args_raw

-- Generic help
kiki "help" [] = do
    putStrLn "Valid commands are:"
    let longest = maximum $ map (length . fst) commands
        pad cmd = take (longest+3) $ cmd ++ repeat ' '
    forM commands $ \(cmd,help) -> do
        putStrLn $ "   " ++ pad cmd ++ help
    putStr . unlines $ [""
                       ,"See 'kiki help <command>' for more information on a specific command."
                       ,"Or see 'kiki help spec' for kiki's notation for specifying keys."
                       ]
    return ()

kiki "help" args = forM_ args $ \arg -> case lookup arg commands of
    Nothing | arg == "spec" -> kiki_usage NoExport NoImport NoSecret arg
    Nothing | arg == "SPEC" -> kiki_usage NoExport NoImport NoSecret arg
    Nothing -> putStrLn $ "No help available for commmand '" ++ arg ++ "'."
    _       -> kiki arg ["--help"]

kiki "show" args = do
    let (sargs0,margs) = processArgs sargspec polyVariadicArgs "--show" args
        notCommon xss = concat (take 1 xss) `notElem` map fst commonArgSpec
        sargs = case filter notCommon sargs0 of
            [] -> ["--working"] : sargs0
            _  -> sargs0
        sargspec = [ ("--working",0) --("--show-wk",0)
                   , ("--dump",0)     --("--show-all",0)
                   , ("--all",0)     --("--show-all",0)
                   , ("--whose-key",0)
                   , ("--packets",1)
                   , ("--key",1)
                   , ("--pem",1)
                   , ("--dns",1)
                   , ("--ssh",1)
                   , ("--sshfp",1)
                   , ("--wip",1)
                   , ("--cert",1)
                   , ("--torhash",1)
                   ]
        polyVariadicArgs = ["--show"]
    let cap = parseCommonArgs margs
        homespec = cap_homespec cap
        passfd = cap_passfd cap
        pems = []
        rings = []
        hosts = []
        walts = []
        streaminfo = StreamInfo { fill = KF_None
                                , typ = KeyRingFile
                                , spill = KF_All
                                , initializer = NoCreate
                                , access = AutoAccess
                                , transforms = []
                                }
        kikiOp = KeyRingOperation
            { opFiles = Map.fromList $
                [ ( HomeSec, streaminfo { access = Sec })
                , ( HomePub, streaminfo { access = Pub })
                ]
                ++ rings
                ++ pems
                ++ walts
                ++ hosts
            , opPassphrases = withAgent $ do pfile <- maybeToList passfd
                                             return $ PassphraseSpec Nothing Nothing pfile
            , opTransforms = []
            , opHome = homespec
            }

    (\f -> maybe f (const $ kiki_usage NoExport NoImport NoSecret "show") $ Map.lookup "--help" margs) $ do
    KikiResult rt report <- runKeyRing kikiOp

    input_key <- maybe (return Nothing)
                       (const $ fmap (Just . readPublicKey) Char8.getContents)
                    $ Map.lookup "--whose-key" margs

    case rt of
      KikiSuccess rt -> do -- interpret --show-* commands.
            let grip = rtGrip rt
            let shspec = Map.fromList [("--working", const $ show_wk (cap_fpstyle cap) (rtSecring rt) grip)
                                      ,("--all",const (show_all (cap_fpstyle cap)))
                                      ,("--whose-key", const $ show_whose_key input_key)
                                      ,("--packets", show_packets)
                                      ,("--key",\[x] -> show_id (cap_fpstyle cap) x $ fromMaybe "" grip)
                                      ,("--pem",\[x] -> show_pem x $ fromMaybe "" grip)
                                      ,("--dns",\[x] -> show_dns x $ fromMaybe "" grip)
                                      ,("--ssh",\[x] -> show_ssh x $ fromMaybe "" grip)
                                      ,("--sshfp",\[x] -> show_sshfp x $ fromMaybe "" grip)
                                      ,("--wip",\[x] -> show_wip x $ fromMaybe "" grip)
                                      ,("--cert",\[x] -> show_cert x $ fromMaybe "" grip)
                                      ,("--torhash",\[x] -> show_torhash x)
                                      ,("--dump", const $ debug_dump (rtSecring rt) grip)
                                      ]
                shargs = mapMaybe (\(x:xs) -> (,xs) <$> Map.lookup x shspec) sargs

            forM_ shargs $ \(cmd,args) -> cmd args (rtKeyDB rt)
      err -> putStrLn $ errorString err

    forM_ report $ \(fname,act) -> do
        putStrLn $ fname ++ ": " ++ reportString act

kiki "merge" [] = do
    putStr . unlines $
        [ "kiki merge [ ( --passphrase-fd=FD"
        , "             | --agent"
        , "             | --show-key=SPEC"
        , "             | --show-all"
        , "             | --packets ) ... ]"
        , "           ( --home[=HOMEDIR]"
        , "           | --type=(keyring|pem|wallet|hosts|dns)"
        , "           | --access=[auto|secret|public]"
        , "           | --flow=(fill|spill|sync)[,(subkeys|signed|match=SPEC)]"
        , "           | --create=(rsa:SIZE|cmd:CMD)"
        , "           | --autosign[=no]"
        , "           | --delete=FINGERPRINT"
        , "           | --delete-usage=TAG"
        , "           | --"
        , "           | FILE ) ..."
        , ""
        , "OPTIONS"
        , ""
        , "  --agent          Use gpg-agent."
        , ""
        , "  --show-all       After files have been written, show information for all"
        , "                   known keys."
        , ""
        , "  --show-key=SPEC  After files have been written, show information for the"
        , "                   key identified by SPEC."
        , ""
        , "  --packets        After files have been written, declare each known pkg packet."
        , ""
        , "OPERANDS"
        , ""
        , "  --home[=HOMEDIR] A symbolic operand that is a place holder for two files:"
        , "                     HOMEDIR/{secring.gpg,pubring.gpg}"
        , "                   HOMEDIR defaults to your GnuPG home directory."
        , ""
        , "  FILE             A path to a key file to read or update."
        , ""
        , "MODIFIERS"
        , ""
        , "  --type=(keyring|pem|wallet|hosts|dns)"
        , "                   The type of the following file.  Unlike other modifiers,"
        , "                   This modifier remains in effect accross multiple operands"
        , "                   unless another --type instance is seen.  The default type"
        , "                   is keyring."
        , ""
        , "  --access=[auto|secret|public]"
        , ""
        , "  --flow=(fill|spill|sync)[,(subkeys|signed|match=SPEC)]"
        , "                   If not specified, default is to spill (read and use but"
        , "                   don't write)."
        , ""
        , "  --create=(rsa:SIZE|ed25519|cv25519|cmd:CMD)"
        , "                   This should be used with a filename to export to in PEM"
        , "                   format but this is just a dummy argument if the flow is set"
        , "                   to spill."
        , ""
        , "  --autosign[=no]"
        , ""
        , "  --delete=FINGERPRINT"
        , ""
        , "  --delete-usage=TAG"
        ]
kiki "merge" args | "--help" `elem` args = do
    kiki "merge" []
    -- TODO: more help
kiki "merge" args = do
    hPutStrLn stderr $ ppShow op
    KikiResult rt report <- runKeyRing (mbAgent op)
    case rt of
      KikiSuccess rt -> do let db = rtKeyDB rt
                           if bShowAll
                            then show_all style db
                            else forM_ keyspecs $ \keyspec -> do
                                    show_id style keyspec (error "show_id wkgrip") db
                           when bPackets $ show_packets [] db
      err            -> putStrLn $ errorString err
    forM_ report $ \(fname,act) -> do
        putStrLn $ fname ++ ": " ++ reportString act
 where
    (_,((_,keyspecs),op)) = foldl' buildOp (True,((flow0,[]),noop)) args4
    (args',mbAgent) = case break (=="--agent") args of
                       (as,[])   -> (as, id)
                       (as,_:bs) -> ( as++bs
                                    , \op -> op { opPassphrases = withAgent (opPassphrases op) })
    (args'',bShowAll) = case break (=="--show-all") args' of
                       (as,[])   -> (as, False)
                       (as,_:bs) -> (as++bs, True)
    (args3,bPackets) = case break (=="--packets") args'' of
                       (as,[])   -> (as, False)
                       (as,_:bs) -> (as++bs, True)
    (args4,style) = case break (=="--fingerprint") args3 of
                       (as,b:bs) | Just s <- readMaybe b
                                 -> (as++bs, s)
                       (as,[])   -> (as, FingerprintAuto)
    noop = KeyRingOperation
            { opFiles = Map.empty
            , opTransforms = []
            , opHome = Nothing
            , opPassphrases = []
            }
    flow0 = StreamInfo
            { access = AutoAccess
            , typ = KeyRingFile
            , spill = KF_All
            , fill = KF_None
            , initializer = NoCreate
            , transforms = []
            }
    updateFlow :: Bool -> Bool -> KeyFilter -> StreamInfo -> StreamInfo
    updateFlow fil spil val flow = spill' $ fill' $ flow
     where
        fill' flow  = flow { fill  = if fil  then val else fill flow }
        spill' flow = flow { spill = if spil then val else spill flow }

    parseFlow :: String -> Maybe ((Bool,Bool),KeyFilter)
    parseFlow spec = do
        guard $ null bads
        Just ( ( "spill" `elem` goods
                || "sync" `elem` goods
               , "fill" `elem` goods
                || "sync" `elem` goods )
               , case match of
                    Just spec -> KF_Match spec
                    Nothing
                        | "signed" `elem` goods  -> KF_Authentic
                        | "subkeys" `elem` goods -> KF_Subkeys
                        | otherwise              -> KF_All)
     where
        ws = case groupBy (\_ c->c/=',') spec of
                w:xs -> w:map (drop 1) xs
                []   -> []
        (goods,bads) = partition acceptable ws
        acceptable :: String -> Bool
        acceptable "spill"   = True
        acceptable "fill"    = True
        acceptable "sync"    = True
        acceptable "signed"  = True
        acceptable "subkeys" = True
        acceptable s | "match=" `isPrefixOf` s = True
        acceptable _ = False
        match = listToMaybe $ do
            m <- filter ("match=" `isPrefixOf`) goods
            return $ drop 6 m

    doFile :: (StreamInfo,[String]) -> KeyRingOperation
                                    -> FilePath
                                    -> ((StreamInfo,[String]),KeyRingOperation)
    doFile (flow,specs) op fname =
        ( (,) flow0 { typ = typ flow } specs -- everything resets except for --type
        , op { opFiles= Map.insert (ArgFile fname) flow (opFiles op) })

    doDelete :: String -> (StreamInfo,[String]) -> KeyRingOperation -> ((StreamInfo,[String]),KeyRingOperation)
    doDelete fp flow op = ( flow
                          , op { opTransforms = opTransforms op ++ [DeleteSubkeyByFingerprint fp] } )

    doDeleteUsage :: String -> (StreamInfo,[String])
                            -> KeyRingOperation
                            -> ((StreamInfo,[String]),KeyRingOperation)
    doDeleteUsage tag flow op = ( flow
                                , op { opTransforms = opTransforms op ++ [DeleteSubkeyByUsage tag] } )

    doAutosign :: Bool -> (StreamInfo,[String])
                       -> KeyRingOperation
                       -> ((StreamInfo,[String]),KeyRingOperation)
    doAutosign True (flow,specs) op =
        if Map.null (opFiles op)
            then ((,) flow specs, op { opTransforms = opTransforms op ++ [Autosign] })
            else ((,) flow { transforms = transforms flow ++ [Autosign] } specs, op)
    doAutosign False (flow,specs) op =
        ( (,) flow { transforms = filter (/=Autosign) (transforms flow) } specs
        , op { opTransforms = filter (/=Autosign) (opTransforms op) } )

    doPassphrase :: (StreamInfo,[String]) -> KeyRingOperation
                                          -> String
                                          -> ((StreamInfo,[String]),KeyRingOperation)
    doPassphrase flow op pass =
        if Map.null (opFiles op)
            then ( flow
                 , op { opPassphrases = PassphraseSpec Nothing Nothing pfd
                                        : opPassphrases op } )
            else error "passphrase-fd must come before any file arguments or --home"
     where
        pfd = FileDesc (read pass)

    buildOp :: (Bool,((StreamInfo,[String]),KeyRingOperation))
                -> String
                -> (Bool,((StreamInfo,[String]),KeyRingOperation))
    buildOp (False,(flow,op)) fname = (False,doFile flow op fname)
    buildOp (True,(flow@(si,specs),op)) arg@(splitArg->parsed) =
        case parsed of
            Left ("",Nothing) -> (False,(flow,op))
            _ -> (True,) dispatch
     where
      dispatch =
        case parsed of
            Right fname -> doFile flow op fname
            Left ("delete",Just fp)       -> doDelete fp flow op
            Left ("delete-usage",Just tag) -> doDeleteUsage tag flow op
            Left ("autosign",Nothing)     -> doAutosign True  flow op
            Left ("autosign",Just "y")    -> doAutosign True  flow op
            Left ("autosign",Just "yes")  -> doAutosign True  flow op
            Left ("autosign",Just "true") -> doAutosign True  flow op
            Left ("autosign",Just "n")    -> doAutosign False flow op
            Left ("autosign",Just "no")   -> doAutosign False flow op
            Left ("autosign",Just "false")-> doAutosign False flow op
            Left ("passphrase-fd",Just pass) -> doPassphrase flow op pass
            Left ("create",Nothing) ->
                ( (,) si { initializer = Internal (GenRSA (4096 `div` 8)) } specs
                , op )
            Left ("create",Just cmd)
                | "cmd:" `isPrefixOf` cmd
                 -> ( (,) si { initializer = case drop 4 cmd of
                                            []     -> NoCreate
                                            extern -> External extern } specs
                    , op )
            Left ("create",Just cmd)
                | "rsa:" `isPrefixOf` cmd
                 -> ( (,) si { initializer = case drop 4 cmd of
                                    []   -> NoCreate
                                    bits ->
                                        case takeWhile isDigit bits of
                                            []     -> NoCreate
                                            digits -> Internal (GenRSA (read digits `div` 8)) }
                          specs
                    , op )
            Left ("create",Just "ed25519")
                 -> ( (si { initializer = Internal GenEd25519 }, specs)
                    , op )
            Left ("create",Just "cv25519")
                 -> ( (si { initializer = Internal GenCv25519 }, specs)
                    , op )
            Left ("type",Just "keyring") -> ( (,) si { typ = KeyRingFile     } specs, op )
            Left ("type",Just "pem"    ) -> ( (,) si { typ = PEMFile         } specs, op )
            Left ("type",Just "wallet" ) -> ( (,) si { typ = WalletFile      } specs, op )
            Left ("type",Just "hosts"  ) -> ( (,) si { typ = Hosts           } specs, op )
            Left ("type",Just "dns"  )   -> ( (,) si { typ = DNSPresentation } specs, op )
            Left ("access",Just "public") -> ( (,) si { access = Pub } specs, op )
            Left ("access",Just "secret") -> ( (,) si { access = Sec } specs, op )
            Left ("access",Just "auto")   -> ( (,) si { access = AutoAccess } specs, op )
            Left ("home",mb) ->
                ( flow
                , op { opFiles = Map.insert HomePub (si { typ=KeyRingFile
                                                        , access=Pub })
                                 $ Map.insert HomeSec (si { typ=KeyRingFile
                                                          , access=Sec })
                                 $ opFiles op
                     , opHome = opHome op `mplus` mb
                     }
                )
            Left ("flow",Just flowspec) ->
                case parseFlow flowspec of
                    Just ( (spil,fil), mtch ) ->
                        ( (,) (updateFlow fil spil mtch si) specs
                        , op )
                    Nothing -> error "Valid flow words are: spill,fill,sync,signed,subkeys or match=KEYSPEC"
            Left ("show-key",Just keyspec) -> ( (,) si (keyspec:specs)
                                              , op )
            Left (option,_) -> error $ "Unrecognized option: " ++ option

kiki "init" args | "--help" `elem` args = do
    putStr . unlines $
        [ "kiki init [ --passphrase-fd=FD"
        , "          | --homedir[=HOMEDIR]"
        , "          | --chroot=ROOTDIR"
        , "          | --cipher="++intercalate "|" (map ciphername ciphers)
        , "          | -(4|5) ] ..."
        , ""
        , "Modify your GnuPG keyring and update /var/cache/kiki.  The following"
        , "changes will occur to the keyring:"
        , ""
        , "          master-key (generated if not present)"
        , "          tor        (generated if not prsenet)"
        , "          ipsec      (generated if not prsenet)"
        , "          ssh-server (imported or generated if not present)"
        , "          ssh-client (imported or gnnerated if not present)"
        , ""
        , "OPTIONS"
        , ""
        , "     --chroot=ROOTDIR"
        , "                Use ROOTDIR for input of ssh keys and export files to"
        , "                ROOTDIR/var/cache/kiki instead of the current system path."
        , "                When this option is specified, the GNUPGHOME environment"
        , "                variable is ignored and you must use --homedir to specify"
        , "                a value other than /root/.gnupg."
        , ""
        , "     -4"
        , "                New PGP key packets should use the v4 (default) format."
        , ""
        , "     -5"
        , "                New PGP key packets should use the v5 format and use the"
        , "                SHA256-based v5 fingerprints."
        , ""
        ] ++ documentHomeDir ++ [""] ++ documentPassphraseFDFlag True True True

kiki "init" args = run args $ importAndRefresh <$> dashdashPGPVersion <*> dashdashChroot <*> dashdashHomedir <*> dashdashCipher
kiki "spawn" args | "--help" `elem` args =
    putStr . unlines $
        [ "kiki spawn [ --passphrase-fd=FD"
        , "           | --homedir[=HOMEDIR]"
        , "           | --cipher="++intercalate "|" (map ciphername ciphers)++" ]"
        , "           <PATH>"
        ]
kiki "spawn" args = run args $ spawn <$> dashdashHomedir <*> dashdashCipher <*> param 0

kiki "delete" args | "--help" `elem` args = do
    putStr . unlines $
        [ "kiki delete <fingerprint> ..."
        , ""
        , "  Delete the subkeys specified by the given fingerprints along"
        , "  with all associated signatures and trust markers."
        ]
    return ()
kiki "delete" args = doTransform args delete
 where delete fps = map DeleteSubkeyByFingerprint fps

kiki "rename" args | "--help" `elem` args = do
    putStr . unlines $
        [ "kiki rename [--homedir <home>] [--passphrase-fd <fd>] <old-tag> <new-tag>"
        , ""
        , "  Reassigns a key usage tag from old-tag to new-tag."
        , "  The old signature will be replaced and a new one formed."
        ]
    return ()

kiki "rename" args = doTransform args rename
 where rename (oldtag:newtag:_) = [ RenameSubkeys oldtag newtag ]
       rename _                 = []

kiki "tar" args | "--help" `elem` args = do
    putStr . unlines $
        [ "kiki tar (-c|-t) [--secrets SPEC] [--passphrase-fd FD] [--homedir HOMEDIR]"
        , ""
        , "Import or export a tar archive containing key files in the proper"
        , "format for software configuration."
        , ""
        ,"    -c  Generate tar archive on stdout."
        ,""
        ,"    -t  List filepaths that would be included in the (-c) output archive."
        ,""
        ,"    --secrets SPEC"
        ,"        Include secret keys for the specified identity."
        ,"        Otherwise, only public keys are included."
        ,""
        ,"        SPEC is matched against the following forms in order:"
        ,""
        ,"          -"
        ,"           (current working identity)"
        ,""
        ,"          fp:4A39F"
        ,"            (tail end of a v4 fingerprint or the front end of a v5"
        ,"            fingerprint prefixed by 'fp:')"
        ,""
        ,"          u:joe"
        ,"            (sub-string of a user id prefixed by 'u:')"
        ,""
        ,"          5E24CD442AA6965D2012E62A905C24185D5379C2"
        ,"            (fingerprint as 40 characters of hexidecimal)"
        ,""
        ,"          joe"
        ,"            (sub-string of a user id without 'u:' prefix)"
        ]

kiki "verify" args | "--help" `elem` args = do
    putStr . unlines $
        [ "kiki verify [--homedir HOMEDIR | --homeless] [[--keyring FILE] ...] FILE"
        ]
kiki "verify" argvals =
    let opts = [("--homedir",1),("--keyring",1),("--homeless",0)]
    in case runArgs (parseInvocation (fancy opts [] "") argvals)
                    (verifyFile <$> flag "--homeless"
                                <*> dashdashHomedir
                                <*> args "--keyring"
                                <*> param 0) of
        Left er  -> hPutStrLn stderr $ usageErrorMessage er
        Right io -> io

kiki "sign" args | "--help" `elem` args = do
    putStr . unlines $
        [ "kiki sign [--homedir HOMEDIR | --homeless] [[--keyring FILE] ...] --with-key KEYID FILE"
        ]
kiki "sign" argvals =
    let opts = [("--homedir",1),("--keyring",1),("--homeless",0),("--with-key",1)]
    in case runArgs (parseInvocation (fancy opts [] "") argvals)
                    (signFile <$> flag "--homeless"
                                <*> dashdashHomedir
                                <*> args "--keyring"
                                <*> arg "--with-key"
                                <*> param 0) of
        Left er  -> hPutStrLn stderr $ usageErrorMessage er
        Right io -> io

kiki cmd args = hPutStrLn stderr $ "I don't know how to "++cmd++"."

sshkeyname :: Packet -> [FilePath]
sshkeyname SecretKeyPacket { key_algorithm = RSA } = ["id_rsa"]
sshkeyname _ = []

-- |
--
-- no leading hyphen, returns Right (input string).
--
-- single leading hyphen, quits program with "Unrecognized option" error
--
-- Otherwise, Left (key-value pair) is returned by parsing
-- a string of the form --key=value.
splitArg :: String -> Either (String,Maybe String) String
splitArg arg =
    case hyphens of
        ""  -> Right name
        "-" -> error $ "Unrecognized option: " ++ arg
        _   -> Left $ parseLongOption name
 where
    (hyphens, name) = span (=='-') arg
    parseLongOption name = (key,val v)
     where
        (key,v) = break (=='=') name
        val ('=':vs) = Just vs
        val _        = Nothing

commands :: [(String,String)]
commands =
 [ ( "help", "display usage information" )
 --, ( "sync", "update key files of various kinds by propogating information" )
 , ( "show", "display information from your keyrings")
 , ( "sync-secret", "update key files of various kinds by propogating information (both secret and public)" )
 , ( "sync-public", "update key files of various kinds by propogating public information" )
 , ( "import-secret", "import (both public and secret) information into your keyring" )
 , ( "import-public", "import (public) information into your keyring" )
 , ( "export-secret", "export (both public and secret) information into your keyring" )
 , ( "export-public", "import (public) information into your keyring" )
 , ( "merge", "low level import/export operation" )
 -- , ( "init-key", "initialize the samizdat key ring")
 , ( "init", "Initialize kiki")
 , ( "spawn", "Initialize a new, pre-authenticated, key set for use by another person.")
 , ( "delete", "Delete a subkey and its associated signatures" )
 , ( "rename", "Change the usage tag on a specified subkey" )
 --    also repairs signature and adds missing cross-certification.
 , ( "tar", "import or export system key files in tar format" )
 , ( "verify", "Check a clear-sign pgp signature." )
 , ( "sign", "Create a detached signature for a given file.")
 ]

main :: IO ()
main = do
    dotlock_init
    args_raw0 <- getArgs
    args_raw <- case break (=="--trace-verify") args_raw0 of
                  (as,[]) -> return as
                  (as,_:bs) -> do setVerifyFlag True
                                  return $ as ++ bs
    case args_raw of

        []        -> kiki "show" args_raw

        ["--help"] -> do
            putStrLn "Showing help for the default \"show\" command."
            putStrLn "Use \"help\" without leading hyphens to see other available commands."
            putStrLn "\n"
            kiki "show" args_raw
        ('-':_):_ -> kiki "show" args_raw

        cmd : args | cmd `elem` map fst commands
          -> kiki cmd args

        _ -> kiki "help" [] --args_raw