File: prog.c

package info (click to toggle)
daemon 0.8.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,072 kB
  • sloc: ansic: 30,432; sh: 4,310; perl: 592; makefile: 307
file content (2940 lines) | stat: -rw-r--r-- 68,457 bytes parent folder | download
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
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
/*
* libslack - https://libslack.org
*
* Copyright (C) 1999-2004, 2010, 2020-2023 raf <raf@raf.org>
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*
* 20230824 raf <raf@raf.org>
*/

/*

=head1 NAME

I<libslack(prog)> - program framework module

=head1 SYNOPSIS

    #include <slack/std.h>
    #include <slack/prog.h>

    typedef struct option option;
    typedef struct Option Option;
    typedef struct Options Options;

    typedef void opt_action_int_t(int arg);
    typedef void opt_action_optional_int_t(int *arg);
    typedef void opt_action_string_t(const char *arg);
    typedef void opt_action_optional_string_t(const char *arg);
    typedef void opt_action_none_t(void);
    typedef void func_t(void);

    enum OptionArgument
    {
        OPT_NONE,
        OPT_INTEGER,
        OPT_STRING
    };

    enum OptionAction
    {
        OPT_NOTHING,
        OPT_VARIABLE,
        OPT_FUNCTION
    };

    typedef enum OptionArgument OptionArgument;
    typedef enum OptionAction OptionAction;

    struct Option
    {
        const char *name;
        char short_name;
        const char *argname;
        const char *desc;
        int has_arg;
        OptionArgument arg_type;
        OptionAction action;
        void *object;
        func_t *function;
    };

    struct Options
    {
        Options *parent;
        Option *options;
    };

    void prog_init(void);
    const char *prog_set_name(const char *name);
    Options *prog_set_options(Options *options);
    const char *prog_set_syntax(const char *syntax);
    const char *prog_set_desc(const char *desc);
    const char *prog_set_version(const char *version);
    const char *prog_set_date(const char *date);
    const char *prog_set_author(const char *author);
    const char *prog_set_contact(const char *contact);
    const char *prog_set_vendor(const char *vendor);
    const char *prog_set_url(const char *url);
    const char *prog_set_legal(const char *legal);
    Msg *prog_set_out(Msg *out);
    Msg *prog_set_err(Msg *err);
    Msg *prog_set_dbg(Msg *dbg);
    Msg *prog_set_alert(Msg *alert);
    ssize_t prog_set_debug_level(size_t debug_level);
    ssize_t prog_set_verbosity_level(size_t verbosity_level);
    int prog_set_locker(Locker *locker);
    const char *prog_name(void);
    const Options *prog_options(void);
    const char *prog_syntax(void);
    const char *prog_desc(void);
    const char *prog_version(void);
    const char *prog_date(void);
    const char *prog_author(void);
    const char *prog_contact(void);
    const char *prog_vendor(void);
    const char *prog_url(void);
    const char *prog_legal(void);
    Msg *prog_out(void);
    Msg *prog_err(void);
    Msg *prog_dbg(void);
    Msg *prog_alert(void);
    size_t prog_debug_level(void);
    size_t prog_verbosity_level(void);
    int prog_out_fd(int fd);
    int prog_out_stdout(void);
    int prog_out_file(const char *path);
    int prog_out_syslog(const char *ident, int option, int facility, int priority);
    int prog_out_push_filter(msg_filter_t *filter);
    int prog_out_none(void);
    int prog_err_fd(int fd);
    int prog_err_stderr(void);
    int prog_err_file(const char *path);
    int prog_err_syslog(const char *ident, int option, int facility, int priority);
    int prog_err_push_filter(msg_filter_t *filter);
    int prog_err_none(void);
    int prog_dbg_fd(int fd);
    int prog_dbg_stdout(void);
    int prog_dbg_stderr(void);
    int prog_dbg_file(const char *path);
    int prog_dbg_syslog(const char *id, int option, int facility, int priority);
    int prog_dbg_push_filter(msg_filter_t *filter);
    int prog_dbg_none(void);
    int prog_alert_fd(int fd);
    int prog_alert_stdout(void);
    int prog_alert_stderr(void);
    int prog_alert_file(const char *path);
    int prog_alert_syslog(const char *id, int option, int facility, int priority);
    int prog_alert_push_filter(msg_filter_t *filter);
    int prog_alert_none(void);
    int prog_opt_process(int ac, char **av);
    void prog_usage_msg(const char *format, ...);
    void prog_help_msg(void);
    void prog_version_msg(void);
    const char *prog_basename(const char *path);
    extern Options prog_options_table[1];
    int opt_process(int argc, char **argv, Options *options, char *msgbuf, size_t bufsize);
    char *opt_usage(char *buf, size_t size, Options *options);

=head1 DESCRIPTION

This module provides administrative services for arbitrary programs. The
services include program identification; flexible, complete command line
option processing; help, usage and version messages; flexible debug,
verbose, error and normal messaging (simple call syntax with arbitrary
message destinations including multiplexing).

This module exposes an alternate interface to I<GNU getopt_long(3)>. It
defines a way to specify command line option syntax, semantics and
descriptions in multiple, discrete chunks. The I<getopt> functions require
that the client specify the syntax and partial semantics for all options in
the same place (if it is to be done statically). This can be annoying when
library modules require their own command line options. This module allows
various parts of a program to (statically) specify their own command line
options independently, and link them together via C<parent> pointers.

Option syntax is specified in much the same way as for I<GNU
getopt_long(3)>. Option semantics are specified by an action
(C<OPT_NOTHING>, C<OPT_VARIABLE> or C<OPT_FUNCTION>), an argument type
(C<OPT_NONE>, C<OPT_INTEGER> or C<OPT_STRING>), and either an object
(C<int *>, C<char **>) or function (C<func()>, C<func(int)> or C<func(char *)>).

The I<opt_process(3)> and I<opt_usage(3)> functions are used by the I<prog>
functions and needn't be used directly. Instead, use I<prog_opt_process(3)>
to execute options and I<prog_usage_msg(3)> and I<prog_help_msg(3)> to
construct usage and help messages directly from the supplied option data.
They are exposed in case you don't want to use any other part of this
module.

=over 4

=cut

*/

#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* For snprintf() on OpenBSD-4.7 */
#endif

#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE /* New name for _BSD_SOURCE */
#endif

#include "config.h"
#include "std.h"

#include "msg.h"
#include "err.h"
#include "mem.h"
#include "prog.h"

#ifndef HAVE_SNPRINTF
#include "snprintf.h"
#endif

typedef struct Prog Prog;

struct Prog
{
	const char *name;
	Options *options;
	const char *syntax;
	const char *desc;
	const char *version;
	const char *date;
	const char *author;
	const char *contact;
	const char *vendor;
	const char *url;
	const char *legal;
	Msg *out;
	Msg *err;
	Msg *dbg;
	Msg *log;
	size_t debug_level;
	size_t verbosity_level;
	Locker *locker;
};

#ifndef TEST

static Prog g =
{
	NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
	NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL
};

/*

=item C<void prog_init(void)>

Initialises the message, error, debug, and alert destinations to C<stdout>,
C<stderr>, C<stderr>, and C<stderr>, respectively. These are all C<null> by
default so this function must be called before any messages are emitted.

=cut

*/

void prog_init(void)
{
	prog_out_stdout();
	prog_err_stderr();
	prog_dbg_stderr();
	prog_alert_stderr();
}

/*

=item C<const char *prog_set_name(const char *name)>

Sets the program's name to C<name>. This is used when composing usage, help,
version, and error messages. On success, returns C<name>. On error, returns
C<null> with C<errno> set appropriately.

=cut

*/

#define RDLOCK(ret) { int rc; if ((rc = locker_rdlock(g.locker))) { set_errno(rc); return (ret); } }
#define WRLOCK(ret) { int rc; if ((rc = locker_wrlock(g.locker))) { set_errno(rc); return (ret); } }
#define UNLOCK(ret) { int rc; if ((rc = locker_unlock(g.locker))) { set_errno(rc); return (ret); } }

#define PROG_SET_STR_AND_RETURN(name, value) \
	WRLOCK(NULL) \
	name = value; \
	UNLOCK(NULL) \
	return value

#define PROG_SET_MSG_AND_RETURN(name, value) \
	WRLOCK(NULL) \
	if (name && name != value) \
		msg_release(name); \
	name = value; \
	UNLOCK(NULL) \
	return value

#define PROG_POP_MSG(name, lvalue) \
	WRLOCK(-1) \
	lvalue = name; \
	name = NULL; \
	UNLOCK(-1) \

