aboutsummaryrefslogtreecommitdiff
path: root/firma
blob: 8dd34c3e7aaae67b1640729619dc1aa69cc871aa (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
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
#!/bin/bash
#
# firma: GnuPG-based encrypted mailing list manager
# Feedback: firma@sarava.org
#
#  Firma is free software; you can redistribute it and/or modify it under the
#  terms of the GNU General Public License as published by the Free Software
#  Foundation; either version 2 of the License, or (at your option) any later
#  version.
#
#  Firma is distributed in the hope that it will be useful, but WITHOUT ANY
#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with
#  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
#  Place - Suite 330, Boston, MA 02111-1307, USA
#

function Usage {
  #-------------------------------------------------------------
  # display help
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  # this will be printed to STDOUT, so no indentation here
  echo "\
Usage: $BASENAME OPTION [LIST-NAME]
GnuPG-based encrypted mailing list manager.

  -a, --admin-task LIST-NAME        process administrative tasks on list
  -c, --create-newlist LIST-NAME    create a new mailing list
  -e, --email-admin-task LIST-NAME  process administrative tasks via email
  -h, --help                        display help and exit
  -p, --process-message LIST-NAME   process a message sent to list
  -v, --version                     output version information and exit

If option -a is given, read standard input for tasks to be performed.
Tasks can be one or more of the following:
$(AdminHelp)

For help with admin and config paramaters, type $BASENAME --help task-name

Report bugs to <firma@firma.sarava.org>, encrypting your message using the
public key 3DF104314023E18358EFDD270D51B4E79E693CF7, available at keys.indymedia.org."
}


function Version {
  #-------------------------------------------------------------
  # display version information
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  # this will be printed to STDOUT, so no indentation here
  echo "\
firma $VERSION

Copyright (C) 2005-2007 A Firma
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the GNU General Public License
for more details."
}


function DeclareGpgVars {
  #-------------------------------------------------------------
  # declare gpg-related global variables
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  GPG_FLAGS="--no-options --no-default-keyring --homedir $LIST_HOMEDIR --quiet --no-tty --batch --no-use-agent --no-permission-warning"
  GPG_FLAGS_NO_BATCH="--no-options --no-default-keyring --homedir $LIST_HOMEDIR --quiet --no-batch --no-use-agent --no-permission-warning"
  GPG="$GPG_BINARY $GPG_FLAGS"
  GPG_NOBATCH="$GPG_BINARY $GPG_FLAGS_NO_BATCH"
  GPG_LIST_KEYS="$GPG --list-keys --with-colons"
  GPG_DECRYPT="$GPG --passphrase-fd 0 --decrypt"
  GPG_ENCRYPT="$GPG --armor --trust-model always --local-user $LIST_ADDRESS --passphrase-fd 0 --no-emit-version --sign --encrypt"
}


function CheckPassphrase {
  #-------------------------------------------------------------
  # check if a passphrase is valid: is 25 characters long or more;
  #+includes lower and upper case letters, numbers and at least 1
  #+punctuation character; and no character is sequentially
  #+repeated more than 4 times.
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 if passphrase is valid,
  #          1 if invalid
  #-------------------------------------------------------------

  local -i return_code=0

  if [[ -z "$PASSPHRASE" || \
       "$(echo "$PASSPHRASE" | wc -c)" -lt "25" || \
       -z "$(echo "$PASSPHRASE" | tr -dc '[:lower:]')" || \
       -z "$(echo "$PASSPHRASE" | tr -dc '[:upper:]')" || \
       -z "$(echo "$PASSPHRASE" | tr -dc '[:digit:]')" || \
       "$(echo "$PASSPHRASE" | tr -dc '[:punct:]' | wc -c)" -lt "1" || \
       -n "$(echo "$PASSPHRASE" | fold -w1 | uniq -cd | grep -v '^ \{6\}[234] ')"
     ]]; then
    return_code=1
  fi

  return $return_code
}


function CheckFirmaConfigFile {
  #-------------------------------------------------------------
  # check firma.conf parameters
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 if all checks are passed,
  #          1 on any fatal errors
  #-------------------------------------------------------------

  local -i return_code=0
  local gpg_version

  # check LOG_TO_SYSLOG value first, since it will define if firma
  #+should print or log error messages
  if [[ -n "$LOG_TO_SYSLOG" && \
        "$LOG_TO_SYSLOG" != "0" && \
        "$LOG_TO_SYSLOG" != "1"
     ]]; then

    LOG_TO_SYSLOG="0"
    LogMessage "\
WARNING: LOG_TO_SYSLOG should be set either to '0' or '1'.
WARNING: Setting LOG_TO_SYSLOG to '0' for this run."

  elif [[ -z "$LOG_TO_SYSLOG" ]]; then
    LOG_TO_SYSLOG="0"
  elif [[ "$LOG_TO_SYSLOG" == "1" ]]; then

    if [[ ! -f "$LOGGER_BINARY" || ! -x "$LOGGER_BINARY" ]]; then

      LOG_TO_SYSLOG="0"
      LogMessage "\
WARNING: Logger binary ($LOGGER_BINARY) could not be found.
WARNING: Setting LOG_TO_SYSLOG to '0' for this run."

    else # SYSLOG_PRIORITY defaults to "user.err"
      SYSLOG_PRIORITY=${SYSLOG_PRIORITY:-"user.err"}
    fi

  fi

  # check GPG_BINARY value
  if [[ ! -f "$GPG_BINARY" || ! -x "$GPG_BINARY" ]]; then
    LogMessage "FATAL: GPG binary ($GPG_BINARY) could not be found. Quitting."
    return_code=1

  # check MAIL_AGENT value
  elif [[ ! -f "$MAIL_AGENT" || ! -x "$MAIL_AGENT" ]]; then
    LogMessage "FATAL: Mail transport agent binary ($MAIL_AGENT) could not be found. Quitting."
    return_code=1

  # check LISTS_DIR value
  elif [[ ! -d "$LISTS_DIR" ]]; then
    LogMessage "FATAL: Lists directory ($LISTS_DIR) could not be found. Quitting."
    return_code=1

  # optional parameters
  else

    # check USE_GPG_HIDDEN_RECIPIENT_OPTION value
    if [[ -n "$USE_GPG_HIDDEN_RECIPIENT_OPTION" && \
          "$USE_GPG_HIDDEN_RECIPIENT_OPTION" != "0" && \
          "$USE_GPG_HIDDEN_RECIPIENT_OPTION" != "1"
       ]]; then

      LogMessage "\
WARNING: USE_GPG_HIDDEN_RECIPIENT_OPTION should be set either to '0' or '1'.
WARNING: Setting USE_GPG_HIDDEN_RECIPIENT_OPTION to '0' for this run."
      USE_GPG_HIDDEN_RECIPIENT_OPTION="0"

    elif [[ -z "$USE_GPG_HIDDEN_RECIPIENT_OPTION" ]]; then
      USE_GPG_HIDDEN_RECIPIENT_OPTION="0"
    elif [[ "$USE_GPG_HIDDEN_RECIPIENT_OPTION" == "1" ]]; then

      gpg_version="$($GPG_BINARY --version | head -n 1 | tr -dc '[:digit:]')"
      if [[ "$gpg_version" -lt "140" ]]; then

        LogMessage "\
WARNING: GPG's \"--hidden-recipient\" option is only available from version 1.4.0 onwards.
WARNING: Setting USE_GPG_HIDDEN_RECIPIENT_OPTION to '0' for this run."
        USE_GPG_HIDDEN_RECIPIENT_OPTION="0"

      fi

    fi

    # check FIRMA_USER value
    if [[ -z "$(echo "$FIRMA_USER" | tr -d '[:space:]')" ]]; then
      FIRMA_USER="nobody"
    fi

    # check FIRMA_GROUP value
    if [[ -z "$(echo "$FIRMA_GROUP" | tr -d '[:space:]')" ]]; then
      FIRMA_GROUP="nobody"
    fi

    # check KEYSERVER value
    if [[ -z "$(echo "$KEYSERVER" | tr -d '[:space:]')" ]]; then
      KEYSERVER="keys.indymedia.org"
    fi

  fi

  return $return_code
}


function CheckListConfigFile {
  #-------------------------------------------------------------
  # check list configuration file parameters
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars
  # returns: 0 if all checks are passed,
  #          1 on any fatal errors
  #-------------------------------------------------------------

  local -i return_code=0
  local administrator
  local valid_admins
  local replay_default_file="/var/log/firma/replay.db"

  # check LIST_HOMEDIR value
  if [[ ! -d "$LIST_HOMEDIR" || \
        ! -f "$LIST_HOMEDIR/pubring.gpg" || \
        ! -f "$LIST_HOMEDIR/secring.gpg"
     ]]; then
    LogMessage "FATAL: $LIST_NAME: GPG home directory ($LIST_HOMEDIR) or the GPG keyrings could not be found. Quitting."
    return_code=1

  # check PASSPHRASE value
  elif [[ -z "$(grep -o "^PASSPHRASE='[^']*'$" $LIST_CONFIG_FILE)" ]] || \
          ! CheckPassphrase; then
    LogMessage "FATAL: $LIST_NAME: List passphrase is empty or does not meet the minimum complexity requirements. Quitting."
    return_code=1

  # check LIST_ADDRESS value, confirming if the list private key is present
  elif [[ -z "$($GPG --list-secret-keys --with-colons --fixed-list-mode "<$LIST_ADDRESS>" 2> /dev/null)" ]]; then
    LogMessage "FATAL: $LIST_NAME: List's secret key could not be found. Quitting."
    return_code=1

  # optional parameters
  else

    # check if the list has an administrator (or more than one)
    if [[ -z "$(echo "$LIST_ADMIN" | tr -d '[:space:]')" ]]; then
      LogMessage "WARNING: $LIST_NAME: List has no administrator."
      LIST_ADMIN=""
    else

      # check if the public key(s) of the list administrator(s) is(are) present
      valid_admins=""
      for administrator in $LIST_ADMIN; do

        if [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$administrator>" 2> /dev/null | \
                      grep -v '^tru:')"
           ]]; then
          LogMessage "\
WARNING: $LIST_NAME: Public key for list administrator \"$administrator\" could not be found.
WARNING: $LIST_NAME: Removing this address from LIST_ADMIN for this run."
        else
          valid_admins="$valid_admins $administrator"
        fi

      done
      LIST_ADMIN="$valid_admins"

      if [[ -z "$(echo "$LIST_ADMIN" | tr -d '[:space:]')" ]]; then
        LogMessage "WARNING: $LIST_NAME: List has no valid administrator."
        LIST_ADMIN=""
      fi

    fi

    # check if LIST_REQUEST_ADDRESS has already been set
    if [[ -z "$(echo "$LIST_REQUEST_ADDRESS" | tr -d '[:space:]')" ]]; then
      LIST_REQUEST_ADDRESS="$(echo $LIST_ADDRESS | cut -d @ -f 1)-request@$(echo $LIST_ADDRESS | cut -d @ -f 2)"
    fi

    # check REQUIRE_SIGNATURE value
    if [[ -n "$REQUIRE_SIGNATURE" && \
          "$REQUIRE_SIGNATURE" != "0" && \
          "$REQUIRE_SIGNATURE" != "1"
       ]]; then

      LogMessage "\
WARNING: $LIST_NAME: REQUIRE_SIGNATURE should be set either to '0' or '1'.
WARNING: $LIST_NAME: Setting REQUIRE_SIGNATURE to '1' for this run."
      REQUIRE_SIGNATURE="1"

    elif [[ -z "$REQUIRE_SIGNATURE" ]]; then
      REQUIRE_SIGNATURE="1"
    fi

    # check REPLIES_SHOULD_GO_TO_LIST value
    if [[ -n "$REPLIES_SHOULD_GO_TO_LIST" && \
          "$REPLIES_SHOULD_GO_TO_LIST" != "0" && \
          "$REPLIES_SHOULD_GO_TO_LIST" != "1"
       ]]; then

      LogMessage "\
WARNING: $LIST_NAME: REPLIES_SHOULD_GO_TO_LIST should be set either to '0' or '1'.
WARNING: $LIST_NAME: Setting REPLIES_SHOULD_GO_TO_LIST to '0' for this run."
      REPLIES_SHOULD_GO_TO_LIST="0"

    elif [[ -z "$REPLIES_SHOULD_GO_TO_LIST" ]]; then
      REPLIES_SHOULD_GO_TO_LIST="0"
    fi

    # check HIDE_SENDER value
    if [[ -n "$HIDE_SENDER" && \
          "$HIDE_SENDER" != "0" && \
          "$HIDE_SENDER" != "1"
       ]]; then

      LogMessage "\
WARNING: $LIST_NAME: HIDE_SENDER should be set either to '0' or '1'.
WARNING: $LIST_NAME: Setting HIDE_SENDER to '0' for this run."
      HIDE_SENDER="0"

    elif [[ -z "$HIDE_SENDER" ]]; then
      HIDE_SENDER="0"
    fi

    # check REPLAY_PROTECTION value
    if [[ -n "$REPLAY_PROTECTION" && \
          "$REPLAY_PROTECTION" != "0" && \
          "$REPLAY_PROTECTION" != "1"
       ]]; then

      LogMessage "\
WARNING: $LIST_NAME: REPLAY_PROTECTION should be set either to '0' or '1'.
WARNING: $LIST_NAME: Setting REPLAY_PROTECTION to '0' for this run."
      REPLAY_PROTECTION="0"

    elif [[ -z "$REPLAY_PROTECTION" ]]; then
      REPLAY_PROTECTION="0"
    elif [[ "$REPLAY_PROTECTION" == "1" ]]; then

      # check REPLAY_COUNT value
      if [[ -n "$REPLAY_COUNT" && \
            -n "$(echo "$REPLAY_COUNT" | tr -d '[:digit:]')"
         ]]; then

        LogMessage "\
WARNING: $LIST_NAME: REPLAY_COUNT should be a number.
WARNING: $LIST_NAME: Setting REPLAY_COUNT to '150' for this run."
        REPLAY_COUNT="150"

      elif [[ -z "$REPLAY_COUNT" ]]; then
        REPLAY_COUNT="150"
      else # REPLAY_COUNT is either set to 0 (defaults to 150) or
           #+contains a valid value

        REPLAY_COUNT="$(( 10#$(echo "$REPLAY_COUNT" | tr -dc '[:digit:]') ))"
        if [[ "$REPLAY_COUNT" == "0" ]]; then

          LogMessage "\
WARNING: $LIST_NAME: REPLAY_COUNT has to be greater than '0'.
WARNING: $LIST_NAME: Setting REPLAY_COUNT to '150' for this run."
          REPLAY_COUNT="150"

        fi

      fi

      # check REPLAY_FILE value
      if [[ -z "$(echo "$REPLAY_FILE" | tr -d '[:space:]')" ]]; then
        REPLAY_FILE="$replay_default_file"
      fi

      touch "$REPLAY_FILE" 2> /dev/null
      chown "$FIRMA_USER":"$FIRMA_GROUP" "$REPLAY_FILE" 2> /dev/null
      chmod 600 "$REPLAY_FILE" 2> /dev/null

      if [[ ! -r "$REPLAY_FILE" || ! -w "$REPLAY_FILE" ]]; then

        LogMessage "\
WARNING: $LIST_NAME: REPLAY_FILE ($REPLAY_FILE) can't be read or written to.
WARNING: $LIST_NAME: Setting REPLAY_PROTECTION to '0' for this run."
        REPLAY_PROTECTION="0"

      fi

    fi

    # check DELIVERY_RANDOMIZATION value
    if [[ -n "$DELIVERY_RANDOMIZATION" && \
          -n "$(echo "$DELIVERY_RANDOMIZATION" | tr -d '[:digit:]')"
       ]]; then

      LogMessage "\
WARNING: $LIST_NAME: DELIVERY_RANDOMIZATION should be a number.
WARNING: $LIST_NAME: Setting DELIVERY_RANDOMIZATION to '0' for this run."
      DELIVERY_RANDOMIZATION="0"

    else # DELIVERY_RANDOMIZATION is either empty (defaults to 0) or
         #+contains a valid value

      DELIVERY_RANDOMIZATION="$(( 10#$(echo $DELIVERY_RANDOMIZATION | tr -dc '[:digit:]') ))"

    fi

    # check SILENTLY_DISCARD_INVALID_MESSAGES value
    if [[ -n "$SILENTLY_DISCARD_INVALID_MESSAGES" && \
          "$SILENTLY_DISCARD_INVALID_MESSAGES" != "0" && \
          "$SILENTLY_DISCARD_INVALID_MESSAGES" != "1"
       ]]; then

      LogMessage "\
WARNING: $LIST_NAME: SILENTLY_DISCARD_INVALID_MESSAGES should be set either to '0' or '1'.
WARNING: $LIST_NAME: Setting SILENTLY_DISCARD_INVALID_MESSAGES to '0' for this run."
      SILENTLY_DISCARD_INVALID_MESSAGES="0"

    elif [[ -z "$SILENTLY_DISCARD_INVALID_MESSAGES" ]]; then
      SILENTLY_DISCARD_INVALID_MESSAGES="0"
    fi

  fi

  return $return_code
}


function GetMessage {
  #-------------------------------------------------------------
  # read message from STDIN
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 on success,
  #          1 if there's no input
  #-------------------------------------------------------------

  local -i return_code=0

  # store message in ORIG_MESSAGE
  ORIG_MESSAGE="$(sed -ne '1,$p')"

  # check if message was successfully stored
  if [[ -z "$ORIG_MESSAGE" ]]; then
    LogMessage "FATAL: Message couldn't be read from standard input. Quitting."
    return_code=1
  fi

  return $return_code
}


function GetGpgMessage {
  #-------------------------------------------------------------
  # get the gpg encrypted part of the message
  #
  # parameter(s): none
  # depends on function(s): GetMessage
  # returns: 0 on success,
  #          1 if encrypted bloc can't be located within the message
  #-------------------------------------------------------------

  local -i return_code=0

  # find the first blank line in the message
  FIRST_BLANK_LINE=$(echo "$ORIG_MESSAGE" | grep -nm 1 '^$' | cut -d : -f 1)

  # then, find the beginning of the encrypted bloc
  if [[ -n $FIRST_BLANK_LINE ]]; then
    ENCRYPTED_BLOC_BEGINS=$(echo "$ORIG_MESSAGE" | grep -nm 1 -- '^-----BEGIN PGP MESSAGE-----' | cut -d : -f 1)

    # and then find the end of the bloc
    if [[ -n $ENCRYPTED_BLOC_BEGINS ]]; then
      ENCRYPTED_BLOC_ENDS=$(echo "$ORIG_MESSAGE" | grep -nm 1 -- '^-----END PGP MESSAGE-----' | cut -d : -f 1)

      # if there's an encrypted bloc, store it in ORIG_GPG_MESSAGE
      if [[ -n $ENCRYPTED_BLOC_ENDS ]]; then
        ORIG_GPG_MESSAGE="$(
          echo "$ORIG_MESSAGE" | \
          sed -ne "$((${ENCRYPTED_BLOC_ENDS} + 1))q;${ENCRYPTED_BLOC_BEGINS},${ENCRYPTED_BLOC_ENDS}p"
        )"
      fi
    fi
  fi

  # check if the bloc was successfully stored
  if [[ -z "$ORIG_GPG_MESSAGE" ]]; then
    LogMessage "WARNING: No valid GPG encrypted bloc found within the message"
    return_code=1
  fi

  return $return_code
}


function ParseGpgDecryptStderr {
  #-------------------------------------------------------------
  # parse $GPG_DECRYPT STDERR for signature checking
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars, GetGpgMessage, GetSenderAddress
  # returns: 0
  #-------------------------------------------------------------

  local gpg_decrypt_stderr

  # get GPG_DECRYPT STDERR, discarding its STDOUT
  gpg_decrypt_stderr="$(
    echo -e "${PASSPHRASE}\n${ORIG_GPG_MESSAGE}" | \
    ($GPG_DECRYPT --status-fd 2 1> /dev/null) 2>&1
  )"

  # check if message was encrypted with the list's public key
  if
    echo "$gpg_decrypt_stderr" | \
    grep -q "^\[GNUPG:] ENC_TO $(
      $GPG_LIST_KEYS $LIST_ADDRESS 2> /dev/null | \
      sed -ne '/:[sca]*[^e][sca]*:$/d' -e '/^sub:[^ired]:/p' | \
      cut -d : -f 5
    )"
  then
    ENCRYPTED_TO_LIST="1"

    # if it was, check if its signature is valid
    if
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] GOODSIG'
    then
      GOOD_SIGNATURE="1"

      if [[ -z "$SENDER_ADDRESS" ]]; then
        GetSenderAddress
      fi

      if
        echo "$gpg_decrypt_stderr" | \
        grep '^\[GNUPG:] GOODSIG' | \
        grep -q "$SENDER_ADDRESS"
      then
        SIGNATURE_MADE_BY_SENDER="1"
      else
        SIGNATURE_MADE_BY_SENDER="0"
      fi

    # else, check if the signature is invalid (BAD signature)
    elif
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] BADSIG'
    then
      BAD_SIGNATURE="1"

    # else, check if the signature couldn't be verified
    elif
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] ERRSIG'
    then
      SIGNATURE_CHECKING_FAILED="1"

    # else, check if the message could at least be decrypted
    elif
      echo "$gpg_decrypt_stderr" | \
      grep -q '^\[GNUPG:] DECRYPTION_OKAY'
    then
      MESSAGE_DECRYPTION_OKAY="1"

    fi
  fi
}


function GetSubscribersList {
  #-------------------------------------------------------------
  # get list subscriber addresses for message encryption and delivery
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success,
  #          1 if there are no valid subscribers on list
  #-------------------------------------------------------------

  local -i return_code=0

  # get subscribers' email addresses, excluding invalid, revoked,
  #+expired and disabled keys, as well as any signing only keys
  SUBSCRIBERS_LIST="$(
    $GPG_LIST_KEYS 2> /dev/null | \
    sed -ne "/$LIST_ADDRESS/Id" -e '/:[scaeSCA]*[^E][scaeSCA]*:$/d' -e '/:[scaeSCAE]*D[scaeSCAE]*:$/d' -e '/^pub:[^ired]:/p' | \
    cut -d : -f 10 | \
    grep -o '<[^<>]*>$' | \
    sed -e 's/[<>]//g' | \
    sort -d
  )"

  # check if the list has valid subscribers
  if [[ -z "$SUBSCRIBERS_LIST" ]]; then
    LogMessage "FATAL: $LIST_NAME: No valid subscribers on list \"$LIST_ADDRESS\". Quitting."
    return_code=1
  fi

  return $return_code
}