#define PROG_SET_INT_AND_RETURN_PREVIOUS(name, value) \
	size_t prev; \
	WRLOCK(-1) \
	prev = name; \
	name = value; \
	UNLOCK(-1) \
	return prev

#define PROG_GET_PTR_AND_RETURN(name) \
	void *value; \
	RDLOCK(NULL) \
	value = (void *)name; \
	UNLOCK(NULL) \
	return value

#define PROG_GET_INT_AND_RETURN(name) \
	int value; \
	RDLOCK(0) \
	value = name; \
	UNLOCK(0) \
	return value

const char *prog_set_name(const char *name)
{
	PROG_SET_STR_AND_RETURN(g.name, name);
}

/*

=item C<Options *prog_set_options(Options *options)>

Sets the program's options to C<options>. This is used when processing the
command line options with I<prog_opt_process(3)>. On success, returns
C<options>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

Options *prog_set_options(Options *options)
{
	PROG_SET_STR_AND_RETURN(g.options, options);
}

/*

=item C<const char *prog_set_syntax(const char *syntax)>

Sets the program's command line syntax summary to C<syntax>. This is used
when composing usage and help messages. It must contain a one line summary
of the command line arguments, excluding the program name (e.g. C<"[options]
arg...">). On success, returns C<syntax>. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

const char *prog_set_syntax(const char *syntax)
{
	PROG_SET_STR_AND_RETURN(g.syntax, syntax);
}

/*

=item C<const char *prog_set_desc(const char *desc)>

Sets the program's description to C<desc>. This is used when composing help
messages. On success, returns C<desc>. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

const char *prog_set_desc(const char *desc)
{
	PROG_SET_STR_AND_RETURN(g.desc, desc);
}

/*

=item C<const char *prog_set_version(const char *version)>

Sets the program's version string to C<version>. This is used when composing
help and version messages. On success, returns C<version>. On error, returns
C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_set_version(const char *version)
{
	PROG_SET_STR_AND_RETURN(g.version, version);
}

/*

=item C<const char *prog_set_date(const char *date)>

Sets the program's release date to C<date>. This is used when composing help
messages. On success, returns C<date>. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

const char *prog_set_date(const char *date)
{
	PROG_SET_STR_AND_RETURN(g.date, date);
}

/*

=item C<const char *prog_set_author(const char *author)>

Sets the program's author to C<author>. This is used when composing help
messages. It must contain the (free format) name of the author. Returns
C<author>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_set_author(const char *author)
{
	PROG_SET_STR_AND_RETURN(g.author, author);
}

/*

=item C<const char *prog_set_contact(const char *contact)>

Sets the program's contact address to C<contact>. This is used when
composing help messages. It must contain the email address to which bug
reports should be sent. On success, returns C<contact>. On error, returns
C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_set_contact(const char *contact)
{
	PROG_SET_STR_AND_RETURN(g.contact, contact);
}

/*

=item C<const char *prog_set_vendor(const char *vendor)>

Sets the program's vendor to C<vendor>. This is used when composing help
messages. It must contain the (free format) name of the vendor. Returns
C<vendor>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_set_vendor(const char *vendor)
{
	PROG_SET_STR_AND_RETURN(g.vendor, vendor);
}

/*

=item C<const char *prog_set_url(const char *url)>

Sets the program's URL to C<url>. This is used when composing help messages.
It must contain the URL where the program can be downloaded. On success,
returns C<url>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_set_url(const char *url)
{
	PROG_SET_STR_AND_RETURN(g.url, url);
}

/*

=item C<const char *prog_set_legal(const char *legal)>

Sets the program's legal notice to C<legal>. This is used when composing
help messages. It is assumed that the legal notice may contain multiple
lines and so must contain its own newline characters. On success, returns
C<legal>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_set_legal(const char *legal)
{
	PROG_SET_STR_AND_RETURN(g.legal, legal);
}

/*

=item C<Msg *prog_set_out(Msg *out)>

Sets the program's message destination to C<out>. This is used by I<msg(3)>
and I<vmsg(3)> which are, in turn, used to emit usage, version and help
messages. The program message destination is set to standard output by
I<prog_init(3)>, but it can be anything. However, it is probably best to
leave it as standard output at least until after command line option
processing is complete. See I<msg(3)> for details. On success, returns
C<out>. On error, returns C<null> with C<errno> set appropriately.

=cut

*/

Msg *prog_set_out(Msg *out)
{
	PROG_SET_MSG_AND_RETURN(g.out, out);
}

/*

=item C<Msg *prog_set_err(Msg *err)>

Sets the program's error message destination to C<err>. This is used by
I<error(3)>, I<errorsys(3)>, I<fatal(3)>, I<fatalsys(3)>, I<dump(3)> and
I<dumpsys(3)>. The program error message destination is set to standard
error by I<prog_init(3)>, but it can be anything. See I<msg(3)> for details.
On success, returns C<err>. On error, returns C<null> with C<errno> set
appropriately.

=cut

*/

Msg *prog_set_err(Msg *err)
{
	PROG_SET_MSG_AND_RETURN(g.err, err);
}

/*

=item C<Msg *prog_set_dbg(Msg *dbg)>

Sets the program's debug message destination to C<dbg>. This is set to
standard error by I<prog_init(3)>, but it can be set to anything. See
I<msg(3)> for details. On success, returns C<dbg>. On error, returns C<null>
with C<errno> set appropriately.

=cut

*/

Msg *prog_set_dbg(Msg *dbg)
{
	PROG_SET_MSG_AND_RETURN(g.dbg, dbg);
}

/*

=item C<Msg *prog_set_alert(Msg *alert)>

Sets the program's alert message destination to C<alert>. This is set to
standard error by I<prog_init(3)> but it can be set to anything. See
I<msg(3)> for details. On success, returns C<alert>. On error, returns
C<null> with C<errno> set appropriately.

=cut

*/

Msg *prog_set_alert(Msg *alert)
{
	PROG_SET_MSG_AND_RETURN(g.log, alert);
}

/*

=item C<ssize_t prog_set_debug_level(size_t debug_level)>

Sets the program's debug level to C<debug_level>. This is used when
determining whether or not to emit a debug message. The debug level
comprises two parts, the I<section> and the I<level>. The I<level> occupies
the low byte of C<debug_level>. The I<section> occupies the next three
bytes. This enables debugging to be partitioned into sections, allowing
users to turn on debugging at any level (from 0 up to 255) for particular
sections of a program (at most 24). Debug messages with a section value
whose bits overlap those of the program's current debug section and with a
level that is less than or equal to the program's current debug level are
emitted. As a convenience, if the program debug section is zero, debug
messages with a sufficiently small level are emitted regardless of the
message section. On success, returns the previous debug level. On error,
returns C<-1> with C<errno> set appropriately.

Example:

    #define LEXER_SECTION  (1 << 8)
    #define PARSER_SECTION (2 << 8)
    #define INTERP_SECTION (4 << 8)

    prog_set_debug_level(LEXER_SECTION | PARSER_SECTION | 1);
    debug((LEXER_SECTION  | 1, "lexer debugmsg"))  // yes
    debug((LEXER_SECTION  | 4, "lexer debugmsg"))  // no (level too high)
    debug((PARSER_SECTION | 1, "parser debugmsg")) // yes
    debug((INTERP_SECTION | 1, "interp debugmsg")) // no (wrong section)
    debug((1, "global debug"))                  // no (no section to match)

    prog_set_debug_level(1);
    debug((LEXER_SECTION  | 1, "lexer debugmsg"))  // yes
    debug((LEXER_SECTION  | 4, "lexer debugmsg"))  // no (level too high)
    debug((PARSER_SECTION | 1, "parser debugmsg")) // yes
    debug((INTERP_SECTION | 1, "interp debugmsg")) // yes
    debug((1, "global debugmsg"))                  // yes
    debug((4, "global debugmsg"))                  // no (level too high)

=cut

*/

ssize_t prog_set_debug_level(size_t debug_level)
{
	PROG_SET_INT_AND_RETURN_PREVIOUS(g.debug_level, debug_level);
}

/*

=item C<ssize_t prog_set_verbosity_level(size_t verbosity_level)>

Sets the program's verbosity level to C<verbosity_level>. This is used to
determine whether or not to emit verbose messages. Verbose messages with a
level that is less than or equal to the program's current verbosity level
are emitted. On success, returns the previous verbosity level. On error,
returns C<-1> with C<errno> set appropriately.

=cut

*/

ssize_t prog_set_verbosity_level(size_t verbosity_level)
{
	PROG_SET_INT_AND_RETURN_PREVIOUS(g.verbosity_level, verbosity_level);
}