function GetMessageHeadersAndBody {
  #-------------------------------------------------------------
  # store the message headers and body in two separate variables
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetGpgMessage
  # returns: 0
  #-------------------------------------------------------------

  # store everything up to the first blank line in ORIG_MESSAGE_HEADERS,
  #+unfolding any folded headers
  ORIG_MESSAGE_HEADERS="$(
    echo "$ORIG_MESSAGE" | \
    sed -ne "${FIRST_BLANK_LINE}q;1,$(($FIRST_BLANK_LINE - 1))p" | \
    sed -e :a -e '$!N;s/[ \t]*\n[ \t]\+/ /;ta' -e 'P;D'
  )"

  # store everything after this line in ORIG_MESSAGE_BODY
  ORIG_MESSAGE_BODY="$(
    echo "$ORIG_MESSAGE" | \
    sed -ne "$(($FIRST_BLANK_LINE + 1)),\$p"
  )"
}


function EditListMessageHeaders {
  #-------------------------------------------------------------
  # edit the headers of a list message, removing specific lines, adding
  #+a prefix to the Subject, etc
  #
  # parameter(s): none
  # depends on function(s): GetMessageHeadersAndBody
  # returns: 0
  #-------------------------------------------------------------

  local header
  local sed_args

  MESSAGE_HEADERS="$ORIG_MESSAGE_HEADERS"

  # remove headers as/if defined by firma configuration file
  if [[ -n "$REMOVE_THESE_HEADERS_ON_ALL_LISTS" ]]; then
    for header in $REMOVE_THESE_HEADERS_ON_ALL_LISTS; do
      sed_args="$sed_args -e /^${header}/Id"
    done

    MESSAGE_HEADERS="$(
      echo "$MESSAGE_HEADERS" | \
      sed $sed_args
    )"
  fi

  # remove additional headers as/if defined by the list configuration file
  if [[ -n "$REMOVE_THESE_HEADERS" ]]; then

    # remove local variables contents, in case they have been used above
    header=""
    sed_args=""

    for header in $REMOVE_THESE_HEADERS; do
      sed_args="$sed_args -e /^${header}/Id"
    done

    MESSAGE_HEADERS="$(
      echo "$MESSAGE_HEADERS" | \
      sed $sed_args
    )"
  fi

  # insert/replace the Reply-To header
  if [[ "$REPLIES_SHOULD_GO_TO_LIST" == "1" ]]; then

    if ! echo "$MESSAGE_HEADERS" | \
         grep -iq '^Reply-To:'; then

      # these are the headers of the message to be sent, so no indentation here
      MESSAGE_HEADERS="\
$MESSAGE_HEADERS
Reply-To: $LIST_ADDRESS"

    else
      MESSAGE_HEADERS="$(
        echo "$MESSAGE_HEADERS" | \
        sed -e "s/^Reply-To:.*$/Reply-To: $LIST_ADDRESS/I"
      )"
    fi
  fi

  # hide the sender
  if [[ "$HIDE_SENDER" == "1" ]]; then
    MESSAGE_HEADERS="$(
      echo "$MESSAGE_HEADERS" | \
      sed -e "s/^From:.*$/From: $LIST_ADDRESS/I"
    )"
  fi

  # insert the Subject prefix, if any
  if [[ -n "$SUBJECT_PREFIX" ]]; then

    # first, check if there's a Subject line
    if echo "$MESSAGE_HEADERS" | grep -iq '^Subject:'; then

      # and then check if the Subject already contains the list prefix
      if ! echo "$MESSAGE_HEADERS" | \
           grep -im 1 '^Subject:' | \
           grep -qF "$SUBJECT_PREFIX"; then

        # if it doesn't, insert it
        MESSAGE_HEADERS="$(
          echo "$MESSAGE_HEADERS" | \
          sed -e "s/^Subject:[ \t]*/Subject: $SUBJECT_PREFIX/I"
        )"
      fi

    # else, if there's no Subject line, add one containing only the list prefix
    else

      # these are the headers of the message to be sent, so no indentation here
      MESSAGE_HEADERS="\
$MESSAGE_HEADERS
Subject: $SUBJECT_PREFIX"

    fi
  fi
}


function DecryptGpgMessage {
  #-------------------------------------------------------------
  # decrypt the gpg encrypted part of the message
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars, GetGpgMessage
  # returns: 0
  #-------------------------------------------------------------

  DECRYPTED_MESSAGE="$(
    echo -e "${PASSPHRASE}\n${ORIG_GPG_MESSAGE}" | \
    $GPG_DECRYPT 2> /dev/null
  )"
}


function ReplaceGpgMessage {
  #-------------------------------------------------------------
  # replace the original encrypted bloc by one generated for the list subscribers
  #
  # parameter(s): none
  # depends on function(s): GetGpgMessage, GetMessageHeadersAndBody
  # returns: 0
  #-------------------------------------------------------------

  MESSAGE_BODY="$(
    echo "$ORIG_MESSAGE_BODY" | \
    sed -e "$(($ENCRYPTED_BLOC_BEGINS - $FIRST_BLANK_LINE)),$(($ENCRYPTED_BLOC_ENDS - $FIRST_BLANK_LINE))c $(
      echo "$GPG_MESSAGE" | \
      sed -e '$! s/$/\\/'
    )"
  )"
}


function GetSenderAddress {
  #-------------------------------------------------------------
  # get the sender address, needed for warning and bounce messages processing
  #
  # parameter(s): none
  # depends on function(s): GetMessage
  # returns: 0
  #-------------------------------------------------------------

  local from

  from="$(echo "$ORIG_MESSAGE" | grep -im 1 '^From:')"
  SENDER_ADDRESS=$(
    if [[ -z "$(echo $from | grep '>$')" ]]; then
      echo $from
    else
      echo $from | grep -o '<[^<>]*>$' | sed -e 's/[<>]//g'
    fi
  )
}


function AssembleMessage {
  #-------------------------------------------------------------
  # just put the message headers and body together
  #
  # parameter(s): none
  # depends on function(s): EditListMessageHeaders, ReplaceGpgMessage,
  #                         ComposeAndSendWarningMessage,
  #                         ComposeAndSendBounceMessage
  # returns: 0
  #-------------------------------------------------------------

  # this is the actual message which will be sent, so no indentation here
  MESSAGE="\
$MESSAGE_HEADERS

$MESSAGE_BODY"

}


function ReEncryptAndSendListMessage {
  #-------------------------------------------------------------
  # send message to list subscribers
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars, DecryptGpgMessage,
  #                         GetSubscribersList, AssembleMessage
  # returns: 0
  #-------------------------------------------------------------

  local recipients
  local subscriber

  recipients="$(echo $SUBSCRIBERS_LIST)"

  # check if message should be encrypted and sent to all subscribers at once
  if [[ "$USE_GPG_HIDDEN_RECIPIENT_OPTION" == "1" ]]; then

    GPG_MESSAGE="$(
      echo -e "${PASSPHRASE}\n${DECRYPTED_MESSAGE}" | \
      $GPG_ENCRYPT --group subscribers="$recipients" --hidden-recipient subscribers 2> /dev/null
    )"

    ReplaceGpgMessage
    AssembleMessage
    DeliveryRandomization

    # send message
    echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $recipients

  # else, message should be encrypted and sent to one subscriber at a time
  else
    for subscriber in $recipients; do

      GPG_MESSAGE="$(
        echo -e "${PASSPHRASE}\n${DECRYPTED_MESSAGE}" | \
        $GPG_ENCRYPT --recipient $subscriber
      )"

      ReplaceGpgMessage
      AssembleMessage
      DeliveryRandomization

      # send message
      echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $subscriber

    done
  fi
}


function ComposeAndSendWarningMessage {
  #-------------------------------------------------------------
  # send a "BAD signature" warning to the list administrator(s) and to sender
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetSenderAddress, AssembleMessage
  # returns: 0
  #-------------------------------------------------------------

  local recipients

  recipients="$LIST_ADMIN $SENDER_ADDRESS"

  # these are the headers of the message to be sent, so no indentation here
  MESSAGE_HEADERS="\
From: $LIST_ADDRESS
Subject: BAD signature from $SENDER_ADDRESS
To: $SENDER_ADDRESS
Cc: $(echo $LIST_ADMIN | sed -e 's/ /, /g')"

  # this is the body of the message to be sent, so no indentation here
  MESSAGE_BODY="\
-------- Original Message --------
$ORIG_MESSAGE"

  AssembleMessage

  # send message
  echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $recipients
}


function ComposeAndSendBounceMessage {
  #-------------------------------------------------------------
  # send a bounce message back to sender
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetSenderAddress, AssembleMessage
  # returns: 0
  #-------------------------------------------------------------

  local subject

  subject="$(echo "$ORIG_MESSAGE" | grep -im 1 '^Subject:' | cut -d : -f 2- )"

  # these are the headers of the message to be sent, so no indentation here
  MESSAGE_HEADERS="\
From: $LIST_ADDRESS
Subject: [RETURNED MAIL]$subject
To: $SENDER_ADDRESS"

  # this is the body of the message to be sent, so no indentation here
  MESSAGE_BODY="\
$MESSAGE_BODY

-- 
firma"

  AssembleMessage

  # send message
  echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $SENDER_ADDRESS
}


function ProcessMessage {
  #-------------------------------------------------------------
  # process a received message
  #
  # parameter(s): none
  # depends on function(s): GetMessage, GetGpgMessage, GetSubscribersList,
  #                         GetSenderAddress
  # returns: 0 on success,
  #          1 if any of the above functions return an error
  #-------------------------------------------------------------

  local -i return_code=0

  # try to read message from STDIN
  if GetMessage; then

    # check if the message was encrypted
    if GetGpgMessage; then

      # look for replay attacks
      if ReplayProtectionCheck; then

        # if it was, parse gpg decrypt STDERR to decide what to do next
        ParseGpgDecryptStderr

        # if the message was encrypted with the list's public key and if the
        #+message signature is valid, send message to list subscribers
        if AllowMessageProcessing; then

          # check if the list has valid subscribers

          GetSenderAddress
          GetMessageHeadersAndBody
          EditListMessageHeaders
          DecryptGpgMessage

          if [[ "$MODE" == "list-message" ]]; then
            if GetSubscribersList; then
              ReEncryptAndSendListMessage
            else
              return_code=1
            fi
          elif [[ "$MODE" == "admin-non-interactive" ]]; then
            EmailListAdministration
          fi

        # else, if the message was correctly encrypted but its signature is invalid,
        #+send a warning about this to the list administrator(s) and to sender
        elif [[ "$ENCRYPTED_TO_LIST" == "1" && "$BAD_SIGNATURE" == "1" && "$REQUIRE_SIGNATURE" == "1" ]]; then

          GetSenderAddress

          if [[ -n $(echo $LIST_ADMIN) || -n "$SENDER_ADDRESS" ]]; then
            ComposeAndSendWarningMessage
          fi

        # else, a bounce should be sent
        else

          # if bounce processing is enabled, continue
          if [[ "$SILENTLY_DISCARD_INVALID_MESSAGES" != "1" ]]; then

            GetSenderAddress
            if [[ -n "$SENDER_ADDRESS" ]]; then

              # if the message was encrypted with the list's public key
              if [[ $ENCRYPTED_TO_LIST == "1" ]]; then

                # then, if signature can't be checked, then probably the sender is not subscribed to the list
                # send a bounce, if possible
                if [[ "$SIGNATURE_CHECKING_FAILED" == "1" && "$REQUIRE_SIGNATURE" == "1" ]]; then

                  # this is the body of the message to be sent, so no indentation here
                  MESSAGE_BODY="\
 It was not possible to process this message. Your email
 address is not subscribed to this list. Contact the list
 administrator if you have any questions."
                  ComposeAndSendBounceMessage

                # or, if message can be decrypted but its signature can't be checked, then message wasn't signed
                # send a bounce, if possible
                elif [[ $MESSAGE_DECRYPTION_OKAY == "1" ]]; then

                  # this is the body of the message to be sent, so no indentation here
                  MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not signed. Contact the list administrator if you have any
 questions."
                  ComposeAndSendBounceMessage

                elif [[ "$SIGNATURE_MADE_BY_SENDER" != "1" && "$REQUIRE_SIGNATURE" == "1" ]]; then

                # this is the body of the message to be sent, so no indentation here
                MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not sent by the person who signed it."

                  ComposeAndSendBounceMessage

                fi

              # else, message wasn't encrypted with the list's public key
              # send a bounce, if possible
              else

                # this is the body of the message to be sent, so no indentation here
                MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not encrypted with the list's public key. Contact the list
 administrator if you have any questions."
                ComposeAndSendBounceMessage
              fi
            fi
          fi
        fi
      else

        # if bounce processing is enabled, continue
        if [[ "$SILENTLY_DISCARD_INVALID_MESSAGES" != "1" ]]; then

          GetSenderAddress
          if [[ -n "$SENDER_ADDRESS" ]]; then

            # the anti-replay mechanism detected a repeated message
            MESSAGE_BODY="\
 It was not possible to process this message. This list
 is configured to discard replayed messages as an attack
 protection measure. It looks like your message has been
 sent to the list before and so it was discarded. Contact
 the list administrator if you have any questions."
            ComposeAndSendBounceMessage
          fi
        fi
      fi
    # else, message wasn't encrypted at all
    # send a bounce, if possible
    else

      # if bounce processing is enabled, continue
      if [[ "$SILENTLY_DISCARD_INVALID_MESSAGES" != "1" ]]; then

        GetSenderAddress
        if [[ -n "$SENDER_ADDRESS" ]]; then

          # this is the body of the message to be sent, so no indentation here
          MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not encrypted. Contact the list administrator if you have
 have any questions."
          ComposeAndSendBounceMessage
        fi
      fi
    fi

  # else, message could not be read from STDIN
  else
    return_code=1
  fi

  return $return_code
}


function NewList {
  #-------------------------------------------------------------
  # create a list if it doesn't exist yet
  #
  # parameter(s): none
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success, 1 if list already exists or cannot be created
  #-------------------------------------------------------------

  local -i return_code=0
  local answer admin invalid method
  local last_char digits_only

  # UTF-8 is avoided in DETAILS
  echo "Firma will ask you some questions to setup your list."
  echo "Please don't use UTF-8 characters."

  read -rep "  List keyring location: ($LIST_PATH) " LIST_HOMEDIR
  LIST_HOMEDIR=${LIST_HOMEDIR:-"$LIST_PATH"}

  if [[ -d "$LIST_HOMEDIR" ]]; then
    echo "Cannot create list $LIST_NAME: List already exists at $LIST_HOMEDIR"
    return_code=1
  else

    echo "Creating folder $LIST_HOMEDIR..."
    mkdir -p $LIST_HOMEDIR

    if [[ -d "$LIST_HOMEDIR" ]]; then

      # list address
      while true; do
        read -rep "  List email address or 'quit' to exit: " LIST_ADDRESS
        if [[ "$LIST_ADDRESS" == "quit" ]]; then
          echo "Deleting folder $LIST_HOMEDIR..."
          rm -rf $LIST_HOMEDIR
          echo "List creation aborted."
          return_code=1
          break
        elif CheckValidEmail $LIST_ADDRESS; then
          break
        elif [[ -n "$LIST_ADDRESS" ]]; then
          echo "  Invalid email address: $LIST_ADDRESS"
        fi
      done

      # admin emails
      if [[ "$return_code" == "0" ]]; then
        while true; do
          read -rep "  List administrator(s) email address(es) (space delimited) or 'quit' to exit: " LIST_ADMIN
          if [[ "$LIST_ADMIN" == "quit" ]]; then
            echo "Deleting folder $LIST_HOMEDIR..."
            rm -rf $LIST_HOMEDIR
            echo "List creation aborted."
            return_code=1
            break
          elif [[ -n "$LIST_ADMIN" ]]; then
            for admin in $LIST_ADMIN; do
              if ! CheckValidEmail $admin; then
                invalid="$(echo $invalid $admin | sed -e 's/  / /')"
              fi
            done
            if [[ -n "$invalid" ]]; then
              echo "  Invalid email address: $invalid"
              invalid=""
            else
              break
            fi
          fi
        done
      fi

      # list description, passphrase and key size
      if [[ "$return_code" == "0" ]]; then
        read -rep "  List description (optional): " KEY_DESCRIPTION
        if [[ ! -z "$KEY_DESCRIPTION" ]]; then
          KEY_DESCRIPTION="Name-Real: $KEY_DESCRIPTION"
        fi
        while true; do
          read -rep "  Automatically create a passphrase for the list pubkey? (Y/n) " answer
          answer="$(echo $answer | tr '[:lower:]' '[:upper:]')"
          if [[ -z "$answer" || "$answer" == "Y" || "$answer" == "YES" ]]; then
            PASSPHRASE="$(RandomString 62)"
            while ! CheckPassphrase; do
              PASSPHRASE="$(RandomString 62)"
            done
            break
          elif [[ "$answer" == "N" || "$answer" == "NO" ]]; then
            read -resp "  Passphrase to protect the list's secret key (you'll type it once): " PASSPHRASE
            while ! CheckPassphrase; do
              echo ""
              read -resp "  Passphrase doesn't fit all the requirements, please choose another: " PASSPHRASE
            done
            break
          else
            echo "  Please answer either yes or no."
          fi
        done

        while true; do
          echo "  Please choose a key size:"
          echo "    1 - 1024"
          echo "    2 - 2048"
          echo "    3 - 4096 (default)"
          read -rep "  Please choose a key size or 'quit' to exit:  " answer
          answer="$(echo $answer | tr '[:lower:]' '[:upper:]')"
          if [[ "$answer" == "QUIT" ]]; then
            echo "Deleting folder $LIST_HOMEDIR..."
            rm -rf $LIST_HOMEDIR
            echo "List creation aborted."
            return_code=1
            break
          elif [[ "$answer" == "1" || "$answer" == "1024" ]]; then
            KEY_SIZE="1024"
            break
          elif [[ "$answer" == "2" || "$answer" == "2048" ]]; then
            KEY_SIZE="2048"
            break
          elif [[ -z "$answer" || "$answer" == "3" || "$answer" == "4096" ]]; then
            KEY_SIZE="4096"
            break
          else
            echo "  Invalid answer."
          fi
        done
      fi

      # key expiration
      if [[ "$return_code" == "0" ]]; then
        echo "  Choose a key validity:"
        echo "      0 = key does not expire (default)"
        echo "   <n>  = key expires in n days"
        echo "   <n>w = key expires in n weeks"
        echo "   <n>m = key expires in n months"
        echo "   <n>y = key expires in n years"

        while true; do
          read -rep "  Please enter the key expiration time or 'quit' to exit: " KEY_EXPIRATION
          KEY_EXPIRATION="$(echo $KEY_EXPIRATION | tr '[:upper:]' '[:lower:]')"
          last_char="$(echo "$KEY_EXPIRATION" | grep -o '[wmy]$')"
          digits_only="$(echo "$KEY_EXPIRATION" | sed -e "s/${last_char}$//")"
          if [[ -z "$KEY_EXPIRATION" ]]; then
            KEY_EXPIRATION="0"
            break
          elif [[ "$KEY_EXPIRATION" == "quit" ]]; then
            echo "Deleting folder $LIST_HOMEDIR..."
            rm -rf $LIST_HOMEDIR
            echo "List creation aborted."
            return_code=1
            break
          elif [[ -z "$(echo $digits_only | sed -e 's/[0-9]//g')" ]]; then
            break
          else
            echo "  Invalid key expiration time."
          fi
        done
      fi

      # config file creation
      if [[ "$return_code" == "0" ]]; then
        echo "Creating your config..."
        touch $LIST_CONFIG_FILE 2> /dev/null
        chmod 600 $LIST_CONFIG_FILE 2> /dev/null
        chown $FIRMA_USER:$FIRMA_GROUP $LIST_CONFIG_FILE 2> /dev/null
        if [[ -f "$LIST_CONFIG_FILE" ]]; then
          DeclareGpgVars
          echo -e "LIST_HOMEDIR='$LIST_HOMEDIR'\nLIST_ADDRESS='$LIST_ADDRESS'\nLIST_ADMIN='$LIST_ADMIN'\nPASSPHRASE='$PASSPHRASE'" > $LIST_CONFIG_FILE
          echo -e "KEY_SIZE='$KEY_SIZE'\nKEY_DESCRIPTION='$KEY_DESCRIPTION'" >> $LIST_CONFIG_FILE
          echo "Now generating your keyring..."

          $GPG --gen-key <<EOF

            Key-Type: DSA
            Key-Length: $KEY_SIZE
            Subkey-Type: ELG-E
            Subkey-Length: $KEY_SIZE

            $KEY_DESCRIPTION
            Name-Email: $LIST_ADDRESS

            Expire-Date: $KEY_EXPIRATION
            Passphrase: $PASSPHRASE
            %commit

EOF

          # import admins pubkeys
          while true; do
            read -rep "  Import list admins' pubkeys? (Y/n) " answer
            answer="$(echo $answer | tr '[:lower:]' '[:upper:]')"
            if [[ -z "$answer" || "$answer" == "Y" || "$answer" == "YES" ]]; then

              echo "  Please choose a key import method:"
              echo "    1 - Fetch the keys from a keyserver"
              echo "    2 - Key material stored in a file"

              while true; do
                read -rep "  Please enter your choice: " answer
                if [[ "$answer" == "1" ]]; then
                  read -rep "  Please enter the keyserver address (defaults to $KEYSERVER): " answer
                  method="keyserver $answer"
                  break
                elif [[ "$answer" == "2" ]]; then
                  method="file"
                  break
                else
                  echo "  Invalid answer. Choose either 1 or 2."
                fi
              done

              SubscribeUsers $method $LIST_ADMIN

              # send list pubkey to admins
              if [[ "$?" == "0" ]]; then
                while true; do
                  read -rep "  Send list public key to list admins? (Y/n) " answer
                  answer="$(echo $answer | tr '[:lower:]' '[:upper:]')"
                  if [[ -z "$answer" || "$answer" == "Y" || "$answer" == "YES" ]]; then
                    SourceListConfig
                    CheckListConfigFile
                    SendListPubkey $LIST_ADMIN
                    break
                  elif [[ "$answer" == "N" || "$answer" == "NO" ]]; then
                    echo "  Not sending public key from list to admins. Do it manually."
                    break
                  else
                    echo "  Please answer either yes or no."
                  fi
                done
              fi

              break
            elif [[ "$answer" == "N" || "$answer" == "NO" ]]; then
              echo "  Not sending public key from list to admins. Do it manually."
              break
            else
              echo "  Please answer either yes or no."
            fi
          done

          # fix permissions
          chown -R $FIRMA_USER:$FIRMA_GROUP $LIST_HOMEDIR 2> /dev/null

          echo "Your list was created. Now check its configuration at $LIST_CONFIG_FILE."
          echo "To see a list of optional config parameters, type firma --help config."
        fi
      fi
    else
      echo "Could not create list homedir $LIST_HOMEDIR."
      return_code=1
    fi
  fi

  # list creation should be atomic
  if [[ "$return_code" == "0" ]]; then
    echo "List creation complete."
  fi

  return $return_code
}