/*

=item C<int prog_set_locker(Locker *locker)>

Sets the locker (multiple thread synchronisation strategy) for this module.
This is only needed in multi-threaded programs. See I<locker(3)> for
details. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_set_locker(Locker *locker)
{
	if (g.locker)
		return -1;

	g.locker = locker;

	return 0;
}

/*

=item C<const char *prog_name(void)>

Returns the program's name as set by I<prog_set_name(3)>. On error, returns
C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_name(void)
{
	PROG_GET_PTR_AND_RETURN(g.name);
}

/*

=item C<const Options *prog_options(void)>

Returns the program's options as set by I<prog_set_options(3)>. On error,
returns C<null> with C<errno> set appropriately.

=cut

*/

const Options *prog_options(void)
{
	PROG_GET_PTR_AND_RETURN(g.options);
}

/*

=item C<const char *prog_syntax(void)>

Returns the program's command line syntax summary as set by
I<prog_set_syntax(3)>. On error, returns C<null> with C<errno> set
appropriately.

=cut

*/

const char *prog_syntax(void)
{
	PROG_GET_PTR_AND_RETURN(g.syntax);
}

/*

=item C<const char *prog_desc(void)>

Returns the program's description as set by I<prog_set_desc(3)>. On error,
returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_desc(void)
{
	PROG_GET_PTR_AND_RETURN(g.desc);
}

/*

=item C<const char *prog_version(void)>

Returns the program's version string as set by I<prog_set_version(3)>. On
error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_version(void)
{
	PROG_GET_PTR_AND_RETURN(g.version);
}

/*

=item C<const char *prog_date(void)>

Returns the program's release date as set by I<prog_set_date(3)>. On error,
returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_date(void)
{
	PROG_GET_PTR_AND_RETURN(g.date);
}

/*

=item C<const char *prog_author(void)>

Returns the program's author as set by I<prog_set_author(3)>. On error,
returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_author(void)
{
	PROG_GET_PTR_AND_RETURN(g.author);
}

/*

=item C<const char *prog_contact(void)>

Returns the program's contact address as set by I<prog_set_contact(3)>. On
error, returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_contact(void)
{
	PROG_GET_PTR_AND_RETURN(g.contact);
}

/*

=item C<const char *prog_vendor(void)>

Returns the program's vendor as set by I<prog_set_vendor(3)>. On error,
returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_vendor(void)
{
	PROG_GET_PTR_AND_RETURN(g.vendor);
}

/*

=item C<const char *prog_url(void)>

Returns the program's URL as set by I<prog_set_url(3)>. On error, returns
C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_url(void)
{
	PROG_GET_PTR_AND_RETURN(g.url);
}

/*

=item C<const char *prog_legal(void)>

Returns the program's legal notice as set by I<prog_set_legal(3)>. On error,
returns C<null> with C<errno> set appropriately.

=cut

*/

const char *prog_legal(void)
{
	PROG_GET_PTR_AND_RETURN(g.legal);
}

/*

=item C<Msg *prog_out(void)>

Returns the program's message destination as set by I<prog_set_out(3)>. On
error, returns C<null> with C<errno> set appropriately.

=cut

*/

Msg *prog_out(void)
{
	PROG_GET_PTR_AND_RETURN(g.out);
}

/*

=item C<Msg *prog_err(void)>

Returns the program's error message destination as set by
I<prog_set_err(3)>. On error, returns C<null> with C<errno> set
appropriately.

=cut

*/

Msg *prog_err(void)
{
	PROG_GET_PTR_AND_RETURN(g.err);
}

/*

=item C<Msg *prog_dbg(void)>

Returns the program's debug message destination as set by
I<prog_set_dbg(3)>. On error, returns C<null> with C<errno> set
appropriately.

=cut

*/

Msg *prog_dbg(void)
{
	PROG_GET_PTR_AND_RETURN(g.dbg);
}

/*

=item C<Msg *prog_alert(void)>

Returns the program's alert message destination as set by
I<prog_set_alert(3)>. On error, returns C<null> with C<errno> set
appropriately.

=cut

*/

Msg *prog_alert(void)
{
	PROG_GET_PTR_AND_RETURN(g.log);
}

/*

=item C<size_t prog_debug_level(void)>

Returns the program's debug level as set by I<prog_set_debug_level(3)>. On
error, returns C<0> with C<errno> set appropriately.

=cut

*/

size_t prog_debug_level(void)
{
	PROG_GET_INT_AND_RETURN(g.debug_level);
}

/*

=item C<size_t prog_verbosity_level(void)>

Returns the program's verbosity level as set by
I<prog_set_verbosity_level(3)>. On error, returns C<0> with C<errno> set
appropriately.

=cut

*/

size_t prog_verbosity_level(void)
{
	PROG_GET_INT_AND_RETURN(g.verbosity_level);
}

/*

=item C<int prog_out_fd(int fd)>

Sets the program's normal message destination to be the file descriptor,
C<fd>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_out_fd(int fd)
{
	Msg *mesg;

	if (!(mesg = msg_create_fd_with_locker(g.locker, fd)))
		return -1;

	if (!prog_set_out(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_out_stdout(void)>

Sets the program's normal message destination to be standard output. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_out_stdout(void)
{
	return prog_out_fd(STDOUT_FILENO);
}

/*

=item C<int prog_out_file(const char *path)>

Sets the program's normal message destination to be the file specified by
C<path>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_out_file(const char *path)
{
	Msg *mesg;

	if (!(mesg = msg_create_file_with_locker(g.locker, path)))
		return -1;

	if (!prog_set_out(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_out_syslog(const char *ident, int option, int facility, int priority)>

Sets the program's normal message destination to be I<syslog> initialised
with C<ident>, C<option>, C<facility>, and C<priority>. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.

=cut

*/