function AdminHelp {
  #-------------------------------------------------------------
  # display help on admin commands
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  # this will be printed to STDOUT, so no indentation here
  echo "
  quit                             quit the admin prompt
  help                             show this help
  list                             show list subscribers
  listinfo                         show list information
  config                           list configuration
  info EMAIL-ADDRESS               show info of a given subscriber
  sendkey SUBSCRIBER               send list pubkey to subscriber
  sub|subscribe [..]               subscribe users ('subscribe help' for options)
  unsub|unsubscribe EMAIL-ADDRESS  unsubscribe an email from the list
  use EMAIL-ADDRESS                use the given address for message delivery instead
                                   of the primary address on key
"
}


function ListAdministration {
  #-------------------------------------------------------------
  # process administrative tasks
  #
  # parameter(s): task to be performed (plus its argument(s))
  # depends on function(s): ChooseUid, CheckValidEmail, UbsubscribeUser
  #                         SubscribeUsers, SendListPubkey
  # returns: 0 if task is executed successfully,
  #          1 if task can't be executed (command not found, too many/missing arguments, etc.),
  #          3 if a quit command is entered
  #-------------------------------------------------------------

  local -i return_code=0
  local subscribers

  # NOTE: when adding a new admin command, dont forget to
  #       - add a summary on AdminHelp function
  #       - if needed, add a "help" option to show more detailed help

  case $# in
    1)
      case $1 in
        help)
          AdminHelp
          ;;
        quit)
          return_code=3
          ;;
        use)
          AdminLog "$1: missing arguments (try \"help\")"
          return_code=1
          ;;
        unsub|unsubscribe)
          AdminLog "$1: missing arguments (try \"help\")"
          return_code=1
          ;;
        list)
          GetSubscribersList
          for subscriber in $SUBSCRIBERS_LIST; do
            AdminLog "  $subscriber"
          done
          ;;
        sub|subscribe)
          AdminLog "$1: missing arguments (try \"$1 help\")"
          return_code=1
          ;;
        sendkey)
          AdminLog "$1: missing arguments (try \"$1 help\")."
          return_code=1
          ;;
        info)
          AdminLog "$1: missing arguments (try \"help\")."
          return_code=1
          ;;
        listinfo)
          GetSubscribersInfo $LIST_ADDRESS
          ;;
        config)
          AdminLog "$1: missing arguments (try \"$1 help\")."
          return_code=1
          ;;
        *)
          AdminLog "Command not found -- $1 (try \"help\")"
          return_code=1
          ;;
      esac
      ;;
    2)
      case $1 in
        use)
          # check if argument is an email address
          if CheckValidEmail $2; then
            ChooseUid $2
          else
            AdminLog "$1: invalid argument -- $2 (try \"help\")"
            return_code=1
          fi
          ;;
        unsub|unsubscribe)
          UnsubscribeUser $2
          return_code=$?
          ;;
        sub|subscribe)
          SubscribeUsers $2
          return_code=$?
          ;;
        sendkey)
          SendListPubkey $2
          return_code=$?
          ;;
        info)
          GetSubscribersInfo $2
          return_code=$?
          ;;
        listinfo)
          AdminLog "$1: too many arguments -- $@ (try \"help\")"
          return_code=1
          ;;
        config)
          if [[ "$2" == "help" ]]; then
            ConfigHelp
            return_code=$?
          else
            AdminLog "$1: too many arguments -- $@ (try \"$1 help\")"
            return_code=1
          fi
          ;;
        help|quit)
          AdminLog "$1: too many arguments -- $@ (try \"help\")"
          return_code=1
          ;;
        *)
          AdminLog "Command not found -- $1 (try \"help\")"
          return_code=1
          ;;
      esac
      ;;
    *)
      case $1 in
        help|quit|use)
          AdminLog "$1: too many arguments -- $@ (try \"help\")"
          return_code=1
          ;;
        sub|subscribe)
          shift
          SubscribeUsers $*
          return_code=$?
          ;;
        sendkey)
          shift
          SendListPubkey $*
          return_code=$?
          ;;
        info)
          shift
          GetSubscribersInfo $*
          return_code=$?
          ;;
        listinfo)
          AdminLog "$1: too many arguments -- $@ (try \"help\")"
          return_code=1
          ;;
        *)
          AdminLog "Command not found -- $1 (try \"help\")"
          return_code=1
          ;;
      esac
      ;;
  esac

  return $return_code
}


function ChooseUid {
  #-------------------------------------------------------------
  # choose which UID of a public key should be used for message delivery,
  #+deleting all other UIDs on the key
  #
  # parameter(s): chosen email address
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success,
  #          1 if task can't be executed (public key not found, only one UID on key, etc.)
  #-------------------------------------------------------------

  local -i return_code=0
  local keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"
  local uid_count="$($GPG_LIST_KEYS --fixed-list-mode $keyid 2> /dev/null | grep ^uid | wc -l)"
  local chosen_uid_number="$($GPG_LIST_KEYS --fixed-list-mode $keyid 2> /dev/null | grep ^uid | grep -ni "$1" | cut -d : -f 1)"

  # check if supplied address is associated with a public key
  if [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$1>" 2> /dev/null | grep -v '^tru:')" ]]; then
    AdminLog "use: \"$1\" is not associated with any public key on this keyring."
    return_code=1
  # then check if there's more than one UID on this public key
  elif (( "$($GPG_LIST_KEYS --fixed-list-mode $1 2> /dev/null | grep ^uid | wc -l)" == "1" )); then
    AdminLog "use: \"$1\" is part of the only UID on public key ${keyid:32}."
    return_code=1
  # and then check if there's only one public key associated with this address
  elif (( "$($GPG_LIST_KEYS --fixed-list-mode $1 2> /dev/null | grep -i "<$1>:$" | wc -l)" > 1 )); then
    AdminLog "use: \"$1\" is listed in more than one UID on this keyring."
    AdminLog "Delete all but one of the public keys or UIDs associated with this email address."
    return_code=1
  fi

  # if all checks are OK, run the expect script bellow
  if (( $return_code == "0" )); then
    expect -nN -- << EOF
      # no output to STDOUT
      log_user 0
      # set a 5 seconds timeout in case anything goes wrong
      set timeout 5

      # call gpg with the "--edit-key" option
      eval spawn -noecho $GPG --with-colons --command-fd 0 --status-fd 1 --edit-key $keyid
      expect "GET_LINE keyedit.prompt" {
        # select for deletion all UIDs other than the chosen one
        set uid 1
        while { \$uid <= $uid_count } {
          if { \$uid != $chosen_uid_number } {
            send "uid \$uid\n"
            expect "GET_LINE keyedit.prompt"
          }
          set uid [incr uid]
        }
        # delete selected UIDs
        send "deluid\n"
        # confirm deletion
        expect "GET_BOOL keyedit.remove.uid.okay" {send "yes\n"}
        # save and exit
        expect "GET_LINE keyedit.prompt" {send "save\n"}
        expect "GOT_IT"
      }

      # delay until the process above terminates
      wait
      # send following message to user
      # send_user "use: \"$1\" chosen for message delivery. [ expr $uid_count - 1 ] UID(s) deleted from public key ${keyid:32}.\n"
      exit
EOF
  fi

  if [[ "$return_code" == "0" || "$?" == "0" ]]; then
    AdminLog "use: $1 chosen for message delivery. $(($uid_count - 1)) UID(s) deleted from public key ${keyid:32}."
  else
    return_code=1
  fi

  FixListOwnership
  return $return_code
}


function CheckPermission {
  #-------------------------------------------------------------
  # check if file has correct permissions (600) and also
  #+if the file is owned by $FIRMA_USER
  #+got the idea for this function from backupninja
  #
  # parameter(s): file name
  # depends on function(s): none
  # returns: 0 if file has correct permissions
  #          1 if not, and also print a warning message
  #-------------------------------------------------------------

  local file="$1"
  local perms="$(ls -ld "$file")"

  perms="${perms:4:6}"
  if [[ "$perms" != "------" ]]; then
    LogMessage "WARNING: Configuration files must not be group or world writable/readable! Wrong permission for file $file"
    return 1
  fi

  if [[ $(ls -ld $file | cut -d " " -f 3) != "$FIRMA_USER" ]]; then
    LogMessage "WARNING: Configuration files must be owned by $FIRMA_USER! Wrong ownership for file $file"
    return 1
  fi

  return 0
}


function CheckListPermissions {
  #-------------------------------------------------------------
  # check if list files has correct permissions (600) and also
  #+if the files are owned by $FIRMA_USER
  #
  # parameter(s): list config file
  # depends on function(s): CheckPermission
  # returns: 0 if file has correct permissions
  #          1 if not, and also print a warning message
  #-------------------------------------------------------------

  local file
  local folder
  local config

  # check and fix permissions on all files from $LIST_PATH to $FIRMA_USER:$FIRMA_GROUP
  if [[ -n "$1" ]]; then
    folder="$(dirname $1)"
    config="$(basename $1)"
    for file in $config pubring.gpg pubring.gpg~ random_seed secring.gpg trustdb.gpg; do
      if ! CheckPermission $folder/$file; then
        LogMessage "Fixing permission and ownership for $folder/$file"
        chmod 600 $folder/$file 2> /dev/null
        chown $FIRMA_USER:$FIRMA_GROUP $folder/$file 2> /dev/null
      fi
    done
  fi
}


function CheckValidEmail {
  #-------------------------------------------------------------
  # check if argument is a valid email address
  #
  # parameter(s): string
  # depends on function(s): none
  # returns: 0 if string represents a valid email address
  #          1 if not
  #-------------------------------------------------------------

  local local_part='[[:alnum:]][[:alnum:]._+-]*[[:alnum:]]'
  local domain='[[:alnum:]][[:alnum:].-]*[[:alnum:]]'
  local tld='[[:alpha:]]\{2,6\}'

  if ! echo "$1" | grep -q "^${local_part}@${domain}\.${tld}$"; then
    return 1
  else
    return 0
  fi
}