int prog_out_syslog(const char *ident, int option, int facility, int priority)
{
	Msg *mesg;

	if (!(mesg = msg_create_syslog_with_locker(g.locker, ident, option, facility, priority)))
		return -1;

	if (!prog_set_out(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_out_push_filter(msg_filter_t *filter)>

Pushes the message filter function, I<filter>, onto the program's normal
message destination. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_out_push_filter(msg_filter_t *filter)
{
	Msg *mesg, *top;

	PROG_POP_MSG(g.out, top);

	if (!(mesg = msg_create_filter_with_locker(g.locker, filter, top)))
		return -1;

	if (!prog_set_out(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_out_none(void)>

Sets the program's normal message destination to C<null>. This disables all
normal messages. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_out_none(void)
{
	errno = 0;
	prog_set_out(NULL);

	return (errno) ? -1 : 0;
}

/*

=item C<int prog_err_fd(int fd)>

Sets the program's error message destination to be the file descriptor,
C<fd>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_err_fd(int fd)
{
	Msg *mesg;

	if (!(mesg = msg_create_fd_with_locker(g.locker, fd)))
		return -1;

	if (!prog_set_err(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_err_stderr(void)>

Sets the program's error message destination to be standard error. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_err_stderr(void)
{
	return prog_err_fd(STDERR_FILENO);
}

/*

=item C<int prog_err_file(const char *path)>

Sets the program's error message destination to be the file specified by
C<path>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_err_file(const char *path)
{
	Msg *mesg;

	if (!(mesg = msg_create_file_with_locker(g.locker, path)))
		return -1;

	if (!prog_set_err(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_err_syslog(const char *ident, int option, int facility, int priority)>

Sets the program's error message destination to be I<syslog> initialised
with C<ident>, C<option>, C<facility>, and C<priority>. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.

=cut

*/

int prog_err_syslog(const char *ident, int option, int facility, int priority)
{
	Msg *mesg;

	if (!(mesg = msg_create_syslog_with_locker(g.locker, ident, option, facility, priority)))
		return -1;

	if (!prog_set_err(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_err_push_filter(msg_filter_t *filter)>

Pushes the message filter function, I<filter>, onto the program's error
message destination. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_err_push_filter(msg_filter_t *filter)
{
	Msg *mesg, *top;

	PROG_POP_MSG(g.err, top);

	if (!(mesg = msg_create_filter_with_locker(g.locker, filter, top)))
		return -1;

	if (!prog_set_err(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_err_none(void)>

Sets the program's error message destination to C<null>. This disables all
error messages. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_err_none(void)
{
	errno = 0;
	prog_set_err(NULL);

	return (errno) ? -1 : 0;
}

/*

=item C<int prog_dbg_fd(int fd)>

Sets the program's debug message destination to be the file descriptor,
C<fd>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_dbg_fd(int fd)
{
	Msg *mesg;

	if (!(mesg = msg_create_fd_with_locker(g.locker, fd)))
		return -1;

	if (!prog_set_dbg(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_dbg_stdout(void)>

Sets the program's debug message destination to be standard output. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_dbg_stdout(void)
{
	return prog_dbg_fd(STDOUT_FILENO);
}

/*

=item C<int prog_dbg_stderr(void)>

Sets the program's debug message destination to be standard error. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_dbg_stderr(void)
{
	return prog_dbg_fd(STDERR_FILENO);
}

/*

=item C<int prog_dbg_file(const char *path)>

Sets the program's debug message destination to be the file specified by
C<path>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_dbg_file(const char *path)
{
	Msg *dbg;

	if (!(dbg = msg_create_file_with_locker(g.locker, path)))
		return -1;

	if (!prog_set_dbg(dbg))
	{
		msg_release(dbg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_dbg_syslog(const char *id, int option, int facility, int priority)>

Sets the program's debug message destination to be I<syslog> initialised
with C<ident>, C<option>, C<facility>, and C<priority>. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.

=cut

*/

int prog_dbg_syslog(const char *id, int option, int facility, int priority)
{
	Msg *dbg;

	if (!(dbg = msg_create_syslog_with_locker(g.locker, id, option, facility, priority)))
		return -1;

	if (!prog_set_dbg(dbg))
	{
		msg_release(dbg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_dbg_push_filter(msg_filter_t *filter)>

Pushes the message filter function, I<filter>, onto the program's debug
message destination. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_dbg_push_filter(msg_filter_t *filter)
{
	Msg *mesg, *top;

	PROG_POP_MSG(g.dbg, top);

	if (!(mesg = msg_create_filter_with_locker(g.locker, filter, top)))
		return -1;

	if (!prog_set_dbg(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_dbg_none(void)>

Sets the program's debug message destination to C<null>. This disables all
debug messages. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_dbg_none(void)
{
	errno = 0;
	prog_set_dbg(NULL);

	return (errno) ? -1 : 0;
}

/*

=item C<int prog_alert_fd(int fd)>

Sets the program's alert message destination to be the file descriptor
specified by C<fd>. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_alert_fd(int fd)
{
	Msg *mesg;

	if (!(mesg = msg_create_fd_with_locker(g.locker, fd)))
		return -1;

	if (!prog_set_alert(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_alert_stdout(void)>

Sets the program's alert message destination to be standard output. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_alert_stdout(void)
{
	return prog_alert_fd(STDOUT_FILENO);
}

/*

=item C<int prog_alert_stderr(void)>

Sets the program's alert message destination to be standard error. On
success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_alert_stderr(void)
{
	return prog_alert_fd(STDERR_FILENO);
}

/*

=item C<int prog_alert_file(const char *path)>

Sets the program's alert message destination to be the file specified by
C<path>. On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_alert_file(const char *path)
{
	Msg *alert;

	if (!(alert = msg_create_file_with_locker(g.locker, path)))
		return -1;

	if (!prog_set_alert(alert))
	{
		msg_release(alert);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_alert_syslog(const char *id, int option, int facility, int priority)>

Sets the program's alert message destination to be I<syslog> initialised
with C<ident>, C<option>, C<facility>, and C<priority>. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.

=cut

*/

int prog_alert_syslog(const char *id, int option, int facility, int priority)
{
	Msg *alert;

	if (!(alert = msg_create_syslog_with_locker(g.locker, id, option, facility, priority)))
		return -1;

	if (!prog_set_alert(alert))
	{
		msg_release(alert);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_alert_push_filter(msg_filter_t *filter)>

Pushes the message filter function, I<filter>, onto the program's alert
message destination. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_alert_push_filter(msg_filter_t *filter)
{
	Msg *mesg, *top;

	PROG_POP_MSG(g.log, top);

	if (!(mesg = msg_create_filter_with_locker(g.locker, filter, top)))
		return -1;

	g.log = NULL;

	if (!prog_set_alert(mesg))
	{
		msg_release(mesg);
		return -1;
	}

	return 0;
}

/*

=item C<int prog_alert_none(void)>

Sets the program's alert message destination to C<null>. This disables all
alert messages. On success, returns C<0>. On error, returns C<-1> with
C<errno> set appropriately.

=cut

*/

int prog_alert_none(void)
{
	errno = 0;
	prog_set_alert(NULL);

	return (errno) ? -1 : 0;
}

/*

=item C<int prog_opt_process(int ac, char **av)>

Parses and processes the command line options in C<av>. If there is an
error, a usage message is emitted and the program terminates. This function
is just an interface to I<GNU getopt_long(3)> that provides easier, more
flexible, and more complete option handling. As well as supplying the syntax
for options, this function requires their semantics and descriptions. The
descriptions allow usage and help messages to be automatically composed by
I<prog_usage_msg(3)> and I<prog_help_msg(3)>. The semantics (which may be
either a variable assignment or a function invocation) allow complete
command line option processing to be performed with a single call to this
function. On success, returns C<optind>. On error (i.e. invalid option or
option argument), calls I<prog_usage_msg(3)> which terminates the program
with a return code of C<EXIT_FAILURE>. See the I<EXAMPLE> section for
details on specifying option data. See I<opt_process(3)> for details on the
processing of each option. On error, returns C<-1> with C<errno> set
appropriately.

=cut

*/

int prog_opt_process(int ac, char **av)
{
	char msgbuf[256] = "";
	int err;
	int rc;

	if ((err = locker_rdlock(g.locker)))
		return set_errno(err);

	rc = opt_process(ac, av, g.options, msgbuf, 256);

	if ((err = locker_unlock(g.locker)))
		return set_errno(err);

	if (rc == -1)
		prog_usage_msg("%s", msgbuf);

	return rc;
}

/*

=item C<void prog_usage_msg(const char *format, ...)>

Emits a program usage error message, then terminates the program with a
return code of C<EXIT_FAILURE>. The usage message consists of the program's
name, command line syntax, options and their descriptions (if they have been
supplied), and the given message. C<format> is a I<printf(3)>-like format
string. Any remaining arguments are processed as in I<printf(3)>.

B<Warning: Do not under any circumstances ever pass a non-literal string as
the format argument unless you know exactly how many conversions will take
place. Being careless with this is a very good way to build potential
security vulnerabilities into your programs. The same is true for all
functions that take a printf()-like format string as an argument.>

    prog_usage_msg(buf);       // EVIL
    prog_usage_msg("%s", buf); // GOOD

=cut

*/

void prog_usage_msg(const char *format, ...)
{
	char msg_buf[MSG_SIZE];
	char opt_buf[MSG_SIZE];
	int msg_length;
	va_list args;
	va_start(args, format);
	vsnprintf(msg_buf, MSG_SIZE, format, args);
	va_end(args);

	if (locker_rdlock(g.locker))
		exit(EXIT_FAILURE);

	opt_usage(opt_buf, MSG_SIZE, g.options);
	fflush(stderr);

	msg_length = strlen(msg_buf);
	msg_out(g.err, "%s%susage: %s%s%s\n%s%s",
		msg_buf,
		(msg_length && msg_buf[msg_length - 1] != '\n') ? "\n" : "",
		(g.name) ? g.name : "",
		(g.name) ? " " : "",
		(g.syntax) ? g.syntax : "",
		(*opt_buf) ? "options:\n" : "",
		opt_buf
	);

	locker_unlock(g.locker);

	exit(EXIT_FAILURE);
}

/*

=item C<void prog_help_msg(void)>

Emits a program help message, then terminates the program with a return code
of C<EXIT_SUCCESS>. This message consists of the program's usage message,
description, name, version, release date, author, vendor, URL, legal notice
and contact address (if they have been supplied).

=cut

*/

void prog_help_msg(void)
{
	char buf[MSG_SIZE];
	size_t length = 0;

	if (locker_rdlock(g.locker))
		exit(EXIT_FAILURE);

	snprintf(buf, MSG_SIZE, "usage: %s %s\n",
		g.name ? g.name : "",
		g.syntax ? g.syntax : ""
	);

	if (g.options)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "options:\n");
		length = strlen(buf);
		opt_usage(buf + length, MSG_SIZE - length, g.options);
	}

	if (g.desc)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "\n%s\n", g.desc);
	 }

	if (g.name)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "Name: %s\n", g.name);
	}

	if (g.version)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "Version: %s\n", g.version);
	}

	if (g.date)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "Date: %s\n", g.date);
	}

	if (g.author)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "Author: %s\n", g.author);
	}

	if (g.vendor)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "Vendor: %s\n", g.vendor);
	}

	if (g.url)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "URL: %s\n", g.url);
	}

	if (g.legal)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "\n%s\n", g.legal);
	}

	if (g.contact)
	{
		length = strlen(buf);
		snprintf(buf + length, MSG_SIZE - length, "Report bugs to %s\n", g.contact);
	}

	if (locker_unlock(g.locker))
		exit(EXIT_FAILURE);

	msg("%s", buf);
	exit(EXIT_SUCCESS);
}

/*

=item C<void prog_version_msg(void)>

Emits a program version message, then terminates the program with a return
code of C<EXIT_SUCCESS>. This message consists of the program's name and
version (if they have been supplied).

=cut

*/

void prog_version_msg(void)
{
	char buf[MSG_SIZE];

	if (locker_rdlock(g.locker))
		exit(EXIT_FAILURE);

	if (g.name && g.version)
		snprintf(buf, MSG_SIZE, "%s-%s\n", g.name, g.version);
	else if (g.name)
		snprintf(buf, MSG_SIZE, "%s\n", g.name);
	else if (g.version)
		snprintf(buf, MSG_SIZE, "%s\n", g.version);
	else
		*buf = nul;

	if (locker_unlock(g.locker))
		exit(EXIT_FAILURE);

	msg("%s", buf);
	exit(EXIT_SUCCESS);
}

/*

=item C<const char *prog_basename(const char *path)>

Returns the filename part of C<path>. On error, returns C<null> with
C<errno> set appropriately.

=cut

*/

const char *prog_basename(const char *path)
{
	const char *name;

	if (!path)
		return set_errnull(EINVAL);

	return (name = strrchr(path, PATH_SEP)) ? (name + 1) : path;
}

/*

=item C<extern Options prog_options_table[1]>

Contains the syntax, semantics and descriptions of some options that are
available to all programs that use I<libslack>. These options are:

=over 4

=item C<-h>, C<--help>

Print a help message then exit

=item C<-V>, C<--version>

Print a version message then exit

=item C<-v>I<[level]>, C<--verbose>I<[=level]>

Set the verbosity level (Defaults to 1 if I<level> is not supplied)

=item C<-d>I<[level]>, C<--debug>I<[=level]>

Set the debugging level (Defaults to 1 if I<level> is not supplied)

=back

If your program supports no other options than these, C<prog_options_table>
can be passed directly to I<prog_set_options(3)>. Otherwise,
C<prog_options_table> should be assigned to the C<parent> field of the
C<Options> structure that will be passed to I<prog_set_options(3)>.

=cut

*/

static void handle_verbose_option(int *arg)
{
	prog_set_verbosity_level(arg ? *arg : 1);
}

#ifndef NDEBUG
static void handle_debug_option(int *arg)
{
	prog_set_debug_level(arg ? *arg : 1);
}
#endif

static Option prog_optab[] =
{
	{
		"help", 'h', NULL, "Print a help message then exit",
		no_argument, OPT_NONE, OPT_FUNCTION, NULL, (func_t *)prog_help_msg
	},
	{
		"version", 'V', NULL, "Print a version message then exit",
		no_argument, OPT_NONE, OPT_FUNCTION, NULL, (func_t *)prog_version_msg
	},
	{
		"verbose", 'v', "level", "Set the verbosity level",
		optional_argument, OPT_INTEGER, OPT_FUNCTION, NULL, (func_t *)handle_verbose_option
	},
#ifndef NDEBUG
	{
		"debug", 'd', "level", "Set the debugging level",
		optional_argument, OPT_INTEGER, OPT_FUNCTION, NULL, (func_t *)handle_debug_option
	},
#endif
	{
		NULL, nul, NULL, NULL, 0, 0, 0, NULL, NULL
	}
};

Options prog_options_table[1] = {{ NULL, prog_optab }};

/*

C<opt_convert(Options *options)>

Creates and returns a flat table of option structs from C<options>. The
resulting array is for use with I<GNU getopt_long(3)>. It is the caller's
responsibility to deallocate the returned memory with I<free(3)>,
I<mem_release(3)>, or I<mem_destroy(3)>. It is strongly recommended to use
I<mem_destroy(3)>, because it also sets the pointer variable to C<null>. On
error, returns C<null> with C<errno> set appropriately.

*/

static option *opt_convert(Options *options)
{
	Options *opts;
	size_t size = 0;
	size_t i;
	option *ret;
	int index = 0;

	for (opts = options; opts; opts = opts->parent)
		for (i = 0; opts->options[i].name; ++i)
			++size;

	if (!(ret = mem_create(size + 1, option)))
		return NULL;

	for (opts = options; opts; opts = opts->parent)
	{
		int i;

		for (i = 0; opts->options[i].name; ++i, ++index)
		{
			ret[index].name = (char *)opts->options[i].name;
			ret[index].has_arg = opts->options[i].has_arg;
			ret[index].flag = NULL;
			ret[index].val = 0;
		}
	}

	memset(ret + index, 0, sizeof(option));

	return ret;
}

/*

C<opt_optstring(Options *options)>

Creates and returns a string containing all of the short option names from
C<options>. The resulting string is for use with I<GNU getopt_long(3)>. It
is the caller's responsibility to deallocate the returned memory with
I<free(3)>, I<mem_release(3)>, or I<mem_destroy(3)>. It is strongly
recommended to use I<mem_destroy(3)>, because it also sets the pointer
variable to C<null>. On error, returns C<null> with C<errno> set
appropriately.

*/

static char *opt_optstring(Options *options)
{
	Options *opts;
	size_t size = 0;
	size_t i;
	char *optstring;
	char *p;

	for (opts = options; opts; opts = opts->parent)
		for (i = 0; opts->options[i].name; ++i)
			if (opts->options[i].short_name)
				++size;

	if (!(p = optstring = mem_create((size * 3) + 1, char)))
		return NULL;

	for (opts = options; opts; opts = opts->parent)
	{
		int i;

		for (i = 0; opts->options[i].name; ++i)
		{
			if (opts->options[i].short_name)
			{
				char short_name = opts->options[i].short_name;

				if (short_name == '?')
					short_name = '\001';

				*p++ = short_name;

				switch (opts->options[i].has_arg)
				{
					case optional_argument: *p++ = ':';
					case required_argument: *p++ = ':';
				}
			}
		}
	}

	*p = nul;

	return optstring;
}

/*

C<int int_arg(const char *argument)>

Parse and return the number in C<argument>. Uses I<strtol(3)> with base
C<0>. Also, if C<argument> is not a number at all, or it contains trailing
text, sets C<errno = EDOM> and returns C<0>. If C<argument> is out of
integer range, sets C<errno = ERANGE> and returns C<INT_MAX> or C<INT_MIN>.

*/

static int int_arg(const char *argument)
{
	char *endptr = NULL;
	long val = strtol(argument, &endptr, 0);

	if (val > INT_MAX)
		return errno = ERANGE, INT_MAX;

	if (val < INT_MIN)
		return errno = ERANGE, INT_MIN;

	if (endptr == argument || *endptr != '\0')
		return errno = EDOM, 0;

	return (int)val;
}

/*

C<void opt_action(Options *options, int rc, int longindex, const char *argument)>

Performs the action associated with the option in C<options> when I<GNU
getopt_long(3)> returned C<rc> or C<longindex>. C<argument> is a pointer to
an C<int> or a C<char *>. See I<opt_process(3)> for details.

*/

static void opt_action(Options *options, int rc, int longindex, const char *argument)
{
	Option *option;
	int i = -1;

	if (rc != 0 && longindex == -1) /* Short option */
	{
		for (; options; options = options->parent)
		{
			for (i = 0; options->options[i].name; ++i)
				if (options->options[i].short_name == rc)
					break;

			if (options->options[i].short_name == rc)
				break;
		}
	}
	else if (rc == 0 && longindex != -1) /* Long option */
	{
		for (i = 0; options; options = options->parent)
		{
			for (i = 0; longindex && options->options[i].name; ++i)
				--longindex;

			if (!options->options[i].name)
				continue;

			if (longindex == 0)
				break;
		}
	}
	else
		return;

	if (!options || i == -1)
		return;

	option = options->options + i;

	if (option->has_arg == required_argument && !argument)
		return;

	if (option->has_arg == no_argument && argument)
		return;

	if (argument)
	{
		switch (option->arg_type)
		{
			case OPT_NONE:
				break;

			case OPT_INTEGER:
			{
				switch (option->action)
				{
					case OPT_NOTHING:
						break;

					case OPT_VARIABLE:
						*(int *)option->object = int_arg(argument);
						break;

					case OPT_FUNCTION:
					{
						int arg = int_arg(argument);

						if (option->has_arg == required_argument)
							((opt_action_int_t *)option->function)(arg);
						else
							((opt_action_optional_int_t *)option->function)(&arg);

						break;
					}
				}

				break;
			}

			case OPT_STRING:
			{
				switch (option->action)
				{
					case OPT_NOTHING:
						break;

					case OPT_VARIABLE:
						*(const char **)option->object = argument;
						break;

					case OPT_FUNCTION:
						((opt_action_string_t *)option->function)(argument);
						break;
				}

				break;
			}
		}
	}
	else
	{
		switch (option->action)
		{
			case OPT_NOTHING:
				break;

			case OPT_VARIABLE:
				if (option->arg_type != OPT_STRING)
					++*(int *)option->object;
				break;

			case OPT_FUNCTION:
				if (option->action == optional_argument)
					((opt_action_optional_int_t *)option->function)(NULL);
				else
					((opt_action_none_t *)option->function)();
				break;
		}
	}
}

/*

=item C<int opt_process(int argc, char **argv, Options *options, char *msgbuf, size_t bufsize)>

Parses C<argv> for options specified in C<options>. Uses I<GNU
getopt_long(3)>. As each option is encountered, its corresponding action is
performed. On success, returns C<optind>. On error, returns C<-1> with
C<errno> set appropriately.

The following table shows the actions that are applied to an option's
C<object> or C<function> based on its C<has_arg>, C<arg_type> and
C<arg_action> attributes and whether or not an argument is present.

 has_arg           arg_type    arg_action   optarg action
 ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~ ~~~~~~~~~~~~ ~~~~~~ ~~~~~~
 required_argument OPT_INTEGER OPT_VARIABLE yes    *object = strtol(argument)
 required_argument OPT_STRING  OPT_VARIABLE yes    *object = argument
 required_argument OPT_INTEGER OPT_FUNCTION yes    function(strtol(argument))
 required_argument OPT_STRING  OPT_FUNCTION yes    function(argument)

 optional_argument OPT_INTEGER OPT_VARIABLE yes    *object = strtol(argument)
 optional_argument OPT_STRING  OPT_VARIABLE yes    *object = argument
 optional_argument OPT_INTEGER OPT_FUNCTION yes    function(&strtol(argument))
 optional_argument OPT_STRING  OPT_FUNCTION yes    function(argument)

 optional_argument OPT_INTEGER OPT_VARIABLE no     ++*object
 optional_argument OPT_STRING  OPT_VARIABLE no     nothing
 optional_argument OPT_INTEGER OPT_FUNCTION no     function(NULL)
 optional_argument OPT_STRING  OPT_FUNCTION no     function(NULL)

 no_argument       OPT_NONE    OPT_VARIABLE no     ++*object
 no_argument       OPT_NONE    OPT_FUNCTION no     function()

Note that integer option arguments may be expressed in octal, decimal or
hexadecimal. There may be leading whitespace but no trailing text of any
kind. Overflow and underflow are also treated as errors.

=cut

*/

int opt_process(int argc, char **argv, Options *options, char *msgbuf, size_t bufsize)
{
	option *long_options;
	char *optstring;

	if (!(long_options = opt_convert(options)))
		return optind;

	if (!(optstring = opt_optstring(options)))
	{
		mem_release(long_options);
		return optind;
	}

	for (;;)
	{
		int longindex = -1;
		int rc;

		if ((rc = getopt_long(argc, argv, optstring, long_options, &longindex)) == EOF)
			break;

		if (rc == '?' || rc == ':')
		{
			mem_release(long_options);
			mem_release(optstring);
			return set_errno(EINVAL);
		}

		if (rc == '\001')
			rc = '?';

		errno = 0;
		opt_action(options, rc, longindex, optarg);
		if (errno == ERANGE || errno == EDOM)
		{
			if (msgbuf)
			{
				char optname[256];

				if (rc != 0 && longindex == -1) /* Short option */
					snprintf(optname, 256, "-%c", rc);
				else if (rc == 0 && longindex != -1) /* Long option */
					snprintf(optname, 256, "--%s", long_options[longindex].name);

				snprintf(msgbuf, bufsize, "%s: invalid %s argument: %s", *argv, optname, (errno == EDOM) ? "not an integer" : "integer out of range");
			}

			mem_release(long_options);
			mem_release(optstring);
			return -1;
		}
	}

	mem_release(long_options);
	mem_release(optstring);
	return optind;
}

/*

=item C<char *opt_usage(char *buf, size_t size, Options *options)>

Writes a usage message into C<buf> that displays the names, syntax and
descriptions of all options in C<options>. C<options> is traversed depth
first so the chunk with the C<null> C<parent> appears first. Each chunk of
options is preceded by a blank line. No more than C<size> bytes are
written, including the terminating C<nul> character. The string returned
will look like:

      -a, --aaa       -- no-arg/var option
      -b, --bbb       -- no-arg/func option
      -c, --ccc=arg   -- int-arg/var option
      -d, --ddd=arg   -- int-arg/func option
      -e, --eee=arg   -- str-arg/var option
      -f, --fff=arg   -- str-arg/func option
      -g, --ggg[=arg] -- opt-int-arg/var option
      -h, --hhh[=arg] -- opt-str-arg/func option with one of those really,
                         really, really, long descriptions that goes on and on
                         and even contains a really long url:
                         http://www.zip.com.au/~joe/fairly/long/url/index.html
                         would you believe? Here it is again!
                         http://www.zip.com.au/~joe/fairly/long/url/index.html#just_kidding

=cut

*/

char *opt_usage(char *buf, size_t size, Options *options)
{
	const int total_width = 80;
	const char * const indent = "      ";
	const size_t indent_width = strlen(indent);
	const char * const leader = " - ";
	const size_t leader_width = strlen(leader);

	Options *opts;
	Options **stack;
	size_t max_width = 0;
	size_t depth = 0;
	size_t length = 0;
	size_t remainder = 0;
	int i;

	/* Determine the room needed by the longest option */

	for (opts = options; opts; opts = opts->parent, ++depth)
	{
		for (i = 0; opts->options[i].name; ++i)
		{
			Option *opt = opts->options + i;
			size_t width = strlen(opt->name);

			if (opt->argname)
			{
				width += 1 + strlen(opt->argname);

				if (opt->has_arg == optional_argument)
					width += 2;
			}

			if (width > max_width)
				max_width = width;
		}
	}

	/* Include room for "-o, --" */

	max_width += 6;

	/* Remember all options for reverse traversal */

	if (!(stack = mem_create(depth, Options *)))
		return NULL;

	for (opts = options, i = 0; opts; opts = opts->parent)
		stack[i++] = opts;

	/* Process options parent first */

	while (depth--)
	{
		opts = stack[depth];

		snprintf(buf + length, size - length, "\n");
		length = strlen(buf);

		for (i = 0; opts->options[i].name; ++i)
		{
			Option *opt = opts->options + i;
			char help[BUFSIZ];
			const char *desc;
			const char *next = NULL;
			size_t desc_length;
			size_t help_length;

			/* Produce the left hand side: syntax */

			snprintf(help, BUFSIZ, "%s%c%c%c --%s",
				indent,
				opt->short_name ? '-' : ' ',
				opt->short_name ? opt->short_name : ' ',
				opt->short_name ? ',' : ' ',
				opt->name
			);

			help_length = strlen(help);

			if (opt->argname)
			{
				int optional = (opt->has_arg == optional_argument);

				snprintf(help + help_length, BUFSIZ - help_length, "%s%s%s",
					optional ? "[=" : "=",
					opt->argname,
					optional ? "]" : ""
				);

				help_length = strlen(help);
			}

			snprintf(help + help_length, BUFSIZ - help_length, "%*s%s", (int)(max_width - help_length + indent_width), "", leader);
			help_length = strlen(help);
			remainder = total_width - help_length;

			/* Produce the right hand side: descriptions */

			for (desc = opt->desc; (desc_length = strlen(desc)) > remainder; desc = next)
			{
				/* Indent subsequent description lines */
				if (desc != opt->desc)
				{
					snprintf(help + help_length, BUFSIZ - help_length, "%*s%*.*s", (int)(indent_width + max_width), "", (int)leader_width, (int)leader_width, "");
					help_length = strlen(help);
				}

				/* Look for last space that will fit on this line */

				next = desc + remainder;

				for (; next > desc && !isspace((int)(unsigned int)*next); --next)
				{}

				/* If none (word too long), look forward for end of word */

				if (next == desc)
				{
					while (isspace((int)(unsigned int)*next))
						++next;

					next = strchr(desc, ' ');

					if (!next)
						next = desc + desc_length;
				}

				/* Ignore any extra whitespace to the left */

				while (next != desc && isspace((int)(unsigned int)next[-1]))
					--next;

				/* Add one line of description */

				snprintf(help + help_length, BUFSIZ - help_length, "%*.*s\n", (int)(next - desc), (int)(next - desc), desc);
				help_length = strlen(help);

				/* Ignore any extra whitespace to the right */

				while (isspace((int)(unsigned int)*next))
					++next;
			}

			/* Add the last line of description */

			if (desc_length)
			{
				/* Indent the last line if it's not also the first line */

				if (desc != opt->desc)
				{
					snprintf(help + help_length, BUFSIZ - help_length, "%*s%*.*s", (int)(indent_width + max_width), "", (int)leader_width, (int)leader_width, "");
					help_length = strlen(help);
				}

				snprintf(help + help_length, BUFSIZ - help_length, "%s\n", desc);
			}

			/* Add this option's help to the whole usage message */

			snprintf(buf + length, size - length, "%s", help);
			length = strlen(buf);
		}
	}

	mem_release(stack);

	return buf;
}

/*

=back

=head1 ERRORS

On error, C<errno> is set either by an underlying function, or as follows:

=over 4

=item C<EINVAL>

Arguments are C<null> or invalid.

=item C<EDOM>

An integer option argument string failed to be parsed completely.

=item C<ERANGE>

An integer option argument string was out of integer range. In this case,
C<INT_MAX> or C<INT_MIN> is used.

=back

=head1 MT-Level

I<MT-Disciplined> - prog functions

By default, this module is not threadsafe, because most programs are
single-threaded, and synchronisation doesn't come for free. For
multi-threaded programs, use I<prog_set_locker(3)> to synchronise access to
this module's data, before creating the threads that will access it.

Unsafe - opt functions

I<opt_process(3)> and I<opt_usage(3)> must only be used in the main thread.
They should not be needed anywhere else. Normally, they would not be called
directly at all.

=head1 EXAMPLE

The following program:

 #include <slack/std.h>
 #include <slack/prog.h>

 char *name = NULL;
 int minimum = 0;
 int reverse = 0;

 void setup_syslog(char *facility) {}
 void parse_config(char *path) {}

 Option example_optab[] =
 {
     {
         "name", 'n', "name", "Provide a name",
         required_argument, OPT_STRING, OPT_VARIABLE, &name, NULL
     },
     {
         "minimum", 'm', "minval", "Ignore everything below minimum",
         required_argument, OPT_INTEGER, OPT_VARIABLE, &minimum, NULL
     },
     {
         "syslog", 's', "facility.priority", "Send client's output to syslog (defaults to local0.debug)",
         optional_argument, OPT_STRING, OPT_FUNCTION, NULL, (func_t *)setup_syslog
     },
     {
         "reverse", 'r', NULL, "Reverse direction",
         no_argument, OPT_NONE, OPT_VARIABLE, &reverse, NULL
     },
     {
         "config", 'c', "path", "Specify the configuration file",
         required_argument, OPT_STRING, OPT_FUNCTION, NULL, (func_t *)parse_config
     },
     {
         NULL, '\0', NULL, NULL, 0, 0, 0, NULL
     }
 };

 Options options[1] = {{ prog_options_table, example_optab }};

 int main(int ac, char **av)
 {
     int a;
     prog_init();
     prog_set_name("example");
     prog_set_syntax("[options] arg...");
     prog_set_options(options);
     prog_set_version("1.0");
     prog_set_date("20230824");
     prog_set_author("raf <raf@raf.org>");
     prog_set_contact(prog_author());
     prog_set_url("https://libslack.org");
     prog_set_legal("This software is released under the terms of the GPL.\n");
     prog_set_desc("This program is an example of the prog module.\n");

     for (a = prog_opt_process(ac, av); a < ac; ++a)
         msg("av[%d] = \"%s\"\n", a, av[a]);

     return EXIT_SUCCESS;
 }

will behave like:

 $ example --version # to stdout
 example-1.0

 $ example --help # to stdout
 usage: example [options] arg...
 options:

       -h, --help                       - Print a help message then exit
       -V, --version                    - Print a version message then exit
       -v, --verbose[=level]            - Set the verbosity level
       -d, --debug[=level]              - Set the debugging level

       -n, --name=name                  - Provide a name
       -m, --minimum=minval             - Ignore everything below minimum
       -s, --syslog[=facility.priority] - Send client's output to syslog
                                          (defaults to local0.debug)
       -r, --reverse                    - Reverse direction
       -c, --config=path                - Specify the configuration file

 This program is an example of the prog module.

 Name: example
 Version: 1.0
 Date: 20230824
 Author: raf <raf@raf.org>
 URL: https://libslack.org

 This software is released under the terms of the GPL.

 Report bugs to raf <raf@raf.org>

 $ example -x # to stderr
 ./example: invalid option -- x
 usage: example [options] arg...
 options:

       -h, --help                       - Print a help message then exit
       -V, --version                    - Print a version message then exit
       -v, --verbose[=level]            - Set the verbosity level
       -d, --debug[=level]              - Set the debugging level

       -n, --name=name                  - Provide a name
       -m, --minimum=minval             - Ignore everything below minimum
       -s, --syslog[=facility.priority] - Send client's output to syslog
                                          (defaults to local0.debug)
       -r, --reverse                    - Reverse direction
       -c, --config=path                - Specify the configuration file

 $ example a b c # to stdout
 av[1] = "a"
 av[2] = "b"
 av[3] = "c"

=head1 SEE ALSO

I<libslack(3)>,
I<getopt_long(3)>,
I<err(3)>,
I<msg(3)>,
I<prop(3)>,
I<sig(3)>,
I<locker(3)>

=head1 AUTHOR

20230824 raf <raf@raf.org>

=cut

*/

#endif

#ifdef TEST

#include <fcntl.h>
#include <sys/wait.h>

int verify(int i, const char *name, const char *result, const char *prog_name, const char *type)
{
	char buf[BUFSIZ];
	char result_buf[BUFSIZ];
	int fd;
	ssize_t bytes;
	char *q;

	if ((fd = open(name, O_RDONLY)) == -1)
	{
		printf("Test%d: failed to output message\n", i);
		return 1;
	}

	memset(buf, 0, BUFSIZ);
	bytes = read(fd, buf, BUFSIZ);
	close(fd);
	unlink(name);

	if (bytes == -1)
	{
		printf("Test%d: failed to read output (%s)\n", i, strerror(errno));
		return 1;
	}

	snprintf(result_buf, BUFSIZ, result, prog_name, prog_name);
	/* Replace ` with ' as getopt seems to use either */
	while ((q = strchr(buf, '`')))
		*q = '\'';

	if (strcmp(buf, result_buf))
	{
		printf("Test%d: incorrect %s:\nshould be:\n%s\nwas:\n%s\n", i, type, result_buf, buf);
		return 1;
	}

	return 0;
}

int intvar_a;
int intvar_b;
void nonefunc_b(void) { ++intvar_b; }
int intvar_c;
int intvar_d;
void intfunc_d(int arg) { intvar_d = arg; }
const char *strvar_e;
const char *strvar_f;
void strfunc_f(const char *arg) { strvar_f = arg; }
int optintvar_g;
int optintvar_h;
void optintfunc_h(int *arg) { if (arg) optintvar_h = *arg; else ++optintvar_h; }
const char *optstrvar_i;
const char *optstrvar_j;
void optstrfunc_j(const char *arg) { if (arg) optstrvar_j = arg; }

static Option optab[] =
{
	{ "aaa", 'a', NULL,  "no-arg/var option", no_argument, OPT_NONE, OPT_VARIABLE, &intvar_a, NULL },
	{ "bbb", 'b', NULL,  "no-arg/func option", no_argument, OPT_NONE, OPT_FUNCTION, NULL, (func_t *)nonefunc_b },
	{ "ccc", nul, "int", "int-arg/var option", required_argument, OPT_INTEGER, OPT_VARIABLE, &intvar_c, NULL },
	{ "ddd", 'd', "int", "int-arg/func option", required_argument, OPT_INTEGER, OPT_FUNCTION, NULL, (func_t *)intfunc_d },
	{ "eee", 'e', "str", "str-arg/var option", required_argument, OPT_STRING, OPT_VARIABLE, &strvar_e, NULL },
	{ "fff", nul, "str", "str-arg/func option", required_argument, OPT_STRING, OPT_FUNCTION, NULL, (func_t *)strfunc_f },
	{ "ggg", 'g', "int", "opt-int-arg/var option", optional_argument, OPT_INTEGER, OPT_VARIABLE, &optintvar_g, NULL },
	{ "hhh", 'h', "int", "opt-int-arg/func option", optional_argument, OPT_INTEGER, OPT_FUNCTION, NULL, (func_t *)optintfunc_h },
	{ "iii", 'i', "str", "opt-str-arg/var option", optional_argument, OPT_STRING, OPT_VARIABLE, &optstrvar_i, NULL },
	{ "jjj", 'j', "str", "opt-str-arg/func option with one of those really, really, really, long descriptions that goes on and on and even contains a really long url: http://www.zip.com.au/~joe/fairly/long/url/index.html would you believe? Here it is again! http://www.zip.com.au/~joe/fairly/long/url/index.html#just_kidding", optional_argument, OPT_STRING, OPT_FUNCTION, NULL, (func_t *)optstrfunc_j },
	{ NULL, nul, NULL, NULL, 0, 0, 0, NULL, NULL }
};

static Options options[1] = {{ NULL, optab }};

int main(int ac, char **av)
{
	int oargc = 26;
	char *oargv[] = /* Note: optstrvar with no argument (i.e. -i) does nothing  */
	{
		"test.opt", "-ab", "--aaa", "--bbb", "--ccc", "42",
		"-d", "37", "--ddd=51", "-e", "eee", "--eee", "123",
		"--fff", "fff", "--ggg=4", "-g8", "-h3", "-h", "--hhh",
		"-ifish", "--iii=carp", "-i", "--jjj=jjj",
		"remaining", "arguments", NULL
	};
	char buf[BUFSIZ];
	int rc;
	const char * const usage =
		"\n"
		"      -a, --aaa       - no-arg/var option\n"
		"      -b, --bbb       - no-arg/func option\n"
		"          --ccc=int   - int-arg/var option\n"
		"      -d, --ddd=int   - int-arg/func option\n"
		"      -e, --eee=str   - str-arg/var option\n"
		"          --fff=str   - str-arg/func option\n"
		"      -g, --ggg[=int] - opt-int-arg/var option\n"
		"      -h, --hhh[=int] - opt-int-arg/func option\n"
		"      -i, --iii[=str] - opt-str-arg/var option\n"
		"      -j, --jjj[=str] - opt-str-arg/func option with one of those really,\n"
		"                        really, really, long descriptions that goes on and on\n"
		"                        and even contains a really long url:\n"
		"                        http://www.zip.com.au/~joe/fairly/long/url/index.html\n"
		"                        would you believe? Here it is again!\n"
		"                        http://www.zip.com.au/~joe/fairly/long/url/index.html#just_kidding\n";

	const char *prog_name;
	char out_name[32];
	char err_name[32];
	int tests = 3;
	int argc = 3;
	char *argv[3][4] =
	{
		{ "prog.test", "--debug=4", "--help", NULL },
		{ "prog.test", "--debug=1", "--version", NULL },
		{ "prog.test", "--debug=1", "--invalid", NULL }
	};
	char *results[3][2] =
	{
		/* --help output */
		{
			/* stdout */
			"usage: %s [options]\n"
			"options:\n"
			"\n"
			"      -h, --help            - Print a help message then exit\n"
			"      -V, --version         - Print a version message then exit\n"
			"      -v, --verbose[=level] - Set the verbosity level\n"
			"      -d, --debug[=level]   - Set the debugging level\n"
			"\n"
			"This program tests the prog module.\n"
			"\n"
			"Name: %s\n"
			"Version: 1.0\n"
			"Date: 20230824\n"
			"Author: raf <raf@raf.org>\n"
			"Vendor: A Software Vendor\n"
			"URL: https://libslack.org/test\n"
			"\n"
			"This software is released under the terms of the GPL.\n"
			"\n"
			"Report bugs to raf <raf@raf.org>\n",

			/* stderr */
			""
		},

		/* --version output */

		{
			/* stdout */
			"%s-1.0\n",

			/* stderr */
			""
		},

		/* --invalid output */
		{
			/* stdout */
			"",

			/* stderr */
			"%s: unrecognized option '--invalid'\n"
			"usage: %s [options]\n"
			"options:\n"
			"\n"
			"      -h, --help            - Print a help message then exit\n"
			"      -V, --version         - Print a version message then exit\n"
			"      -v, --verbose[=level] - Set the verbosity level\n"
			"      -d, --debug[=level]   - Set the debugging level\n"
		}
	};

	int errors = 0;
	int i;

	if (ac == 2 && !strcmp(av[1], "help"))
	{
		printf("usage: %s\n", *av);
		return EXIT_SUCCESS;
	}

	printf("Testing: %s\n", "prog");

	rc = opt_process(oargc, oargv, options, NULL, 0);
	if (rc != 24)
		++errors, printf("Test1: rc = %d (not 24, fail)\n", rc);
	if (intvar_a != 2)
		++errors, printf("Test2: intvar_a = %d (not 2, fail)\n", intvar_a);
	if (intvar_b != 2)
		++errors, printf("Test3: intvar_b = %d (not 2, fail)\n", intvar_b);
	if (intvar_c != 42)
		++errors, printf("Test4: intvar_c = %d (not 42, fail)\n", intvar_c);
	if (intvar_d != 51)
		++errors, printf("Test5: intvar_d = %d (not 51, fail)\n", intvar_d);
	if (strcmp(strvar_e ? strvar_e : "NULL", "123"))
		++errors, printf("Test6: strvar_e = '%s' (not '123', fail)\n", strvar_e ? strvar_e : "NULL");
	if (strcmp(strvar_f ? strvar_f : "NULL", "fff"))
		++errors, printf("Test7: strvar_f = '%s' (not 'fff', fail)\n", strvar_f ? strvar_f : "NULL");
	if (optintvar_g != 8)
		++errors, printf("Test8: optintvar_g = %d (not 8, fail)\n", optintvar_g);
	if (optintvar_h != 5)
		++errors, printf("Test9: optintvar_h = %d (not 5, fail)\n", optintvar_h);
	if (!optstrvar_i)
		optstrvar_i = "NULL";
	if (strcmp(optstrvar_i, "carp"))
		++errors, printf("Test10: optstrvar_i = '%s' (not 'carp', fail)\n", optstrvar_i);
	if (!optstrvar_j)
		optstrvar_j = "NULL";
	if (strcmp(optstrvar_j, "jjj"))
		++errors, printf("Test11: optstrvar_j = '%s' (not 'jjj', fail)\n", optstrvar_j);

	opt_usage(buf, BUFSIZ, options);
	if (strcmp(buf, usage))
		++errors, printf("Test12: opt_usage() produced incorrect output:\nshould be:\n%s\nwas:\n%s\n", usage, buf);

	optind = 0;

	prog_name = prog_basename(*av);
	argv[0][0] = argv[1][0] = argv[2][0] = (char *)prog_name;

	prog_init();
	prog_set_name(prog_name);
	prog_set_syntax("[options]");
	prog_set_options(prog_options_table);
	prog_set_version("1.0");
	prog_set_date("20230824");
	prog_set_author("raf <raf@raf.org>");
	prog_set_contact("raf <raf@raf.org>");
	prog_set_vendor("A Software Vendor");
	prog_set_url("https://libslack.org/test");
	prog_set_legal("This software is released under the terms of the GPL.\n");
	prog_set_desc("This program tests the prog module.\n");

	for (i = 0; i < tests; ++i)
	{
		pid_t pid;

		snprintf(out_name, 32, "prog.out.%d", i);
		snprintf(err_name, 32, "prog.err.%d", i);

		switch (pid = fork())
		{
			case 0:
			{
				freopen(out_name, "a", stdout);
				freopen(err_name, "a", stderr);

				return (prog_opt_process(argc, argv[i]) != argc);
			}

			case -1:
			{
				++errors, printf("Test%d: failed to perform test - fork() failed (%s)\n", 12 + i + 1, strerror(errno));
				continue;
			}

			default:
			{
				int status;

				if (waitpid(pid, &status, 0) == -1)
				{
					++errors, printf("Test%d: failed to wait for test - waitpid(%d) failed (%s)\n", 12 + i + 1, (int)pid, strerror(errno));
					continue;
				}

				if (WIFSIGNALED(status))
					++errors, printf("Test%d: failed: received signal %d\n", 12 + i + 1, WTERMSIG(status));

				if (i != 2 && WIFEXITED(status) && WEXITSTATUS(status) != EXIT_SUCCESS)
					++errors, printf("Test%d: failed: exit status %d\n", 12 + i + 1, WEXITSTATUS(status));
			}
		}

		errors += verify(12 + i + 1, out_name, results[i][0], prog_name, "stdout");
		errors += verify(12 + i + 1, err_name, results[i][1], prog_name, "stderr");
	}

	if (errors)
		printf("%d/%d tests failed\n", errors, 12 + tests * 2);
	else
		printf("All tests passed\n");

	return (errors == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}

#endif

/* vi:set ts=4 sw=4: */