function UnsubscribeUser {
  #-------------------------------------------------------------
  # unsubscribe a user and remove its pubkey from
  #+the list keyring
  #
  # parameter(s): chosen email address
  # depends on function(s): DeclareGpgVars
  # returns: 0 on success,
  #          1 if task can't be executed (public key not found, etc.)
  #-------------------------------------------------------------

  local key
  local -i return_code=0
  local keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"

  # check if its a valid email
  if ! CheckValidEmail $1; then
    AdminLog "unsub: \"$1\" is not an email address."
    return_code=1
  # check if user is trying to unsubscribe the list key
  elif [[ "$1" == "$LIST_ADDRESS" ]]; then
    AdminLog "unsub: can't delete the list pubkey."
    return_code=1
  # check if supplied address is associated with a public key
  elif [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$1>" 2> /dev/null | grep -v '^tru:')" ]]; then
    AdminLog "unsub: \"$1\" is not associated with any public key on this keyring."
    return_code=1
  else
    for key in $keyid; do
      $GPG --batch --delete-key --yes $key
      if [[ "$?" == "0" ]]; then
        AdminLog "deleted key id $key for $1"
        # now just update the trust db
        $GPG_LIST_KEYS &> /dev/null
      else
        AdminLog "unsub: error deleting key id $key for $1"
        return_code=1
      fi
    done
  fi

  FixListOwnership
  return $return_code
}


function LogMessage {
  #-------------------------------------------------------------
  # write a log message to STDOUT or to syslog
  #
  # parameter(s): string
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  local error_message="$*"
  local line

  if [[ "$LOG_TO_SYSLOG" == "1" ]]; then
    echo "$error_message" | $LOGGER_BINARY -p "$SYSLOG_PRIORITY" -t "$BASENAME"
  else

    echo "$error_message" | while read line; do
      echo >&2 "$BASENAME: $line"
    done

  fi

  return 0
}


function SubscribeUsers {
  #-------------------------------------------------------------
  # subscribe users to the list importing their pubkeys
  #
  # parameter(s): $1: help, stdin, keyserver or file
  #               $2: where to fetch the pubkeys
  #               $3: keyid (keyserver only)
  # depends on function(s): none
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  local -i return_code=0
  local keyserver
  local method

  if [[ "$1" == "help" ]]; then
    AdminLog "
  help                                 show this help
  stdin                                waits for key material from stdin (interactive mode only)
  file <file-name>                     import pubkeys from file (interactive mode only)
  keyserver [server-address] <key-ids> import <key-ids> from <server-address>
                                       (default keyserver: $KEYSERVER)
"
  elif [[ "$1" == "stdin" ]]; then
    if [[ "$MODE" == "admin-interactive" ]]; then
      echo "Please enter the key material here, finishing with Ctrl-D sequence..."
      $GPG_NOBATCH --import
      return_code=$?
      if [[ "$return_code" == "0" ]]; then
        AdminLog "subscription: success"
      fi
    else
      AdminLog "subscribe: stdin option only valid in the interactive (command-line) mode"
      return_code=1
    fi
  elif [[ "$1" == "file" ]]; then
    if [[ -n "$2" ]]; then
      if [[ -f "$2" ]]; then
        $GPG --import < $2
        return_code=$?
        if [[ "$return_code" == "0" ]]; then
          AdminLog "subscription: success"
        fi
      else
        echo >&2 "subscribe: cant add subscribers from $1: no such file or directory"
        return_code=1
      fi
    else
      echo >&2 "subscribe: missing parameters: subscribe file requires a file name"
      return_code=1
    fi
  elif [[ "$1" == "keyserver" ]]; then
    if [[ -n "$2" ]]; then
      if [[ -z "$3" ]]; then
        keyserver="$KEYSERVER"
      else
        if ! CheckValidEmail $2; then
          keyserver="$2"
          shift
        else
          keyserver="$KEYSERVER"
        fi
      fi
      if CheckValidEmail $2; then
        method="--search-keys"
      else
        method="--recv-keys"
      fi
      if [[ "$return_code" == "0" ]]; then
        shift
        $GPG_NOBATCH --keyserver $keyserver $method $*
        return_code=$?
        if [[ "$return_code" == "0" ]]; then
          AdminLog "subscription: success"
        fi
      fi
    else
      AdminLog "subscribe: missing parameters: type subscribe help"
      return_code=1
    fi
  else
    AdminLog "subscribe: wrong option: type subscribe help"
    return_code=1
  fi

  FixListOwnership
  return $return_code
}


function SendListPubkey {
  #-------------------------------------------------------------
  # send list pubkey to a given subscriber list
  #
  # parameter(s): subscribers' emails
  # depends on function(s): GetMessage, GetSenderAddress, AssembleMessage
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  local key
  local keys
  local keyid
  local keyboundary

  if [[ "$1" == "help" ]]; then
    AdminLog "usage: sendkey [all|email|help]"
    AdminLog "supported arguments: all (for all subscribers) or a space-separated subscriber emails."
    return 0
  elif [[ "$1" == "all" ]]; then
    GetSubscribersList
    keys="$SUBSCRIBERS_LIST"
  else
    keys="$*"
  fi

  for key in $keys; do
    keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"

    if [[ -z "$key" ]]; then
      AdminLog "sendkey: missing argument: subscriber email address."
      return 1
    elif ! CheckValidEmail $key; then
      AdminLog "sendkey: \"$key\" is not an email address."
      return 1
    elif [[ -z "$($GPG_LIST_KEYS --fixed-list-mode "<$key>" 2> /dev/null | grep -v '^tru:')" ]]; then
      # check if supplied address is associated with a public key
      AdminLog "sendkey: \"$key\" is not associated with any public key on this keyring."
      return 1
    fi

    RECIPIENTS="$key"
    SUBJECT="mailing list public key"
    keyboundary="$(RandomString 15)"

    # this is the body of the message to be sent, so no indentation here
    MESSAGE_BODY="$($GPG --armor --export $LIST_ADDRESS)"
    MESSAGE_BODY="\
Content-Type: multipart/mixed; boundary=\"$keyboundary\"
Content-Disposition: inline

--$keyboundary
Content-Type: application/pgp-keys
Content-Disposition: attachment; filename=${LIST_NAME}_pubkey.asc
Content-Description: PGP Key for $LIST_ADDRESS

$MESSAGE_BODY

--${keyboundary}--"

    # compose the message
    MimeWrapMessage

    # send message
    echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $RECIPIENTS
  done

  AdminLog "List pubkey sent to $keys."
  FixListOwnership

}


function GetSubscribersInfo {
  #-------------------------------------------------------------
  # get info on a subscriber pubkey
  #
  # parameter(s): subscribers' emails
  # depends on function(s): none
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  local key
  local keys
  local keyid
  local output

  if [[ "$1" == "help" ]]; then
    AdminLog "usage: info [all|emails|help]"
    AdminLog "supported arguments: all (for all subscribers) or a space-separated subscribers' emails."
    return 0
  elif [[ "$1" == "all" ]]; then
    GetSubscribersList
    keys="$SUBSCRIBERS_LIST"
  else
    keys="$*"
  fi

  for key in $keys; do
    keyid="$($GPG_LIST_KEYS --with-fingerprint $1 2> /dev/null | grep ^fpr | cut -d : -f 10)"
    if [[ -n "$keyid" ]]; then
      output="$($GPG --fingeprint $key)"
      AdminLog "$output"
    fi
  done

  FixListOwnership
  return $?
}


function FixListOwnership {
  #-------------------------------------------------------------
  # fix list ownership
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0 on success
  #          1 on failure
  #-------------------------------------------------------------

  if [[ -d "$LIST_PATH" ]]; then
    chown -R $FIRMA_USER:$FIRMA_GROUP $LIST_PATH 2> /dev/null
  fi
  return $?
}


function RandomString {
  #-------------------------------------------------------------
  # print a random string
  #+got it from http://funcoeszz.net/
  #
  # parameter(s): string size (max 62)
  # depends on function(s): none
  # returns: 0
  #          1 if string size is greater than 62
  #-------------------------------------------------------------

  local n alpha="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,;:?!"

  n="$(( 10#$(echo "$1" | tr -dc '[:digit:]') ))"
  if [[ "$n" == "0" ]]; then
    n="6"
  fi

  if [[ "$n" -gt "62" ]]; then
    return 1
  fi

  while [[ "$n" != "0" ]]; do n="$((n-1))" ; pos="$((RANDOM%${#alpha}+1))"
    echo -n "$alpha" | sed "s/\(.\)\{$pos\}.*/\1/"
    alpha="$(echo $alpha | sed "s/.//$pos")"
  done | tr -d '\012' ; echo

  return 0
}


function AdminLog {
  #-------------------------------------------------------------
  # check whether admin is made via command line
  #+or email and then log a message according to the
  #+display mode
  #
  # parameter(s): string
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  if [[ "$MODE" == "admin-interactive" ]]; then
    echo >&2 "$*"
  else
    echo "$*"
  fi
}


function EmailListAdministration {
  #-------------------------------------------------------------
  # parse and execute admin tasks via email
  #
  # parameter(s): none
  # depends on function(s): ProcessMessage should be called first
  # returns: 0 on success  :)
  #          1 on failure  :/
  #-------------------------------------------------------------

  local sender found
  local command

  found="0"
  for sender in $LIST_ADMIN; do
    if [[ "$sender" == "$SENDER_ADDRESS" ]]; then
      found="1"
      break
    fi
  done
  if [[ "$found" == "1" ]]; then
    # message was sent by an admin
    #+then, parse and process admin tasks
    MESSAGE_BODY="$(echo -e "$DECRYPTED_MESSAGE" | while read command; do
      if [[ -n "$command" ]] && echo $command | grep -q -v -e "^Content"; then
        AdminLog "Command> $command"
        ListAdministration $command
      fi
    done)"
    # send a message back to the administrator
    RECIPIENTS="$SENDER_ADDRESS"
    SUBJECT="admin request results"
    CreateMessageBodyPart
    MimeWrapMessage
    echo "$MESSAGE" | $MAIL_AGENT $MAIL_AGENT_ARGS $SENDER_ADDRESS
  else
    # message was sent by a normal subscriber
    # this is the body of the message to be sent, so no indentation here
    MESSAGE_BODY="\
 It was not possible to process this message. Message was
 not sent by a list administrator."
    ComposeAndSendBounceMessage
  fi

  return $?
}


function AllowMessageProcessing {
  #-------------------------------------------------------------
  # check if the message has sufficient rights to be processed
  #
  # parameter(s): none
  # depends on function(s): ParseGpgDecryptStderr
  # returns: 0 if message has rights to be processed
  #          1 if not
  #-------------------------------------------------------------

  local -i return_code=0

  if [[ "$MODE" == "admin-non-interactive" ]]; then
    REQUIRE_SIGNATURE="1"
  fi

  if [[ "$ENCRYPTED_TO_LIST" == "1" ]]; then
    if [[ "$REQUIRE_SIGNATURE" == "1" ]]; then
      if [[ "$GOOD_SIGNATURE" == "1" && "$SIGNATURE_MADE_BY_SENDER" == "1" ]]; then
        return_code=0
      else
        return_code=1
      fi
    else
      return_code=0
    fi
  else
    return_code=1
  fi

  return $return_code
}


function MimeWrapMessage {
  #-------------------------------------------------------------
  # MIME wrap message to be sent, adding needed headers and body parts
  #
  # parameter(s): none
  # depends on variable(s): RECIPIENTS, SUBJECT, GPG_MESSAGE
  #
  # returns: 0
  #-------------------------------------------------------------

  local boundary

  boundary="$(RandomString 15)"

  # these are the headers of the message to be sent, so no indentation here
  MESSAGE_HEADERS="\
From: $LIST_REQUEST_ADDRESS
To: ${RECIPIENTS}
Reply-To: $LIST_REQUEST_ADDRESS
Subject: ${SUBJECT_PREFIX}${SUBJECT}
MIME-Version: 1.0
Content-Type: multipart/encrypted;
  protocol=\"application/pgp-encrypted\";
  boundary=\"${boundary}\"
Content-Disposition: inline"

  GPG_MESSAGE="$(echo -e "${PASSPHRASE}\n${MESSAGE_BODY}" | $GPG_ENCRYPT --recipient $RECIPIENTS)"

  # this is the body of the message to be sent, so no indentation here
  MESSAGE_BODY="\
This is an OpenPGP/MIME encrypted message (RFC 2440 and 3156)
--$boundary
Content-Type: application/pgp-encrypted
Content-Description: PGP/MIME version identification

Version: 1

--$boundary
Content-Type: application/octet-stream; name=\"encrypted.asc\"
Content-Disposition: inline; filename=\"encrypted.asc\"

${GPG_MESSAGE}

--${boundary}--"

  # assemble entire message
  MESSAGE="\
${MESSAGE_HEADERS}

${MESSAGE_BODY}"
}


function CreateMessageBodyPart {
  #-------------------------------------------------------------
  # create a message body part
  #
  # parameter(s): none
  # depends on variable(s): MESSAGE_BODY
  #
  # returns: 0
  #-------------------------------------------------------------

  # this is the body of the message to be sent, so no indentation here
  MESSAGE_BODY="\
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline

$MESSAGE_BODY"
}


function EvalConfigParameter {
  #-------------------------------------------------------------
  # eval parameters from a config file
  #
  # parameter(s): <config-file> <parameter>
  # depends on function(s): none
  # returns: 0 on success
  #          1 if config file not found or missing parameter
  #-------------------------------------------------------------

  if [[ "$#" != "2" ]]; then
    echo "WARNING: missing parameters on EvalConfigParameters."
    return 1
  elif [[ ! -f "$1" ]]; then
    echo "WARNING: file not found: $1"
    return 1
  fi

  echo "$(grep "^$2=" $1 | sed -e "s/^$2='//" -e "s/'$//" | tail -n 1)"

}


function SourceFirmaConfig {
  #-------------------------------------------------------------
  # load firma.conf and set up global variables
  #
  # parameter(s): none for evaluation, help to show all config parameters
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  [[ "$1" == "help" ]] && echo -e "\nMandatory global firma config parameters\n"

  [[ "$1" == "help" ]] && echo -e "\tGPG_BINARY= path to the GnuPG binary." || \
  GPG_BINARY="$(EvalConfigParameter $FIRMA_CONFIG_FILE GPG_BINARY)"

  [[ "$1" == "help" ]] && echo -e "\tMAIL_AGENT= path to the mail transport agent to be used (e.g., sendmail)." || \
  MAIL_AGENT="$(EvalConfigParameter $FIRMA_CONFIG_FILE MAIL_AGENT)"

  [[ "$1" == "help" ]] && echo -e "\tMAIL_AGENT_ARGS= command-line arguments to be passed to the command above." || \
  MAIL_AGENT_ARGS="$(EvalConfigParameter $FIRMA_CONFIG_FILE MAIL_AGENT_ARGS)"

  [[ "$1" == "help" ]] && echo -e "\tLISTS_DIR= path to the mailing lists directory." || \
  LISTS_DIR="$(EvalConfigParameter $FIRMA_CONFIG_FILE LISTS_DIR)"

  [[ "$1" == "help" ]] && echo -e "\nOptional global firma config parameters\n"

  [[ "$1" == "help" ]] && echo -e "\tFIRMA_USER= user that runs firma (usually the same as your MTA user);
\t      defaults to \"nobody\"; you can also specify this parameter
\t      in each mailing list config file if you plan to have one
\t      user per mailing list." || \
  FIRMA_USER="$(EvalConfigParameter $FIRMA_CONFIG_FILE FIRMA_USER)"

  [[ "$1" == "help" ]] && echo -e "\tFIRMA_GROUP= group that runs firma (usually the same as your MTA group);
\t       defaults to \"nobody\"; you can also specify this parameter
\t       in each mailing list config file if you plan to have one
\t       group per mailing list." || \
  FIRMA_GROUP="$(EvalConfigParameter $FIRMA_CONFIG_FILE FIRMA_GROUP)"

  [[ "$1" == "help" ]] && echo -e "\tLOG_TO_SYSLOG= set to "1" to log errors and warnings to syslog, else firma
\t               will print errors to STDERR." || \
  LOG_TO_SYSLOG="$(EvalConfigParameter $FIRMA_CONFIG_FILE LOG_TO_SYSLOG)"

  [[ "$1" == "help" ]] && echo -e "\tLOGGER_BINARY= if logging to syslog, set the path to logger's binary." || \
  LOGGER_BINARY="$(EvalConfigParameter $FIRMA_CONFIG_FILE LOGGER_BINARY)"

  [[ "$1" == "help" ]] && echo -e "\tSYSLOG_PRIORITY= if logging to syslog, set a priority for the error messages
\t                 (defaults to "user.err")." || \
  SYSLOG_PRIORITY="$(EvalConfigParameter $FIRMA_CONFIG_FILE SYSLOG_PRIORITY)"

  [[ "$1" == "help" ]] && echo -e "\tUSE_GPG_HIDDEN_RECIPIENT_OPTION= set to '1' to use GnuPG's --hidden-recipient
\t                                 option, available from version 1.4.0 onwards
\t                                 (try 'man gpg' for more information)." || \
  USE_GPG_HIDDEN_RECIPIENT_OPTION="$(EvalConfigParameter $FIRMA_CONFIG_FILE USE_GPG_HIDDEN_RECIPIENT_OPTION)"

  [[ "$1" == "help" ]] && echo -e "\tREMOVE_THESE_HEADERS_ON_ALL_LISTS= headers that should be stripped from list
\t                                   messages on all lists running under firma
\t                                   (space separated case-insensitive entries)
\t                                   (may include regexps (e.g., X-.*)." || \
  REMOVE_THESE_HEADERS_ON_ALL_LISTS="$(EvalConfigParameter $FIRMA_CONFIG_FILE REMOVE_THESE_HEADERS_ON_ALL_LISTS)"

  [[ "$1" == "help" ]] && echo -e "\tKEYSERVER= default keyserver to import/export keys
\t           (defaults to keys.indymedia.org)." || \
  KEYSERVER="$(EvalConfigParameter $FIRMA_CONFIG_FILE KEYSERVER)"
}


function SourceListConfig {
  #-------------------------------------------------------------
  # load list.conf and set up global variables
  #
  # parameter(s): none for evaluation, help to show all config parameters
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  local firma_user firma_group keyserver

  [[ "$1" == "help" ]] && echo -e "\nMandatory list config parameters\n"

  [[ "$1" == "help" ]] && echo -e "\tLIST_ADDRESS= list's email address." || \
  LIST_ADDRESS="$(EvalConfigParameter $LIST_CONFIG_FILE LIST_ADDRESS)"

  [[ "$1" == "help" ]] && echo -e "\tLIST_REQUEST_ADDRESS= list's email address for administrative
\t                      requests (defaults to listname-request@domain." || \
  LIST_REQUEST_ADDRESS="$(EvalConfigParameter $LIST_CONFIG_FILE LIST_REQUEST_ADDRESS)"

  [[ "$1" == "help" ]] && echo -e "\tLIST_ADMIN= list's administrators email addresses (space separated)." || \
  LIST_ADMIN="$(EvalConfigParameter $LIST_CONFIG_FILE LIST_ADMIN)"

  [[ "$1" == "help" ]] && echo -e "\tLIST_HOMEDIR= list's GnuPG homedir, where the list's keyrings are located." || \
  LIST_HOMEDIR="$(EvalConfigParameter $LIST_CONFIG_FILE LIST_HOMEDIR)"

  [[ "$1" == "help" ]] && echo -e "\tFIRMA_USER= user that runs firma (usually the same as your MTA user);
\t      defaults to \"nobody\"; you can also specify this parameter
\t      in each mailing list config file if you plan to have one
\t      user per mailing list." || \
  firma_user="$(EvalConfigParameter $LIST_CONFIG_FILE FIRMA_USER)"
  [[ -n "$firma_user" ]] && FIRMA_USER="$firma_user"

  [[ "$1" == "help" ]] && echo -e "\tFIRMA_GROUP= group that runs firma (usually the same as your MTA group);
\t       defaults to \"nobody\"; you can also specify this parameter
\t       in each mailing list config file if you plan to have one
\t       group per mailing list." || \
  firma_group="$(EvalConfigParameter $LIST_CONFIG_FILE FIRMA_GROUP)"
  [[ -n "$firma_group" ]] && FIRMA_GROUP="$firma_group"

  [[ "$1" == "help" ]] && echo -e "\tPASSPHRASE= passphrase for the list's private keyring\n
\tNOTE: The passphrase _has_ to be enclosed in single quotes and _cannot_
\tcontain any additional single quote as part of itself. It has to be at least
\t25 characters long, combining numbers, upper and lower case letters and at
\tleast 1 special characters. Also, no character can be sequentially repeated
\tmore than 4 times." || \
  PASSPHRASE="$(EvalConfigParameter $LIST_CONFIG_FILE PASSPHRASE)"

  [[ "$1" == "help" ]] && echo -e "\nOptional list config parameters\n"

  [[ "$1" == "help" ]] && echo -e "\tSUBJECT_PREFIX= prefix to be included in the subject of list messages." || \
  SUBJECT_PREFIX="$(EvalConfigParameter $LIST_CONFIG_FILE SUBJECT_PREFIX)"

  [[ "$1" == "help" ]] && echo -e "\tREMOVE_THESE_HEADERS= headers that should be stripped from list messages
\t                      (space separated case-insensitive entries)
\t                      (may include regexps (e.g., X-.*)." || \
  REMOVE_THESE_HEADERS="$(EvalConfigParameter $LIST_CONFIG_FILE REMOVE_THESE_HEADERS)"

  [[ "$1" == "help" ]] && echo -e "\tREPLIES_SHOULD_GO_TO_LIST= set to '1' to add a Reply-To header containing the list address." || \
  REPLIES_SHOULD_GO_TO_LIST="$(EvalConfigParameter $LIST_CONFIG_FILE REPLIES_SHOULD_GO_TO_LIST)"

  [[ "$1" == "help" ]] && echo -e "\tHIDE_SENDER= set to '1' to add replace the sender address with list address on list messages." || \
  HIDE_SENDER="$(EvalConfigParameter $LIST_CONFIG_FILE HIDE_SENDER)"

  [[ "$1" == "help" ]] && echo -e "\tSILENTLY_DISCARD_INVALID_MESSAGES= set to '1' to silently discard invalid
\t                                   messages (message not signed/encrypted,
\t                                   sender not subscribed to the list, etc.)
\t                                   instead of sending bounces back to sender." || \
  SILENTLY_DISCARD_INVALID_MESSAGES="$(EvalConfigParameter $LIST_CONFIG_FILE SILENTLY_DISCARD_INVALID_MESSAGES)"

  [[ "$1" == "help" ]] && echo -e "\tKEYSERVER= default keyserver to import/export keys
\t           (defaults to keys.indymedia.org)." || \
  keyserver="$(EvalConfigParameter $LIST_CONFIG_FILE KEYSERVER)"
  [[ -n "$keyserver" ]] && KEYSERVER="$keyserver"

  [[ "$1" == "help" ]] && echo -e "\tREQUIRE_SIGNATURE= whether messages sent to the list should be (1) or dont
\t                   need to be (0) signed to be processed; defaults to '1';
\t                   this doesnt affect the way email administration works,
\t                   when signature is mandatory." || \
  REQUIRE_SIGNATURE="$(EvalConfigParameter $LIST_CONFIG_FILE REQUIRE_SIGNATURE)"

  [[ "$1" == "help" ]] && echo -e "\tDELIVERY_RANDOMIZATION= if non-zero, set a random delay between 0 and N seconds
\t                        between each messsage delivery; if you run firma with
\t                        a TLS-enabled MTA and mostly of the list messages are
\t                        sent to others TLS-enabled MTAs, then this option will
\t                        make harder to a sniffer detect the traffic of you mailing
\t                        list, specially if your MTA already sends a lot of messages
\t                        or if you're going to have a lot of encrypted mailing lists,
\t                        all randomizing its delivery." || \
  DELIVERY_RANDOMIZATION="$(EvalConfigParameter $LIST_CONFIG_FILE DELIVERY_RANDOMIZATION)"

  [[ "$1" == "help" ]] && echo -e "\tREPLAY_PROTECTION= when set to '1', stores sha1sums
\t                   of the last REPLAY_COUNT received messages; then,
\t                   if some message with an already stored sha1sum, then
\t                   its bounced back to the sender and considered as an attempt
\t                   of replay attack." || \
  REPLAY_PROTECTION="$(EvalConfigParameter $LIST_CONFIG_FILE REPLAY_PROTECTION)"

  [[ "$1" == "help" ]] && echo -e "\tREPLAY_COUNT= number of messages to store sha1sums;
\t              defaults to 150 and only used when
\t              REPLAY_PROTECTION is set to '1'." || \
  REPLAY_COUNT="$(EvalConfigParameter $LIST_CONFIG_FILE REPLAY_COUNT)"

  [[ "$1" == "help" ]] && echo -e "\tREPLAY_FILE= file to store sha1sums of messages;
\t             only used when REPLAY_PROTECTION is set to '1';
\t             defaults to \"/var/log/firma/replay.db\"." || \
  REPLAY_FILE="$(EvalConfigParameter $LIST_CONFIG_FILE REPLAY_FILE)"
}


function ConfigHelp {
  #-------------------------------------------------------------
  # display help on configuration file parameters
  #
  # parameter(s): none
  # depends on function(s): SourceFirmaConfig, SourceListConfig
  # returns: 0
  #-------------------------------------------------------------

  echo "All firma parameters are passed through two different configuration files:"
  echo "firma.conf, containing general parameters needed to run the script, and a list"
  echo "specific file, containing its address, administrator(s), etc. In both files"
  echo "you should enter PARAMETER='value' (with value between single quotes, without"
  echo "spaces before or after the equal sign and nothing after the second quote)."

  SourceFirmaConfig help
  SourceListConfig help
}


function DeliveryRandomization {
  #-------------------------------------------------------------
  # sleep according $DELIVERY_RANDOMIZATION
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  local n

  if [[ "$DELIVERY_RANDOMIZATION" != "0" ]]; then
    n="$RANDOM"
    let "n %= $DELIVERY_RANDOMIZATION"
    sleep $n
  fi
}


function ReplayProtectionFlush {
  #-------------------------------------------------------------
  # flushes the replay database file
  #
  # parameter(s): none
  # depends on function(s): none
  # returns: 0
  #-------------------------------------------------------------

  if [[ "$REPLAY_PROTECTION" == "1" ]]; then
    if [[ -f "$REPLAY_FILE" ]]; then
      if [[ "$(wc -l $REPLAY_FILE | cut -d " " -f 1)" -gt "$REPLAY_COUNT" ]]; then
        sed -i -e '1d' $REPLAY_FILE
      fi
    else
      touch $REPLAY_FILE 2> /dev/null
      chown $FIRMA_USER:$FIRMA_GROUP $REPLAY_FILE 2> /dev/null
      chmod 600 $REPLAY_FILE 2> /dev/null
    fi
  fi

  return 0
}


function ReplayProtectionCheck {
  #-------------------------------------------------------------
  # check if message was already received and stores it
  #+in the database
  #
  # parameter(s): GetGpgMessage, ReplayProtectionFlush
  # depends on function(s): none
  # returns: 0 if message's sha1sum is not in replay database
  #          1 if message's sha1sum is in the database
  #-------------------------------------------------------------

  local -i return_code=0
  local sha1

  if [[ "$REPLAY_PROTECTION" == "1" && -n "$ORIG_GPG_MESSAGE" ]]; then
    ReplayProtectionFlush
    sha1="$(echo "$ORIG_GPG_MESSAGE" | sha1sum | cut -d " " -f 1)"
    if grep -q "^$sha1$" $REPLAY_FILE; then
      sed -i -e "/^$sha1$/d" $REPLAY_FILE
      return_code=1
    fi
    echo "$sha1" >> $REPLAY_FILE
  fi

  return $return_code
}

#-------------------------------------------------------------
# main()
#-------------------------------------------------------------

# hardcode path to firma.conf, firma version and program name
declare -r \
  FIRMA_CONFIG_FILE="/var/lib/firma/firma.conf" \
  VERSION="0.4-git" \
  BASENAME="$(basename $0)"

# set environmental variables and options
export LANG=en_US
umask 0077

# set initial exit code
EXIT_CODE=0

# define the number of command line arguments, the option
#+being run and its argument, if any
declare -r \
  NUM_OF_ARGS="$#" \
  OPTION="$1" \
  ARG="$2"

# check command line arguments for errors
#+(missing arguments, invalid option, etc)
case "$NUM_OF_ARGS" in
  0)

    echo >&2 "$BASENAME: missing arguments"
    Usage
    EXIT_CODE=1
    ;;

  1)
    case "$OPTION" in

      # valid short option
      -h|-v)
        ;;

      # valid long option
      --help|--version)
        ;;

      # valid short option called without its required argument
      -a|-c|-e|-p)
        echo >&2 "$BASENAME: missing arguments"
        Usage
        EXIT_CODE=1
        ;;

      # valid long option called without its required argument
      --admin-task|--create-newlist|--email-admin-task|--process-message)
        echo >&2 "$BASENAME: missing arguments"
        Usage
        EXIT_CODE=1
        ;;

      # invalid option
      *)
        echo >&2 "$BASENAME: invalid option -- $OPTION"
        Usage
        EXIT_CODE=1
        ;;

    esac
    ;;
  2)
    case "$OPTION" in

      # valid short option
      -a|-c|-e|-p|-h)
        ;;

      # valid long option
      --admin-task|--create-newlist|--email-admin-task|--process-message|--help)
        ;;

      # valid short option called with too many arguments
      -v)
        echo >&2 "$BASENAME: too many arguments -- $@"
        Usage
        EXIT_CODE=1
        ;;

      # valid long option called with too many arguments
      --version)
        echo >&2 "$BASENAME: too many arguments -- $@"
        Usage
        EXIT_CODE=1
        ;;

      # invalid option
      *)
        echo >&2 "$BASENAME: invalid option -- $OPTION"
        Usage
        EXIT_CODE=1
        ;;

    esac
    ;;
  *)
    case "$OPTION" in

      # valid short option called with too many arguments
      -h|-v|-a|-c|-e|-p)
        echo >&2 "$BASENAME: too many arguments -- $@"
        Usage
        EXIT_CODE=1
        ;;

      # valid long option called with too many arguments
      --help|--version|--admin-task|--create-newlist|--email-admin-task|--process-message)
        echo >&2 "$BASENAME: too many arguments -- $@"
        Usage
        EXIT_CODE=1
        ;;

      # invalid option
      *)
        echo >&2 "$BASENAME: invalid option -- $OPTION"
        Usage
        EXIT_CODE=1
        ;;

    esac
    ;;
esac

# parse valid command line arguments
if [[ "$EXIT_CODE" == "0" ]]; then

  case "$NUM_OF_ARGS" in

    1)
      case "$OPTION" in

        -h|--help)
          Usage
          EXIT_CODE=0
          ;;

        -v|--version)
          Version
          EXIT_CODE=0
          ;;

      esac
      ;;
    2)
      # help options
      if [ "$OPTION" == "--help" ] || [ "$OPTION" == "-h" ]; then

        if [ "$ARG" == "config" ]; then

          ConfigHelp
          EXIT_CODE=0

        else

          echo >&2 "$BASENAME: invalid help section -- $ARG"
          Usage
          EXIT_CODE=1

        fi

      # if firma.conf exists and can be read
      elif [[ ! -r "$FIRMA_CONFIG_FILE" ]]; then

        LogMessage "FATAL: Cannot source \`$FIRMA_CONFIG_FILE': No such file or directory"
        EXIT_CODE=1

      # then source and evaluate its parameters
      elif ! { SourceFirmaConfig && \
               CheckFirmaConfigFile && \
               CheckPermission "$FIRMA_CONFIG_FILE"
             }; then

        EXIT_CODE=1

      else

        LIST_NAME="$ARG"
        LIST_PATH="$LISTS_DIR/$LIST_NAME"
        LIST_CONFIG_FILE="$LIST_PATH/$LIST_NAME.conf"

        case "$OPTION" in

          -c|--create-newlist)
            NewList
            EXIT_CODE=$?
            ;;

          # options that depend on the list configuration file
          -a|--admin-task|-e|--email-admin-task|-p|--process-message)

            # if list config file exists and can be read
            if [[ ! -r "$LIST_CONFIG_FILE" ]]; then

              LogMessage "FATAL: Cannot source \`$LIST_CONFIG_FILE': No such file or directory"
              EXIT_CODE=1

            # then source and evaluate its parameters
            elif ! { SourceListConfig && \
                     DeclareGpgVars && \
                     CheckListPermissions "$LIST_CONFIG_FILE" && \
                     CheckListConfigFile
                   }; then

              EXIT_CODE=1

            else

              case "$OPTION" in

                -a|--admin-task)

                  MODE="admin-interactive"
                  # while a "quit" command isn't entered (returns 3), read STDIN
                  while (( $EXIT_CODE != 3 )) && read -rep "Command> " STDIN; do
                    # if line is not empty or commented, process command
                    if [[ -n "$STDIN" && "$STDIN" != "#"* ]]; then
                      ListAdministration $STDIN
                      EXIT_CODE=$?
                    fi
                  done

                  # since quit was entered, exit without error
                  EXIT_CODE=0

                  ;;

                -p|--process-message)
                  MODE="list-message"
                  ProcessMessage
                  EXIT_CODE=$?
                  ;;
                -e|--email-admin-task)
                  MODE="admin-non-interactive"
                  ProcessMessage
                  EXIT_CODE=$?
                  ;;

              esac

            fi
            ;;

        esac

      fi
      ;;

  esac
fi

# exit
exit $EXIT_CODE