summaryrefslogtreecommitdiff
path: root/src/server/__init__.py
blob: fc632cf9665b62b3e14d494b64d099cb9d610618 (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
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
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
from __future__ import print_function, division, absolute_import

import os
import sys
import shutil
import subprocess
import optparse
import math
import signal
import threading
import atexit
import types
import re
import pprint
import time
import traceback
import locale
import inspect
import getpass
import tempfile
import copy
import posixpath

try:
    import Queue as queue
except ImportError:
    import queue

from . import apxs_config

_py_version = '%s%s' % sys.version_info[:2]
_py_soabi = ''
_py_soext = '.so'
_py_dylib = ''

try:
    import sysconfig
    import distutils.sysconfig

    _py_soabi = sysconfig.get_config_var('SOABI')

    _py_soext = sysconfig.get_config_var('EXT_SUFFIX')

    if _py_soext is None:
        _py_soext = sysconfig.get_config_var('SO')

    if (sysconfig.get_config_var('WITH_DYLD') and
            sysconfig.get_config_var('LIBDIR') and
            sysconfig.get_config_var('LDLIBRARY')):
        _py_dylib = posixpath.join(sysconfig.get_config_var('LIBDIR'),
                sysconfig.get_config_var('LDLIBRARY'))
        if not os.path.exists(_py_dylib):
            _py_dylib = ''

except ImportError:
    pass

MOD_WSGI_SO = 'mod_wsgi-py%s%s' % (_py_version, _py_soext)
MOD_WSGI_SO = posixpath.join(posixpath.dirname(__file__), MOD_WSGI_SO)

if not os.path.exists(MOD_WSGI_SO) and _py_soabi:
    MOD_WSGI_SO = 'mod_wsgi-py%s.%s%s' % (_py_version, _py_soabi, _py_soext)
    MOD_WSGI_SO = posixpath.join(posixpath.dirname(__file__), MOD_WSGI_SO)

if not os.path.exists(MOD_WSGI_SO) and os.name == 'nt':
    MOD_WSGI_SO = 'mod_wsgi%s' % distutils.sysconfig.get_config_var('EXT_SUFFIX')
    MOD_WSGI_SO = os.path.join(os.path.dirname(__file__), MOD_WSGI_SO)
    MOD_WSGI_SO = MOD_WSGI_SO.replace('\\', '/')

def where():
    return MOD_WSGI_SO

def default_run_user():
    if os.name == 'nt':
        return '#0'

    try:
        import pwd
        uid = os.getuid()
        return pwd.getpwuid(uid).pw_name
    except KeyError:
        return '#%d' % uid

def default_run_group():
    if os.name == 'nt':
        return '#0'

    try:
        import pwd
        uid = os.getuid()
        entry = pwd.getpwuid(uid)
    except KeyError:
        return '#%d' % uid

    try:
        import grp
        gid = entry.pw_gid
        return grp.getgrgid(gid).gr_name
    except KeyError:
        return '#%d' % gid

def find_program(names, default=None, paths=[]):
    for name in names:
        for path in os.environ['PATH'].split(':') + paths:
            program = posixpath.join(path, name)
            if os.path.exists(program):
                return program
    return default

def find_mimetypes():
    if os.name == 'nt':
        return posixpath.join(posixpath.dirname(posixpath.dirname(
                apxs_config.HTTPD)), 'conf', 'mime.types')
    else:
        import mimetypes
        for name in mimetypes.knownfiles:
            if os.path.exists(name):
                return name
        else:
            return '/dev/null'

SHELL = find_program(['bash', 'sh'], ['/usr/local/bin'])

APACHE_GENERAL_CONFIG = """
<IfModule !version_module>
LoadModule version_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_version.so'
</IfModule>

ServerName %(host)s
ServerRoot '%(server_root)s'
PidFile '%(pid_file)s'

<IfVersion >= 2.4>
DefaultRuntimeDir '%(server_root)s'
</IfVersion>

ServerTokens ProductOnly
ServerSignature Off

<IfDefine !MOD_WSGI_MPM_ENABLE_WINNT_MODULE>
User ${MOD_WSGI_USER}
Group ${MOD_WSGI_GROUP}
</IfDefine>

<IfDefine MOD_WSGI_WITH_LISTENER_HOST>
Listen %(host)s:%(port)s
</IfDefine>
<IfDefine !MOD_WSGI_WITH_LISTENER_HOST>
Listen %(port)s
</IfDefine>

<IfVersion < 2.4>
LockFile '%(server_root)s/accept.lock'
</IfVersion>

<IfVersion >= 2.4>
<IfDefine MOD_WSGI_WITH_PHP5>
<IfModule !mpm_event_module>
<IfModule !mpm_worker_module>
<IfModule !mpm_prefork_module>
<IfDefine MOD_WSGI_MPM_EXISTS_PREFORK_MODULE>
LoadModule mpm_prefork_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_mpm_prefork.so'
</IfDefine>
</IfModule>
</IfModule>
</IfModule>
</IfDefine>
</IfVersion>

<IfVersion >= 2.4>
<IfModule !mpm_event_module>
<IfModule !mpm_worker_module>
<IfModule !mpm_prefork_module>
<IfDefine MOD_WSGI_MPM_ENABLE_EVENT_MODULE>
LoadModule mpm_event_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_mpm_event.so'
</IfDefine>
<IfDefine MOD_WSGI_MPM_ENABLE_WORKER_MODULE>
LoadModule mpm_worker_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_mpm_worker.so'
</IfDefine>
<IfDefine MOD_WSGI_MPM_ENABLE_PREFORK_MODULE>
LoadModule mpm_prefork_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_mpm_prefork.so'
</IfDefine>
</IfModule>
</IfModule>
</IfModule>
</IfVersion>

<IfDefine MOD_WSGI_WITH_HTTP2>
LoadModule http2_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_http2.so'
</IfDefine>

<IfVersion >= 2.4>
<IfModule !access_compat_module>
LoadModule access_compat_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_access_compat.so'
</IfModule>
<IfDefine !MOD_WSGI_MPM_ENABLE_WINNT_MODULE>
<IfModule !unixd_module>
LoadModule unixd_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_unixd.so'
</IfModule>
</IfDefine>
<IfModule !authn_core_module>
LoadModule authn_core_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_authn_core.so'
</IfModule>
<IfModule !authz_core_module>
LoadModule authz_core_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_authz_core.so'
</IfModule>
</IfVersion>

<IfModule !authz_host_module>
LoadModule authz_host_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_authz_host.so'
</IfModule>
<IfModule !mime_module>
LoadModule mime_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_mime.so'
</IfModule>
<IfModule !rewrite_module>
LoadModule rewrite_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_rewrite.so'
</IfModule>
<IfModule !alias_module>
LoadModule alias_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_alias.so'
</IfModule>
<IfModule !dir_module>
LoadModule dir_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_dir.so'
</IfModule>
<IfModule !env_module>
LoadModule env_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_env.so'
</IfModule>
<IfModule !headers_module>
LoadModule headers_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_headers.so'
</IfModule>
<IfModule !filter_module>
LoadModule filter_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_filter.so'
</IfModule>

<IfDefine MOD_WSGI_DIRECTORY_LISTING>
<IfModule !autoindex_module>
LoadModule autoindex_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_autoindex.so'
</IfModule>
</IfDefine>

<IfVersion >= 2.2.15>
<IfModule !reqtimeout_module>
LoadModule reqtimeout_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_reqtimeout.so'
</IfModule>
</IfVersion>

<IfDefine MOD_WSGI_COMPRESS_RESPONSES>
<IfModule !deflate_module>
LoadModule deflate_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_deflate.so'
</IfModule>
</IfDefine>

<IfDefine MOD_WSGI_AUTH_USER>
<IfModule !auth_basic_module>
LoadModule auth_basic_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_auth_basic.so'
</IfModule>
<IfModule !auth_digest_module>
LoadModule auth_digest_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_auth_digest.so'
</IfModule>
<IfModule !authz_user_module>
LoadModule authz_user_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_authz_user.so'
</IfModule>
</IfDefine>

<IfDefine MOD_WSGI_WITH_PROXY>
<IfModule !proxy_module>
LoadModule proxy_module ${MOD_WSGI_MODULES_DIRECTORY}/mod_proxy.so
</IfModule>
<IfModule !proxy_http_module>
LoadModule proxy_http_module ${MOD_WSGI_MODULES_DIRECTORY}/mod_proxy_http.so
</IfModule>
</IfDefine>

<IfModule mpm_prefork_module>
<IfDefine MOD_WSGI_WITH_PHP5>
<IfModule !php5_module>
Loadmodule php5_module '${MOD_WSGI_MODULES_DIRECTORY}/libphp5.so'
</IfModule>
AddHandler application/x-httpd-php .php
</IfDefine>
</IfModule>

<IfDefine MOD_WSGI_LOAD_PYTHON_DYLIB>
LoadFile '%(python_dylib)s'
</IfDefine>

LoadModule wsgi_module '%(mod_wsgi_so)s'

<IfDefine MOD_WSGI_SERVER_METRICS>
<IfModule !status_module>
LoadModule status_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_status.so'
</IfModule>
</IfDefine>

<IfDefine MOD_WSGI_CGID_SCRIPT>
<IfModule !cgid_module>
LoadModule cgid_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_cgid.so'
</IfModule>
</IfDefine>

<IfDefine MOD_WSGI_CGI_SCRIPT>
<IfModule !cgi_module>
LoadModule cgi_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_cgi.so'
</IfModule>
</IfDefine>

<IfVersion < 2.4>
DefaultType text/plain
</IfVersion>

TypesConfig '%(mime_types)s'

HostnameLookups Off
MaxMemFree 64
Timeout %(socket_timeout)s
ListenBacklog %(server_backlog)s

<IfDefine MOD_WSGI_WITH_HTTP2>
Protocols h2 h2c http/1.1
</IfDefine>

<IfVersion >= 2.2.15>
RequestReadTimeout %(request_read_timeout)s
</IfVersion>

LimitRequestBody %(limit_request_body)s

<Directory />
    AllowOverride None
<IfVersion < 2.4>
    Order deny,allow
    Deny from all
</IfVersion>
<IfVersion >= 2.4>
    Require all denied
</IfVersion>
</Directory>

WSGIPythonHome '%(python_home)s'

WSGIVerboseDebugging '%(verbose_debugging_flag)s'

<IfDefine !MOD_WSGI_MPM_ENABLE_WINNT_MODULE>
<IfDefine MOD_WSGI_WITH_SOCKET_PREFIX>
WSGISocketPrefix %(socket_prefix)s/wsgi
</IfDefine>
<IfDefine !MOD_WSGI_WITH_SOCKET_PREFIX>
WSGISocketPrefix %(server_root)s/wsgi
</IfDefine>
WSGISocketRotation Off
</IfDefine>

<IfDefine EMBEDDED_MODE>
MaxConnectionsPerChild %(maximum_requests)s
</IfDefine>

<IfDefine ORPHAN_INTERPRETER>
WSGIDestroyInterpreter Off
</IfDefine>
<IfDefine !ORPHAN_INTERPRETER>
WSGIDestroyInterpreter On
</IfDefine>

<IfDefine !ONE_PROCESS>
<IfDefine !EMBEDDED_MODE>
WSGIRestrictEmbedded On
<IfDefine MOD_WSGI_MULTIPROCESS>
WSGIDaemonProcess %(host)s:%(port)s \\
   display-name='%(daemon_name)s' \\
   home='%(working_directory)s' \\
   processes=%(processes)s \\
   threads=%(threads)s \\
   maximum-requests=%(maximum_requests)s \\
   python-path='%(python_path)s' \\
   python-eggs='%(python_eggs)s' \\
   lang='%(lang)s' \\
   locale='%(locale)s' \\
   listen-backlog=%(daemon_backlog)s \\
   queue-timeout=%(queue_timeout)s \\
   socket-timeout=%(socket_timeout)s \\
   connect-timeout=%(connect_timeout)s \\
   request-timeout=%(request_timeout)s \\
   inactivity-timeout=%(inactivity_timeout)s \\
   startup-timeout=%(startup_timeout)s \\
   deadlock-timeout=%(deadlock_timeout)s \\
   graceful-timeout=%(graceful_timeout)s \\
   eviction-timeout=%(eviction_timeout)s \\
   restart-interval=%(restart_interval)s \\
   cpu-time-limit=%(cpu_time_limit)s \\
   shutdown-timeout=%(shutdown_timeout)s \\
   send-buffer-size=%(send_buffer_size)s \\
   receive-buffer-size=%(receive_buffer_size)s \\
   header-buffer-size=%(header_buffer_size)s \\
   response-buffer-size=%(response_buffer_size)s \\
   response-socket-timeout=%(response_socket_timeout)s \\
   server-metrics=%(server_metrics_flag)s
</IfDefine>
<IfDefine !MOD_WSGI_MULTIPROCESS>
WSGIDaemonProcess %(host)s:%(port)s \\
   display-name='%(daemon_name)s' \\
   home='%(working_directory)s' \\
   threads=%(threads)s \\
   maximum-requests=%(maximum_requests)s \\
   python-path='%(python_path)s' \\
   python-eggs='%(python_eggs)s' \\
   lang='%(lang)s' \\
   locale='%(locale)s' \\
   listen-backlog=%(daemon_backlog)s \\
   queue-timeout=%(queue_timeout)s \\
   socket-timeout=%(socket_timeout)s \\
   connect-timeout=%(connect_timeout)s \\
   request-timeout=%(request_timeout)s \\
   inactivity-timeout=%(inactivity_timeout)s \\
   startup-timeout=%(startup_timeout)s \\
   deadlock-timeout=%(deadlock_timeout)s \\
   graceful-timeout=%(graceful_timeout)s \\
   eviction-timeout=%(eviction_timeout)s \\
   restart-interval=%(restart_interval)s \\
   cpu-time-limit=%(cpu_time_limit)s \\
   shutdown-timeout=%(shutdown_timeout)s \\
   send-buffer-size=%(send_buffer_size)s \\
   receive-buffer-size=%(receive_buffer_size)s \\
   response-buffer-size=%(response_buffer_size)s \\
   response-socket-timeout=%(response_socket_timeout)s \\
   server-metrics=%(server_metrics_flag)s
</IfDefine>
</IfDefine>
</IfDefine>

WSGICallableObject '%(callable_object)s'
WSGIPassAuthorization On
WSGIMapHEADToGET %(map_head_to_get)s

<IfDefine MOD_WSGI_DISABLE_RELOADING>
WSGIScriptReloading Off
</IfDefine>

<IfDefine EMBEDDED_MODE>
<IfDefine MOD_WSGI_WITH_PYTHON_PATH>
WSGIPythonPath '%(python_path)s'
</IfDefine>
</IfDefine>

<IfDefine ONE_PROCESS>
WSGIRestrictStdin Off
<IfDefine MOD_WSGI_WITH_PYTHON_PATH>
WSGIPythonPath '%(python_path)s'
</IfDefine>
</IfDefine>

<IfDefine MOD_WSGI_SERVER_METRICS>
ExtendedStatus On
</IfDefine>

WSGIServerMetrics %(server_metrics_flag)s

<IfDefine MOD_WSGI_SERVER_STATUS>
<Location /server-status>
    SetHandler server-status
<IfVersion < 2.4>
    Order deny,allow
    Deny from all
    Allow from localhost
</IfVersion>
<IfVersion >= 2.4>
    Require all denied
    Require host localhost
</IfVersion>
</Location>
</IfDefine>

<IfDefine MOD_WSGI_KEEP_ALIVE>
KeepAlive On
KeepAliveTimeout %(keep_alive_timeout)s
</IfDefine>
<IfDefine !MOD_WSGI_KEEP_ALIVE>
KeepAlive Off
</IfDefine>

<IfDefine MOD_WSGI_ENABLE_SENDFILE>
EnableSendfile On
WSGIEnableSendfile On
</IfDefine>

<IfDefine MOD_WSGI_COMPRESS_RESPONSES>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
</IfDefine>

<IfDefine MOD_WSGI_ROTATE_LOGS>
ErrorLog "|%(rotatelogs_executable)s \\
    %(error_log_file)s.%%Y-%%m-%%d-%%H_%%M_%%S %(max_log_size)sM"
</IfDefine>
<IfDefine !MOD_WSGI_ROTATE_LOGS>
ErrorLog "%(error_log_file)s"
</IfDefine>
LogLevel %(log_level)s

<IfDefine MOD_WSGI_ERROR_LOG_FORMAT>
ErrorLogFormat "%(error_log_format)s"
</IfDefine>

<IfDefine MOD_WSGI_ACCESS_LOG>
<IfModule !log_config_module>
LoadModule log_config_module ${MOD_WSGI_MODULES_DIRECTORY}/mod_log_config.so
</IfModule>
LogFormat "%%h %%l %%u %%t \\"%%r\\" %%>s %%b" common
LogFormat "%%h %%l %%u %%t \\"%%r\\" %%>s %%b \\"%%{Referer}i\\" \\"%%{User-agent}i\\"" combined
LogFormat "%(access_log_format)s" custom
<IfDefine MOD_WSGI_ROTATE_LOGS>
CustomLog "|%(rotatelogs_executable)s \\
    %(access_log_file)s.%%Y-%%m-%%d-%%H_%%M_%%S %(max_log_size)sM" %(log_format_nickname)s
</IfDefine>
<IfDefine !MOD_WSGI_ROTATE_LOGS>
CustomLog "%(access_log_file)s" %(log_format_nickname)s
</IfDefine>
</IfDefine>

<IfDefine MOD_WSGI_CHUNKED_REQUEST>
WSGIChunkedRequest On
</IfDefine>

<IfDefine MOD_WSGI_WITH_PROXY_HEADERS>
WSGITrustedProxyHeaders %(trusted_proxy_headers)s
</IfDefine>
<IfDefine MOD_WSGI_WITH_TRUSTED_PROXIES>
WSGITrustedProxies %(trusted_proxies)s
</IfDefine>

<IfDefine MOD_WSGI_WITH_HTTPS>
<IfModule !ssl_module>
LoadModule ssl_module ${MOD_WSGI_MODULES_DIRECTORY}/mod_ssl.so
</IfModule>
</IfDefine>

<IfModule mpm_prefork_module>
<IfDefine !ONE_PROCESS>
ServerLimit %(prefork_server_limit)s
StartServers %(prefork_start_servers)s
MaxClients %(prefork_max_clients)s
MinSpareServers %(prefork_min_spare_servers)s
MaxSpareServers %(prefork_max_spare_servers)s
</IfDefine>
<IfDefine ONE_PROCESS>
ServerLimit 1
StartServers 1
MaxClients 1
MinSpareServers 1
MaxSpareServers 1
</IfDefine>
MaxRequestsPerChild 0
</IfModule>

<IfModule mpm_worker_module>
<IfDefine !ONE_PROCESS>
ServerLimit %(worker_server_limit)s
ThreadLimit %(worker_thread_limit)s
StartServers %(worker_start_servers)s
MaxClients %(worker_max_clients)s
MinSpareThreads %(worker_min_spare_threads)s
MaxSpareThreads %(worker_max_spare_threads)s
ThreadsPerChild %(worker_threads_per_child)s
</IfDefine>
<IfDefine ONE_PROCESS>
ServerLimit 1
ThreadLimit 1
StartServers 1 
MaxClients 1
MinSpareThreads 1
MaxSpareThreads 1
ThreadsPerChild 1
</IfDefine>
MaxRequestsPerChild 0
ThreadStackSize 262144
</IfModule>

<IfModule mpm_event_module>
<IfDefine !ONE_PROCESS>
ServerLimit %(worker_server_limit)s
ThreadLimit %(worker_thread_limit)s
StartServers %(worker_start_servers)s
MaxClients %(worker_max_clients)s
MinSpareThreads %(worker_min_spare_threads)s
MaxSpareThreads %(worker_max_spare_threads)s
ThreadsPerChild %(worker_threads_per_child)s
</IfDefine>
<IfDefine ONE_PROCESS>
ServerLimit 1
ThreadLimit 1
StartServers 1
MaxClients 1
MinSpareThreads 1
MaxSpareThreads 1
ThreadsPerChild 1
</IfDefine>
MaxRequestsPerChild 0
ThreadStackSize 262144
</IfModule>

<IfDefine !MOD_WSGI_VIRTUAL_HOST>
<IfVersion < 2.4>
NameVirtualHost *:%(port)s
</IfVersion>
<VirtualHost _default_:%(port)s>
</VirtualHost>
</IfDefine>

<IfDefine MOD_WSGI_VIRTUAL_HOST>

<IfVersion < 2.4>
NameVirtualHost *:%(port)s
</IfVersion>
<VirtualHost _default_:%(port)s>
<Location />
<IfVersion < 2.4>
Order deny,allow
Deny from all
</IfVersion>
<IfVersion >= 2.4>
Require all denied
</IfVersion>
<IfDefine MOD_WSGI_ALLOW_LOCALHOST>
Allow from localhost
</IfDefine>
</Location>
</VirtualHost>
<IfDefine !MOD_WSGI_HTTPS_ONLY>
<VirtualHost *:%(port)s>
ServerName %(server_name)s
<IfDefine MOD_WSGI_SERVER_ALIAS>
ServerAlias %(server_aliases)s
</IfDefine>
</VirtualHost>
<IfDefine MOD_WSGI_REDIRECT_WWW>
<VirtualHost *:%(port)s>
ServerName %(parent_domain)s
Redirect permanent / http://%(server_name)s:%(port)s/
</VirtualHost>
</IfDefine>
</IfDefine>

<IfDefine MOD_WSGI_HTTPS_ONLY>
<VirtualHost *:%(port)s>
ServerName %(server_name)s
<IfDefine MOD_WSGI_SERVER_ALIAS>
ServerAlias %(server_aliases)s
</IfDefine>
RewriteEngine On
RewriteCond %%{HTTPS} off
RewriteRule (.*) https://%(server_name)s:%(https_port)s%%{REQUEST_URI}
</VirtualHost>
<IfDefine MOD_WSGI_REDIRECT_WWW>
<VirtualHost *:%(port)s>
ServerName %(parent_domain)s
RewriteEngine On
RewriteCond %%{HTTPS} off
RewriteRule (.*) https://%(server_name)s:%(https_port)s%%{REQUEST_URI}
</VirtualHost>
</IfDefine>
</IfDefine>

</IfDefine>

<IfDefine MOD_WSGI_VIRTUAL_HOST>

<IfDefine MOD_WSGI_WITH_HTTPS>
<IfDefine MOD_WSGI_WITH_LISTENER_HOST>
Listen %(host)s:%(https_port)s
</IfDefine>
<IfDefine !MOD_WSGI_WITH_LISTENER_HOST>
Listen %(https_port)s
</IfDefine>
<IfVersion < 2.4>
NameVirtualHost *:%(https_port)s
</IfVersion>
<VirtualHost _default_:%(https_port)s>
<Location />
<IfVersion < 2.4>
Order deny,allow
Deny from all
</IfVersion>
<IfVersion >= 2.4>
Require all denied
</IfVersion>
<IfDefine MOD_WSGI_ALLOW_LOCALHOST>
Allow from localhost
</IfDefine>
</Location>
SSLEngine On
SSLCertificateFile %(ssl_certificate_file)s
SSLCertificateKeyFile %(ssl_certificate_key_file)s
<IfDefine MOD_WSGI_VERIFY_CLIENT>
SSLCACertificateFile %(ssl_ca_certificate_file)s
SSLVerifyClient none
</IfDefine>
<IfDefine MOD_WSGI_CERTIFICATE_CHAIN>
SSLCertificateChainFile %(ssl_certificate_chain_file)s
</IfDefine>
</VirtualHost>
<VirtualHost *:%(https_port)s>
ServerName %(server_name)s
<IfDefine MOD_WSGI_SERVER_ALIAS>
ServerAlias %(server_aliases)s
</IfDefine>
SSLEngine On
SSLCertificateFile %(ssl_certificate_file)s
SSLCertificateKeyFile %(ssl_certificate_key_file)s
<IfDefine MOD_WSGI_VERIFY_CLIENT>
SSLCACertificateFile %(ssl_ca_certificate_file)s
SSLVerifyClient none
</IfDefine>
<IfDefine MOD_WSGI_CERTIFICATE_CHAIN>
SSLCertificateChainFile %(ssl_certificate_chain_file)s
</IfDefine>
<IfDefine MOD_WSGI_HTTPS_ONLY>
<IfDefine MOD_WSGI_HSTS_POLICY>
Header set Strict-Transport-Security %(hsts_policy)s
</IfDefine>
</IfDefine>
<IfDefine MOD_WSGI_SSL_ENVIRONMENT>
SSLOptions +StdEnvVars
</IfDefine>
</VirtualHost>
<IfDefine MOD_WSGI_REDIRECT_WWW>
<VirtualHost *:%(https_port)s>
ServerName %(parent_domain)s
Redirect permanent / https://%(server_name)s:%(https_port)s/
SSLEngine On
SSLCertificateFile %(ssl_certificate_file)s
SSLCertificateKeyFile %(ssl_certificate_key_file)s
<IfDefine MOD_WSGI_VERIFY_CLIENT>
SSLCACertificateFile %(ssl_ca_certificate_file)s
SSLVerifyClient none
</IfDefine>
<IfDefine MOD_WSGI_CERTIFICATE_CHAIN>
SSLCertificateChainFile %(ssl_certificate_chain_file)s
</IfDefine>
</VirtualHost>
</IfDefine>
</IfDefine>

</IfDefine>

DocumentRoot '%(document_root)s'

AccessFileName .htaccess

<Directory '%(server_root)s'>
    AllowOverride %(allow_override)s
<Files handler.wsgi>
<IfVersion < 2.4>
    Order allow,deny
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
</Files>
</Directory>

<Directory '%(document_root)s'>
    AllowOverride %(allow_override)s
<IfDefine MOD_WSGI_DIRECTORY_INDEX>
    DirectoryIndex %(directory_index)s
</IfDefine>
<IfDefine MOD_WSGI_DIRECTORY_LISTING>
    Options +Indexes
</IfDefine>
<IfDefine MOD_WSGI_CGI_SCRIPT>
    Options +ExecCGI
</IfDefine>
<IfDefine MOD_WSGI_CGID_SCRIPT>
    Options +ExecCGI
</IfDefine>
    RewriteEngine On
    Include %(rewrite_rules)s
<IfVersion < 2.4>
    Order allow,deny
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
</Directory>

<Directory '%(document_root)s%(mount_point)s'>
<IfDefine !MOD_WSGI_STATIC_ONLY>
    RewriteCond %%{REQUEST_FILENAME} !-f
<IfDefine MOD_WSGI_DIRECTORY_INDEX>
    RewriteCond %%{REQUEST_FILENAME} !-d
</IfDefine>
<IfDefine MOD_WSGI_SERVER_STATUS>
    RewriteCond %%{REQUEST_URI} !/server-status
</IfDefine>
    RewriteRule .* - [H=wsgi-handler]
</IfDefine>
</Directory>

<IfDefine MOD_WSGI_ERROR_OVERRIDE>
WSGIErrorOverride On
</IfDefine>

<IfDefine MOD_WSGI_HOST_ACCESS>
<Location />
    WSGIAccessScript '%(host_access_script)s'
</Location>
</IfDefine>

<IfDefine MOD_WSGI_AUTH_USER>
<Location />
    AuthType %(auth_type)s
    AuthName '%(host)s:%(port)s'
    Auth%(auth_type)sProvider wsgi
    WSGIAuthUserScript '%(auth_user_script)s'
<IfDefine MOD_WSGI_AUTH_GROUP>
    WSGIAuthGroupScript '%(auth_group_script)s'
</IfDefine>
<IfVersion < 2.4>
    Require valid-user
<IfDefine MOD_WSGI_AUTH_GROUP>
    Require wsgi-group '%(auth_group)s'
</IfDefine>
</IfVersion>
<IfVersion >= 2.4>
    <RequireAll>
    Require valid-user
<IfDefine MOD_WSGI_AUTH_GROUP>
    Require wsgi-group '%(auth_group)s'
</IfDefine>
    </RequireAll>
</IfVersion>
</Location>
</IfDefine>

<IfDefine !ONE_PROCESS>
<IfDefine !EMBEDDED_MODE>
WSGIHandlerScript wsgi-handler '%(server_root)s/handler.wsgi' \\
    process-group='%(host)s:%(port)s' application-group=%%{GLOBAL}
WSGIImportScript '%(server_root)s/handler.wsgi' \\
    process-group='%(host)s:%(port)s' application-group=%%{GLOBAL}
</IfDefine>
</IfDefine>

<IfDefine EMBEDDED_MODE>
WSGIHandlerScript wsgi-handler '%(server_root)s/handler.wsgi' \\
    process-group='%%{GLOBAL}' application-group=%%{GLOBAL}
WSGIImportScript '%(server_root)s/handler.wsgi' \\
    process-group='%%{GLOBAL}' application-group=%%{GLOBAL}
</IfDefine>

<IfDefine ONE_PROCESS>
<IfDefine !MOD_WSGI_MPM_ENABLE_WINNT_MODULE>
WSGIHandlerScript wsgi-handler '%(server_root)s/handler.wsgi' \\
    process-group='%%{GLOBAL}' application-group=%%{GLOBAL}
WSGIImportScript '%(server_root)s/handler.wsgi' \\
    process-group='%%{GLOBAL}' application-group=%%{GLOBAL}
</IfDefine>
<IfDefine MOD_WSGI_MPM_ENABLE_WINNT_MODULE>
WSGIHandlerScript wsgi-handler '%(server_root)s/handler.wsgi' \\
    application-group=%%{GLOBAL}
WSGIImportScript '%(server_root)s/handler.wsgi' \\
    application-group=%%{GLOBAL}
</IfDefine>
</IfDefine>
"""

APACHE_IGNORE_ACTIVITY_CONFIG = """
<Location '%(url)s'>
WSGIIgnoreActivity On
</Location>
"""

APACHE_PROXY_PASS_MOUNT_POINT_CONFIG = """
ProxyPass '%(mount_point)s' '%(url)s'
ProxyPassReverse '%(mount_point)s' '%(url)s'
<Location '%(mount_point)s'>
RewriteEngine On
RewriteRule .* - [E=SERVER_PORT:%%{SERVER_PORT},NE]
RequestHeader set X-Forwarded-Port %%{SERVER_PORT}e
RewriteCond %%{HTTPS} on
RewriteRule .* - [E=URL_SCHEME:https,NE]
RequestHeader set X-Forwarded-Scheme %%{URL_SCHEME}e env=URL_SCHEME
</Location>
"""

APACHE_PROXY_PASS_MOUNT_POINT_SLASH_CONFIG = """
ProxyPass '%(mount_point)s/' '%(url)s/'
ProxyPassReverse '%(mount_point)s/' '%(url)s/'
<Location '%(mount_point)s/'>
RewriteEngine On
RewriteRule .* - [E=SERVER_PORT:%%{SERVER_PORT},NE]
RequestHeader set X-Forwarded-Port %%{SERVER_PORT}e
RewriteCond %%{HTTPS} on
RewriteRule .* - [E=URL_SCHEME:https,NE]
RequestHeader set X-Forwarded-Scheme %%{URL_SCHEME}e env=URL_SCHEME
</Location>
<LocationMatch '^%(mount_point)s$'>
RewriteEngine On
RewriteRule - http://%%{HTTP_HOST}%%{REQUEST_URI}/ [R=302,L]
</LocationMatch>
"""

APACHE_PROXY_PASS_HOST_CONFIG = """
<VirtualHost *:%(port)s>
ServerName %(host)s
ProxyPass / '%(url)s'
ProxyPassReverse / '%(url)s'
RequestHeader set X-Forwarded-Port %(port)s
RewriteEngine On
RewriteCond %%{HTTPS} on
RewriteRule .* - [E=URL_SCHEME:https,NE]
RequestHeader set X-Forwarded-Scheme %%{URL_SCHEME}e env=URL_SCHEME
</VirtualHost>
"""

APACHE_ALIAS_DIRECTORY_CONFIG = """
Alias '%(mount_point)s' '%(directory)s'

<Directory '%(directory)s'>
    AllowOverride %(allow_override)s
<IfVersion < 2.4>
    Order allow,deny
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
</Directory>
"""

APACHE_ALIAS_FILENAME_CONFIG = """
Alias '%(mount_point)s' '%(directory)s/%(filename)s'

<Directory '%(directory)s'>
<Files '%(filename)s'>
<IfVersion < 2.4>
    Order allow,deny
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
</Files>
</Directory>
"""

APACHE_ALIAS_DOCUMENTATION = """
Alias /__wsgi__/docs '%(documentation_directory)s'
Alias /__wsgi__/images '%(images_directory)s'

<Directory '%(documentation_directory)s'>
    DirectoryIndex index.html
<IfVersion < 2.4>
    Order allow,deny
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
</Directory>

<Directory '%(images_directory)s'>
<IfVersion < 2.4>
    Order allow,deny
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
</Directory>
"""

APACHE_VERIFY_CLIENT_CONFIG = """
<IfDefine MOD_WSGI_VERIFY_CLIENT>
<Location '%(path)s'>
SSLVerifyClient require
SSLVerifyDepth 1
</Location>
</IfDefine>
"""

APACHE_ERROR_DOCUMENT_CONFIG = """
ErrorDocument '%(status)s' '%(document)s'
"""

APACHE_SETENV_CONFIG = """
SetEnv '%(name)s' '%(value)s'
"""

APACHE_PASSENV_CONFIG = """
PassEnv '%(name)s'
"""

APACHE_HANDLER_SCRIPT_CONFIG = """
WSGIHandlerScript wsgi-resource '%(server_root)s/resource.wsgi' \\
    process-group='%(host)s:%(port)s' application-group=%%{GLOBAL}
"""

APACHE_HANDLER_CONFIG = """
AddHandler %(handler)s %(extension)s
"""

APACHE_INCLUDE_CONFIG = """
Include '%(filename)s'
"""

APACHE_TOOLS_CONFIG = """
WSGIDaemonProcess express display-name=%%{GROUP} threads=1 server-metrics=On
"""

APACHE_METRICS_CONFIG = """
WSGIImportScript '%(server_root)s/server-metrics.py' \\
    process-group=express application-group=server-metrics
"""

APACHE_SERVICE_CONFIG = """
WSGIDaemonProcess 'service:%(name)s' \\
    display-name=%%{GROUP} \\
    user='%(user)s' \\
    group='%(group)s' \\
    home='%(working_directory)s' \\
    threads=0 \\
    python-path='%(python_path)s' \\
    python-eggs='%(python_eggs)s' \\
    lang='%(lang)s' \\
    locale='%(locale)s' \\
    server-metrics=%(server_metrics_flag)s
WSGIImportScript '%(script)s' \\
    process-group='service:%(name)s' \\
    application-group=%%{GLOBAL}
"""

APACHE_SERVICE_WITH_LOG_CONFIG = """
<VirtualHost *:%(port)s>
<IfDefine MOD_WSGI_ROTATE_LOGS>
ErrorLog "|%(rotatelogs_executable)s \\
    %(log_directory)s/%(log_file)s.%%Y-%%m-%%d-%%H_%%M_%%S %(max_log_size)sM"
</IfDefine>
<IfDefine !MOD_WSGI_ROTATE_LOGS>
ErrorLog "%(log_directory)s/%(log_file)s"
</IfDefine>
WSGIDaemonProcess 'service:%(name)s' \\
    display-name=%%{GROUP} \\
    user='%(user)s' \\
    group='%(group)s' \\
    home='%(working_directory)s' \\
    threads=0 \\
    python-path='%(python_path)s' \\
    python-eggs='%(python_eggs)s' \\
    lang='%(lang)s' \\
    locale='%(locale)s' \\
    server-metrics=%(server_metrics_flag)s
WSGIImportScript '%(script)s' \\
    process-group='service:%(name)s' \\
    application-group=%%{GLOBAL}
</VirtualHost>
"""

def generate_apache_config(options):
    with open(options['httpd_conf'], 'w') as fp:
        print(APACHE_GENERAL_CONFIG % options, file=fp)

        if options['ignore_activity']:
            for url in options['ignore_activity']:
                print(APACHE_IGNORE_ACTIVITY_CONFIG % dict(url=url), file=fp)

        if options['proxy_mount_points']:
            for mount_point, url in options['proxy_mount_points']:
                if mount_point.endswith('/'):
                    print(APACHE_PROXY_PASS_MOUNT_POINT_CONFIG % dict(
                            mount_point=mount_point, url=url), file=fp)
                else:
                    print(APACHE_PROXY_PASS_MOUNT_POINT_SLASH_CONFIG % dict(
                            mount_point=mount_point, url=url), file=fp)

        if options['proxy_virtual_hosts']:
            for host, url in options['proxy_virtual_hosts']:
                print(APACHE_PROXY_PASS_HOST_CONFIG % dict(
                        host=host, port=options['port'], url=url),
                        file=fp)

        if options['url_aliases']:
            for mount_point, target in sorted(options['url_aliases'],
                    reverse=True):
                path = posixpath.abspath(target)

                if os.path.isdir(path) or not os.path.exists(path):
                    if target.endswith('/') and path != '/':
                        directory = path + '/'
                    else:
                        directory = path

                    print(APACHE_ALIAS_DIRECTORY_CONFIG % dict(
                            mount_point=mount_point, directory=directory,
                            allow_override=options['allow_override']),
                            file=fp)

                else:
                    directory = posixpath.dirname(path)
                    filename = posixpath.basename(path)

                    print(APACHE_ALIAS_FILENAME_CONFIG % dict(
                            mount_point=mount_point, directory=directory,
                            filename=filename), file=fp)

        if options['enable_docs']:
            print(APACHE_ALIAS_DOCUMENTATION % options, file=fp)

        if options['error_documents']:
            for status, document in options['error_documents']:
                print(APACHE_ERROR_DOCUMENT_CONFIG % dict(status=status,
                        document=document.replace("'", "\\'")), file=fp)

        if options['ssl_verify_client_urls']:
            paths = sorted(options['ssl_verify_client_urls'], reverse=True)
            for path in paths:
                print(APACHE_VERIFY_CLIENT_CONFIG % dict(path=path), file=fp)
        else:
            print(APACHE_VERIFY_CLIENT_CONFIG % dict(path='/'), file=fp)

        if options['setenv_variables']:
            for name, value in options['setenv_variables']:
                print(APACHE_SETENV_CONFIG % dict(name=name, value=value),
                        file=fp)

        if options['passenv_variables']:
            for name in options['passenv_variables']:
                print(APACHE_PASSENV_CONFIG % dict(name=name), file=fp)

        if options['handler_scripts']:
            print(APACHE_HANDLER_SCRIPT_CONFIG % options, file=fp)

            for extension, script in options['handler_scripts']:
                print(APACHE_HANDLER_CONFIG % dict(handler='wsgi-resource',
                        extension=extension), file=fp)

        if options['with_cgi']:
            print(APACHE_HANDLER_CONFIG % dict(handler='cgi-script',
                    extension='.cgi'), file=fp)

        if options['service_scripts']:
            service_log_files = {}
            if options['service_log_files']:
                service_log_files.update(options['service_log_files'])
            users = dict(options['service_users'] or [])
            groups = dict(options['service_groups'] or [])
            for name, script in options['service_scripts']:
                user = users.get(name, '${MOD_WSGI_USER}')
                group = groups.get(name, '${MOD_WSGI_GROUP}')
                if name in service_log_files:
                    print(APACHE_SERVICE_WITH_LOG_CONFIG % dict(name=name,
                            user=user, group=group, script=script,
                            port=options['port'],
                            log_directory=options['log_directory'],
                            log_file=service_log_files[name],
                            rotatelogs_executable=options['rotatelogs_executable'],
                            max_log_size=options['max_log_size'],
                            python_path=options['python_path'],
                            working_directory=options['working_directory'],
                            python_eggs=options['python_eggs'],
                            lang=options['lang'], locale=options['locale'],
                            server_metrics_flag=options['server_metrics_flag']),
                            file=fp)
                else:
                    print(APACHE_SERVICE_CONFIG % dict(name=name, user=user,
                            group=group, script=script,
                            python_path=options['python_path'],
                            working_directory=options['working_directory'],
                            python_eggs=options['python_eggs'],
                            lang=options['lang'], locale=options['locale'],
                            server_metrics_flag=options['server_metrics_flag']),
                            file=fp)

        if options['include_files']:
            for filename in options['include_files']:
                filename = posixpath.abspath(filename)
                print(APACHE_INCLUDE_CONFIG % dict(filename=filename),
                        file=fp)

        if options['with_newrelic_platform']:
            print(APACHE_TOOLS_CONFIG % options, file=fp)

        if options['with_newrelic_platform']:
            print(APACHE_METRICS_CONFIG % options, file=fp)

_interval = 1.0
_times = {}
_files = []

_running = False
_queue = queue.Queue()
_lock = threading.Lock()

def _restart(path):
    _queue.put(True)
    prefix = 'monitor (pid=%d):' % os.getpid()
    print('%s Change detected to "%s".' % (prefix, path), file=sys.stderr)
    print('%s Triggering process restart.' % prefix, file=sys.stderr)
    os.kill(os.getpid(), signal.SIGINT)

def _modified(path):
    try:
        # If path doesn't denote a file and were previously
        # tracking it, then it has been removed or the file type
        # has changed so force a restart. If not previously
        # tracking the file then we can ignore it as probably
        # pseudo reference such as when file extracted from a
        # collection of modules contained in a zip file.

        if not os.path.isfile(path):
            return path in _times

        # Check for when file last modified.

        mtime = os.stat(path).st_mtime
        if path not in _times:
            _times[path] = mtime

        # Force restart when modification time has changed, even
        # if time now older, as that could indicate older file
        # has been restored.

        if mtime != _times[path]:
            return True
    except Exception:
        # If any exception occured, likely that file has been
        # been removed just before stat(), so force a restart.

        return True

    return False

def _monitor():
    global _files

    while True:
        # Check modification times on all files in sys.modules.

        for module in list(sys.modules.values()):
            if not hasattr(module, '__file__'):
                continue
            path = getattr(module, '__file__')
            if not path:
                continue
            if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
                path = path[:-1]
            if _modified(path):
                return _restart(path)

        # Check modification times on files which have
        # specifically been registered for monitoring.

        for path in _files:
            if _modified(path):
                return _restart(path)

        # Go to sleep for specified interval.

        try:
            return _queue.get(timeout=_interval)

        except queue.Empty:
            pass

_thread = threading.Thread(target=_monitor)
_thread.setDaemon(True)

def _exiting():
    try:
        _queue.put(True)
    except Exception:
        pass
    _thread.join()

def track_changes(path):
    if not path in _files:
        _files.append(path)

def start_reloader(interval=1.0):
    global _interval
    if interval < _interval:
        _interval = interval

    global _running
    _lock.acquire()
    if not _running:
        prefix = 'monitor (pid=%d):' % os.getpid()
        print('%s Starting change monitor.' % prefix, file=sys.stderr)
        _running = True
        _thread.start()
        atexit.register(_exiting)
    _lock.release()

class PostMortemDebugger(object):

    def __init__(self, application, startup):
        self.application = application
        self.generator = None

        import pdb
        self.debugger = pdb.Pdb()

        if startup:
            self.activate_console()

    def activate_console(self):
        self.debugger.set_trace(sys._getframe().f_back)

    def run_post_mortem(self):
        self.debugger.reset()
        self.debugger.interaction(None, sys.exc_info()[2])

    def __call__(self, environ, start_response):
        try:
            self.generator = self.application(environ, start_response)
            return self
        except Exception:
            self.run_post_mortem()
            raise

    def __iter__(self):
        try:
            for item in self.generator:
                yield item
        except Exception:
            self.run_post_mortem()
            raise

    def close(self):
        try:
            if hasattr(self.generator, 'close'):
                return self.generator.close()
        except Exception:
            self.run_post_mortem()
            raise

class RequestRecorder(object):

    def __init__(self, application, savedir):
        self.application = application
        self.savedir = savedir
        self.lock = threading.Lock()
        self.pid = os.getpid()
        self.count = 0

    def __call__(self, environ, start_response):
        with self.lock:
            self.count += 1
            count = self.count

        key = "%s-%s-%s" % (int(time.time()*1000000), self.pid, count)

        iheaders = os.path.join(self.savedir, key + ".iheaders")
        iheaders_fp = open(iheaders, 'w')

        icontent = os.path.join(self.savedir, key + ".icontent")
        icontent_fp = open(icontent, 'w+b')

        oheaders = os.path.join(self.savedir, key + ".oheaders")
        oheaders_fp = open(oheaders, 'w')

        ocontent = os.path.join(self.savedir, key + ".ocontent")
        ocontent_fp = open(ocontent, 'w+b')

        oaexcept = os.path.join(self.savedir, key + ".oaexcept")
        oaexcept_fp = open(oaexcept, 'w')

        orexcept = os.path.join(self.savedir, key + ".orexcept")
        orexcept_fp = open(orexcept, 'w')

        ofexcept = os.path.join(self.savedir, key + ".ofexcept")
        ofexcept_fp = open(ofexcept, 'w')

        errors = environ['wsgi.errors']
        pprint.pprint(environ, stream=iheaders_fp)
        iheaders_fp.close()

        input = environ['wsgi.input']

        data = input.read(8192)

        while data:
            icontent_fp.write(data)
            data = input.read(8192)

        icontent_fp.flush()
        icontent_fp.seek(0, os.SEEK_SET)

        environ['wsgi.input'] = icontent_fp

        def _start_response(status, response_headers, *args):
            pprint.pprint(((status, response_headers)+args),
                    stream=oheaders_fp)

            _write = start_response(status, response_headers, *args)

            def write(self, data):
                ocontent_fp.write(data)
                ocontent_fp.flush()
                return _write(data)

            return write

        try:
            try:
                result = self.application(environ, _start_response)

            except:
                traceback.print_exception(*sys.exc_info(), file=oaexcept_fp)
                raise

            try:
                for data in result:
                    ocontent_fp.write(data)
                    ocontent_fp.flush()
                    yield data

            except:
                traceback.print_exception(*sys.exc_info(), file=orexcept_fp)
                raise

            finally:
                try:
                    if hasattr(result, 'close'):
                        result.close()

                except:
                    traceback.print_exception(*sys.exc_info(),
                            file=ofexcept_fp)
                    raise

        finally:
            oheaders_fp.close()
            ocontent_fp.close()
            oaexcept_fp.close()
            orexcept_fp.close()
            ofexcept_fp.close()

class ApplicationHandler(object):

    def __init__(self, entry_point, application_type='script',
            callable_object='application', mount_point='/',
            with_newrelic_agent=False, debug_mode=False,
            enable_debugger=False, debugger_startup=False,
            enable_recorder=False, recorder_directory=None):

        self.entry_point = entry_point
        self.application_type = application_type
        self.callable_object = callable_object
        self.mount_point = mount_point

        if application_type == 'module':
            __import__(entry_point)
            self.module = sys.modules[entry_point]
            self.application = getattr(self.module, callable_object)
            self.target = self.module.__file__
            parts = os.path.splitext(self.target)[-1]
            if parts[-1].lower() in ('.pyc', '.pyd', '.pyd'):
                self.target = parts[0] + '.py'

        elif application_type == 'paste':
            from paste.deploy import loadapp
            self.application = loadapp('config:%s' % entry_point)
            self.target = entry_point

        elif application_type != 'static':
            self.module = types.ModuleType('__wsgi__')
            self.module.__file__ = entry_point

            with open(entry_point, 'r') as fp:
                code = compile(fp.read(), entry_point, 'exec',
                        dont_inherit=True)
                exec(code, self.module.__dict__)

            sys.modules['__wsgi__'] = self.module
            self.application = getattr(self.module, callable_object)
            self.target = entry_point

        try:
            self.mtime = os.path.getmtime(self.target)
        except Exception:
            self.mtime = None

        if with_newrelic_agent:
            self.setup_newrelic_agent()

        self.debug_mode = debug_mode
        self.enable_debugger = enable_debugger

        if enable_debugger:
            self.setup_debugger(debugger_startup)

        if enable_recorder:
            self.setup_recorder(recorder_directory)

    def setup_newrelic_agent(self):
        import newrelic.agent

        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')
        environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

        global_settings = newrelic.agent.global_settings()
        if global_settings.log_file is None:
            global_settings.log_file = 'stderr'

        newrelic.agent.initialize(config_file, environment)
        newrelic.agent.register_application()

        self.application = newrelic.agent.WSGIApplicationWrapper(
                self.application)

    def setup_debugger(self, startup):
        self.application = PostMortemDebugger(self.application, startup)

    def setup_recorder(self, savedir):
        self.application = RequestRecorder(self.application, savedir)

    def reload_required(self, environ):
        if self.debug_mode:
            return False

        try:
            mtime = os.path.getmtime(self.target)
        except Exception:
            mtime = None

        return mtime != self.mtime

    def handle_request(self, environ, start_response):
        # Strip out the leading component due to internal redirect in
        # Apache when using web application as fallback resource.

        mount_point = environ.get('mod_wsgi.mount_point')

        script_name = environ.get('SCRIPT_NAME')
        path_info = environ.get('PATH_INFO')

        if mount_point is not None:
            # If this is set then it means that SCRIPT_NAME was
            # overridden by a trusted proxy header. In this case
            # we want to ignore any local mount point, simply
            # stripping it from the path.

            script_name = environ['mod_wsgi.script_name']

            environ['PATH_INFO'] = script_name + path_info

            if self.mount_point != '/':
                if environ['PATH_INFO'].startswith(self.mount_point):
                    environ['PATH_INFO'] = environ['PATH_INFO'][len(
                            self.mount_point):]

        else:
            environ['SCRIPT_NAME'] = ''
            environ['PATH_INFO'] = script_name + path_info

            if self.mount_point != '/':
                if environ['PATH_INFO'].startswith(self.mount_point):
                    environ['SCRIPT_NAME'] = self.mount_point
                    environ['PATH_INFO'] = environ['PATH_INFO'][len(
                            self.mount_point):]

        return self.application(environ, start_response)

    def __call__(self, environ, start_response):
        return self.handle_request(environ, start_response)

class ResourceHandler(object):

    def __init__(self, resources):
        self.resources = {}

        for extension, script in resources:
            extension_name = re.sub(r'[^\w]{1}', '_', extension)
            module_name = '__wsgi_resource%s__' % extension_name
            module = types.ModuleType(module_name)
            module.__file__ = script

            with open(script, 'r') as fp:
                code = compile(fp.read(), script, 'exec',
                        dont_inherit=True)
                exec(code, module.__dict__)

            sys.modules[module_name] = module
            self.resources[extension] = module

    def resource_extension(self, resource):
        return os.path.splitext(resource)[-1]

    def reload_required(self, resource):
        extension = self.resource_extension(resource)
        function = getattr(self.resources[extension], 'reload_required', None)
        if function is not None:
            return function(environ)
        return False

    def handle_request(self, environ, start_response):
        resource = environ['SCRIPT_NAME']
        extension = self.resource_extension(resource)
        module = self.resources[extension]
        function = getattr(module, 'handle_request', None)
        if function is not None:
            return function(environ, start_response)
        function = getattr(module, 'application')
        return function(environ, start_response)

    def __call__(self, environ, start_response):
        return self.handle_request(environ, start_response)

WSGI_HANDLER_SCRIPT = """
import os
import sys
import atexit
import time

import mod_wsgi.server

working_directory = r'%(working_directory)s'

entry_point = r'%(entry_point)s'
application_type = '%(application_type)s'
callable_object = '%(callable_object)s'
mount_point = '%(mount_point)s'
with_newrelic_agent = %(with_newrelic_agent)s
newrelic_config_file = '%(newrelic_config_file)s'
newrelic_environment = '%(newrelic_environment)s'
disable_reloading = %(disable_reloading)s
reload_on_changes = %(reload_on_changes)s
debug_mode = %(debug_mode)s
enable_debugger = %(enable_debugger)s
debugger_startup = %(debugger_startup)s
enable_coverage = %(enable_coverage)s
coverage_directory = '%(coverage_directory)s'
enable_profiler = %(enable_profiler)s
profiler_directory = '%(profiler_directory)s'
enable_recorder = %(enable_recorder)s
recorder_directory = '%(recorder_directory)s'
enable_gdb = %(enable_gdb)s

os.environ['MOD_WSGI_EXPRESS'] = 'true'
os.environ['MOD_WSGI_SERVER_NAME'] = '%(server_host)s'
os.environ['MOD_WSGI_SERVER_ALIASES'] = %(server_aliases)r or ''

if reload_on_changes:
    os.environ['MOD_WSGI_RELOADER_ENABLED'] = 'true'

if debug_mode:
    os.environ['MOD_WSGI_DEBUG_MODE'] = 'true'

    # We need to fiddle sys.path as we are not using daemon mode and so
    # the working directory will not be added to sys.path by virtue of
    # 'home' option to WSGIDaemonProcess directive. We could use the
    # WSGIPythonPath directive, but that will cause .pth files to also
    # be evaluated.

    sys.path.insert(0, working_directory)

if enable_debugger:
    os.environ['MOD_WSGI_DEBUGGER_ENABLED'] = 'true'

def output_coverage_report():
    coverage_info.stop()
    coverage_info.html_report(directory=coverage_directory)

if enable_coverage:
    os.environ['MOD_WSGI_COVERAGE_ENABLED'] = 'true'

    from coverage import coverage
    coverage_info = coverage()
    coverage_info.start()
    atexit.register(output_coverage_report)

def output_profiler_data():
    profiler_info.disable()
    output_file = '%%s-%%d.pstats' %% (int(time.time()*1000000), os.getpid())
    output_file = os.path.join(profiler_directory, output_file)
    profiler_info.dump_stats(output_file)

if enable_profiler:
    os.environ['MOD_WSGI_PROFILER_ENABLED'] = 'true'

    from cProfile import Profile
    profiler_info = Profile()
    profiler_info.enable()
    atexit.register(output_profiler_data)

if enable_recorder:
    os.environ['MOD_WSGI_RECORDER_ENABLED'] = 'true'

if enable_gdb:
    os.environ['MOD_WSGI_GDB_ENABLED'] = 'true'

if with_newrelic_agent:
    if newrelic_config_file:
        os.environ['NEW_RELIC_CONFIG_FILE'] = newrelic_config_file
    if newrelic_environment:
        os.environ['NEW_RELIC_ENVIRONMENT'] = newrelic_environment

handler = mod_wsgi.server.ApplicationHandler(entry_point,
        application_type=application_type, callable_object=callable_object,
        mount_point=mount_point, with_newrelic_agent=with_newrelic_agent,
        debug_mode=debug_mode, enable_debugger=enable_debugger,
        debugger_startup=debugger_startup, enable_recorder=enable_recorder,
        recorder_directory=recorder_directory)

if not disable_reloading:
    reload_required = handler.reload_required

handle_request = handler.handle_request

if not disable_reloading and reload_on_changes and not debug_mode:
    mod_wsgi.server.start_reloader()
"""

WSGI_RESOURCE_SCRIPT = """
import mod_wsgi.server

resources = %(resources)s

handler = mod_wsgi.server.ResourceHandler(resources)

reload_required = handler.reload_required
handle_request = handler.handle_request
"""

WSGI_DEFAULT_SCRIPT = """
CONTENT = b'''
<html>
<head>
<title>My web site runs on Malt Whiskey</title>
</head>
<body style="margin-top: 100px;">
<table align="center"; style="width: 850px;" border="0" cellpadding="30">
<tbody>
<tr>
<td>
<img style="width: 275px; height: 445px;"
  src="/__wsgi__/images/snake-whiskey.jpg">
</td>
<td style="text-align: center;">
<span style="font-family: Arial,Helvetica,sans-serif;
  font-weight: bold; font-size: 70px;">
My web site<br>runs on<br>Malt Whiskey<br>
<br>
</span>
<span style="font-family: Arial,Helvetica,sans-serif;
  font-weight: bold;">
For further information on configuring mod_wsgi,<br>
see the <a href="%(documentation_url)s">documentation</a>.
</span>
</td>
</tr>
</tbody>
</table>
</body>
</html>
'''

def application(environ, start_response):
    status = '200 OK'
    output = CONTENT

    response_headers = [('Content-type', 'text/html'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]
"""

def generate_wsgi_handler_script(options):
    path = os.path.join(options['server_root'], 'handler.wsgi')
    with open(path, 'w') as fp:
        print(WSGI_HANDLER_SCRIPT % options, file=fp)

    path = os.path.join(options['server_root'], 'resource.wsgi')
    with open(path, 'w') as fp:
        print(WSGI_RESOURCE_SCRIPT % dict(resources=repr(
                options['handler_scripts'])), file=fp)

    path = os.path.join(options['server_root'], 'default.wsgi')
    with open(path, 'w') as fp:
        print(WSGI_DEFAULT_SCRIPT % options, file=fp)

SERVER_METRICS_SCRIPT = """
import os
import logging

newrelic_config_file = '%(newrelic_config_file)s'
newrelic_environment = '%(newrelic_environment)s'

with_newrelic_platform = %(with_newrelic_platform)s

if with_newrelic_platform:
    if newrelic_config_file:
        os.environ['NEW_RELIC_CONFIG_FILE'] = newrelic_config_file
    if newrelic_environment:
        os.environ['NEW_RELIC_ENVIRONMENT'] = newrelic_environment

logging.basicConfig(level=logging.INFO,
    format='%%(name)s (pid=%%(process)d, level=%%(levelname)s): %%(message)s')

_logger = logging.getLogger(__name__)

try:
    from mod_wsgi.metrics.newrelic import Agent

    agent = Agent()
    agent.start()

except ImportError:
    _logger.fatal('The module mod_wsgi.metrics.newrelic is not available. '
            'The New Relic platform plugin has been disabled. Install the '
            '"mod_wsgi-metrics" package.')
"""

def generate_server_metrics_script(options):
    path = os.path.join(options['server_root'], 'server-metrics.py')
    with open(path, 'w') as fp:
        print(SERVER_METRICS_SCRIPT % options, file=fp)

WSGI_CONTROL_SCRIPT = """
#!%(shell_executable)s

# %(sys_argv)s

HTTPD="%(httpd_executable)s"
HTTPD_ARGS="%(httpd_arguments)s"

HTTPD_COMMAND="$HTTPD $HTTPD_ARGS"

MOD_WSGI_MODULES_DIRECTORY="%(modules_directory)s"
export MOD_WSGI_MODULES_DIRECTORY

SHLIBPATH="%(shlibpath)s"

if [ "x$SHLIBPATH" != "x" ]; then
    %(shlibpath_var)s="$SHLIBPATH:$%(shlibpath_var)s"
    export %(shlibpath_var)s
fi

MOD_WSGI_SERVER_ROOT="%(server_root)s"

export MOD_WSGI_SERVER_ROOT

MOD_WSGI_LISTENER_HOST="%(host)s"

export MOD_WSGI_LISTENER_HOST

MOD_WSGI_HTTP_PORT="%(port)s"
MOD_WSGI_HTTPS_PORT="%(https_port)s"

export MOD_WSGI_HTTP_PORT
export MOD_WSGI_HTTPS_PORT

WSGI_RUN_USER="${WSGI_RUN_USER:-%(user)s}"
WSGI_RUN_GROUP="${WSGI_RUN_GROUP:-%(group)s}"

MOD_WSGI_USER="${MOD_WSGI_USER:-${WSGI_RUN_USER}}"
MOD_WSGI_GROUP="${MOD_WSGI_GROUP:-${WSGI_RUN_GROUP}}"

export MOD_WSGI_USER
export MOD_WSGI_GROUP

if [ `id -u` = "0" -a ${MOD_WSGI_USER} = "root" ]; then
    cat << EOF

WARNING: When running as the 'root' user, it is required that the options
'--user' and '--group' be specified to mod_wsgi-express. These should
define a non 'root' user and group under which the Apache child worker
processes and mod_wsgi daemon processes should be run. Failure to specify
these options will result in Apache and/or the mod_wsgi daemon processes
failing to start. See the mod_wsgi-express documentation for further
information on this restriction.

EOF

fi

MOD_WSGI_WORKING_DIRECTORY="%(working_directory)s"

export MOD_WSGI_WORKING_DIRECTORY

LANG='%(lang)s'
LC_ALL='%(locale)s'

export LANG
export LC_ALL

ACMD="$1"
ARGV="$@"

if test -f %(server_root)s/envvars; then
    . %(server_root)s/envvars
fi

STATUSURL="http://%(host)s:%(port)s/server-status"

if [ "x$ARGV" = "x" ]; then
    ARGV="-h"
fi

GDB="%(gdb_executable)s"
ENABLE_GDB="%(enable_gdb)s"

PROCESS_NAME="%(process_name)s"

cd $MOD_WSGI_WORKING_DIRECTORY

case $ACMD in
start|stop|restart|graceful|graceful-stop)
    if [ "x$ENABLE_GDB" != "xTrue" ]; then
        exec -a "$PROCESS_NAME" $HTTPD_COMMAND -k $ARGV
    else
        echo "run $HTTPD_ARGS -k $ARGV" > %(server_root)s/gdb.cmds
        gdb -x %(server_root)s/gdb.cmds $HTTPD
    fi
    ;;
configtest)
    exec $HTTPD_COMMAND -t
    ;;
status)
    exec %(python_executable)s -m webbrowser -t $STATUSURL
    ;;
*)
    exec $HTTPD_COMMAND $ARGV
esac
"""

APACHE_ENVVARS_FILE = """
. %(envvars_script)s
"""

def generate_control_scripts(options):
    path = os.path.join(options['server_root'], 'apachectl')
    with open(path, 'w') as fp:
        print(WSGI_CONTROL_SCRIPT.lstrip() % options, file=fp)

    os.chmod(path, 0o755)

    path = os.path.join(options['server_root'], 'envvars')

    if options['envvars_script']:
        with open(path, 'w') as fp:
            if options['envvars_script']:
                print(APACHE_ENVVARS_FILE.lstrip() % options, file=fp)

    elif not os.path.isfile(path):
        with open(path, 'w') as fp:
            pass

def check_percentage(option, opt_str, value, parser):
    if value is not None and value < 0 or value > 1:
        raise optparse.OptionValueError('%s option value needs to be within '
                'the range 0 to 1.' % opt_str)
    setattr(parser.values, option.dest, value)

option_list = []

def add_option(platforms, *args, **kwargs):
    targets = platforms.split('|')

    suppress = False

    if os.name == 'nt':
        if 'all' not in targets and 'windows' not in targets:
            suppress = True
    else:
        if 'all' not in targets and 'unix' not in targets:
            suppress = True

    if suppress:
        kwargs['help'] = optparse.SUPPRESS_HELP

    if 'hidden' in targets:
        kwargs['help'] = optparse.SUPPRESS_HELP

    option_list.append(optparse.make_option(*args, **kwargs))

add_option('all', '--application-type', default='script',
        metavar='TYPE', help='The type of WSGI application entry point '
        'that was provided. Defaults to \'script\', indicating the '
        'traditional mod_wsgi style WSGI script file specified by a '
        'filesystem path. Alternatively one can supply \'module\', '
        'indicating that the provided entry point is a Python module '
        'which should be imported using the standard Python import '
        'mechanism, or \'paste\' indicating that the provided entry '
        'point is a Paste deployment configuration file. If you want '
        'to just use the server to host static files only, then you '
        'can also instead supply \'static\' with the target being '
        'the directory containing the files to server or the current '
        'directory if none is supplied.')

add_option('all', '--entry-point', default=None,
        metavar='FILE-PATH|MODULE', help='The file system path or '
        'module name identifying the file which contains the WSGI '
        'application entry point. How the value given is interpreted '
        'depends on the corresponding type identified using the '
        '\'--application-type\' option. Use of this option is the '
        'same as if the value had been given as argument but without '
        'any option specifier. A named option is also provided so '
        'as to make it clearer in a long option list what the entry '
        'point actually is. If both methods are used, that specified '
        'by this option will take precedence.')

add_option('all', '--host', default=None, metavar='IP-ADDRESS',
        help='The specific host (IP address) interface on which '
        'requests are to be accepted. Defaults to listening on '
        'all host interfaces.')

add_option('all', '--port', default=8000, type='int',
        metavar='NUMBER', help='The specific port to bind to and '
        'on which requests are to be accepted. Defaults to port 8000.')

add_option('all', '--http2', action='store_true', default=False,
        help='Flag indicating whether HTTP/2 should be enabled.'
        'Requires the mod_http2 module to be available.')

add_option('all', '--https-port', type='int', metavar='NUMBER',
        help='The specific port to bind to and on which secure '
        'requests are to be accepted.')

add_option('all', '--ssl-port', type='int', metavar='NUMBER',
        dest='https_port', help=optparse.SUPPRESS_HELP)

add_option('all', '--ssl-certificate-file', default=None,
        metavar='FILE-PATH', help='Specify the path to the SSL '
        'certificate file.')

add_option('all', '--ssl-certificate-key-file', default=None,
        metavar='FILE-PATH', help='Specify the path to the private '
        'key file corresponding to the SSL certificate file.')

add_option('all', '--ssl-certificate', default=None,
        metavar='FILE-PATH', help='Specify the common path to the SSL '
        'certificate files. This is a convenience function so that '
        'only one option is required to specify the location of the '
        'certificate file and the private key file. It is expected that '
        'the files have \'.crt\' and \'.key\' extensions. This option '
        'should refer to the common part of the names for both files '
        'which appears before the extension.')

add_option('all', '--ssl-ca-certificate-file', default=None,
        metavar='FILE-PATH', help='Specify the path to the file with '
        'the CA certificates to be used for client authentication. When '
        'specified, access to the whole site will by default require '
        'client authentication. To require client authentication for '
        'only parts of the site, use the --ssl-verify-client option.')

add_option('all', '--ssl-verify-client', action='append',
        metavar='URL-PATH', dest='ssl_verify_client_urls',
        help='Specify a sub URL of the site for which client '
        'authentication is required. When this option is specified, '
        'the default of client authentication being required for the '
        'whole site will be disabled and verification will only be '
        'required for the specified sub URL.')

add_option('all', '--ssl-certificate-chain-file', default=None,
        metavar='FILE-PATH', help='Specify the path to a file '
        'containing the certificates of Certification Authorities (CA) '
        'which form the certificate chain of the server certificate.')

add_option('all', '--ssl-environment', action='store_true',
        default=False, help='Flag indicating whether the standard set '
        'of SSL related variables are passed in the per request '
        'environment passed to a handler.')

add_option('all', '--https-only', action='store_true',
        default=False, help='Flag indicating whether any requests '
        'made using a HTTP request over the non secure connection '
        'should be redirected automatically to use a HTTPS request '
        'over the secure connection.')

add_option('all', '--hsts-policy', default=None, metavar='PARAMS',
        help='Specify the HSTS policy that should be applied when '
        'HTTPS only connections are being enforced.')

add_option('all', '--server-name', default=None, metavar='HOSTNAME',
        help='The primary host name of the web server. If this name '
        'starts with \'www.\' then an automatic redirection from the '
        'parent domain name to the \'www.\' server name will created.')

add_option('all', '--server-alias', action='append',
        dest='server_aliases', metavar='HOSTNAME', help='A secondary '
        'host name for the web server. May include wildcard patterns.')

add_option('all', '--allow-localhost', action='store_true',
        default=False, help='Flag indicating whether access via '
        'localhost should still be allowed when a server name has been '
        'specified and a name based virtual host has been configured.')

add_option('unix', '--processes', type='int', metavar='NUMBER',
        help='The number of worker processes (instances of the WSGI '
        'application) to be started up and which will handle requests '
        'concurrently. Defaults to a single process.')

add_option('all', '--threads', type='int', default=5, metavar='NUMBER',
        help='The number of threads in the request thread pool of '
        'each process for handling requests. Defaults to 5 in each '
        'process. Note that if embedded mode and only prefork MPM '
        'is available, then processes will instead be used.')

add_option('unix', '--max-clients', type='int', default=None,
        metavar='NUMBER', help='The maximum number of simultaneous '
        'client connections that will be accepted. This will default '
        'to being 1.5 times the total number of threads in the '
        'request thread pools across all process handling requests. '
        'Note that if embedded mode is used this will be ignored.')

add_option('unix', '--initial-workers', type='float', default=None,
        metavar='NUMBER', action='callback', callback=check_percentage,
        help='The initial number of workers to create on startup '
        'expressed as a percentage of the maximum number of clients. '
        'The value provided should be between 0 and 1. The default is '
        'dependent on the type of MPM being used. Note that if '
        'embedded mode is used, this will be ignored.'),

add_option('unix', '--minimum-spare-workers', type='float',
        default=None, metavar='NUMBER', action='callback',
        callback=check_percentage, help='The minimum number of spare '
        'workers to maintain expressed as a percentage of the maximum '
        'number of clients. The value provided should be between 0 and '
        '1. The default is dependent on the type of MPM being used. '
        'Note that if embedded mode is used, this will be ignored.')

add_option('unix', '--maximum-spare-workers', type='float',
        default=None, metavar='NUMBER', action='callback',
        callback=check_percentage, help='The maximum number of spare '
        'workers to maintain expressed as a percentage of the maximum '
        'number of clients. The value provided should be between 0 and '
        '1. The default is dependent on the type of MPM being used. '
        'Note that if embedded mode is used, this will be ignored.')

add_option('all', '--limit-request-body', type='int', default=10485760,
        metavar='NUMBER', help='The maximum number of bytes which are '
        'allowed in a request body. Defaults to 10485760 (10MB).')

add_option('all', '--maximum-requests', type='int', default=0,
        metavar='NUMBER', help='The number of requests after which '
        'any one worker process will be restarted and the WSGI '
        'application reloaded. Defaults to 0, indicating that the '
        'worker process should never be restarted based on the number '
        'of requests received.')

add_option('unix', '--startup-timeout', type='int', default=15,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass waiting for the application to be successfully '
        'loaded and started by a worker process. When this timeout '
        'has been reached without the application having been '
        'successfully loaded and started, the worker process will '
        'be forced to restart. Defaults to 15 seconds.')

add_option('unix', '--shutdown-timeout', type='int', default=5,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass when waiting for a worker process to shutdown as a '
        'result of the maximum number of requests or inactivity timeout '
        'being reached, or when a user initiated SIGINT signal is sent '
        'to a worker process. When this timeout has been reached the '
        'worker process will be forced to exit even if there are '
        'still active requests or it is still running Python exit '
        'functions. Defaults to 5 seconds.')

add_option('unix', '--restart-interval', type='int', default='0',
        metavar='SECONDS', help='Number of seconds between worker '
        'process restarts. If graceful timeout is also specified, '
        'active requests will be given a chance to complete before '
        'the process is forced to exit and restart. Not enabled by '
        'default.')

add_option('unix', '--cpu-time-limit', type='int', default='0',
        metavar='SECONDS', help='Number of seconds of CPU time the '
        'process can use before it will be restarted. If graceful '
        'timeout is also specified, active requests will be given '
        'a chance to complete before the process is forced to exit '
        'and restart. Not enabled by default.')

add_option('unix', '--graceful-timeout', type='int', default=15,
        metavar='SECONDS', help='Grace period for requests to complete '
        'normally, while still accepting new requests, when worker '
        'processes are being shutdown and restarted due to maximum '
        'requests being reached or restart interval having expired. '
        'Defaults to 15 seconds.')

add_option('unix', '--eviction-timeout', type='int', default=0,
        metavar='SECONDS', help='Grace period for requests to complete '
        'normally, while still accepting new requests, when the WSGI '
        'application is being evicted from the worker processes, and '
        'the process restarted, due to forced graceful restart signal. '
        'Defaults to timeout specified by \'--graceful-timeout\' '
        'option.')

add_option('unix', '--deadlock-timeout', type='int', default=60,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass before the worker process is forcibly shutdown and '
        'restarted after a potential deadlock on the Python GIL has '
        'been detected. Defaults to 60 seconds.')

add_option('unix', '--inactivity-timeout', type='int', default=0,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass before the worker process is shutdown and restarted '
        'when the worker process has entered an idle state and is no '
        'longer receiving new requests. Not enabled by default.')

add_option('unix', '--ignore-activity', action='append',
        dest='ignore_activity', metavar='URL-PATH', help='Specify '
        'the URL path for any location where activity should be '
        'ignored when the \'--activity-timeout\' option is used. '
        'This would be used on health check URLs so that health '
        'checks do not prevent process restarts due to inactivity.')

add_option('unix', '--request-timeout', type='int', default=60,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass before the worker process is forcibly shutdown and '
        'restarted when a request does not complete in the expected '
        'time. In a multi threaded worker, the request time is '
        'calculated as an average across all request threads. Defaults '
        'to 60 seconds.')

add_option('unix', '--connect-timeout', type='int', default=15,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass before giving up on attempting to get a connection '
        'to the worker process from the Apache child process which '
        'accepted the request. This comes into play when the worker '
        'listener backlog limit is exceeded. Defaults to 15 seconds.')

add_option('all', '--socket-timeout', type='int', default=60,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass before timing out on a read or write operation on '
        'a socket and aborting the request. Defaults to 60 seconds.')

add_option('all', '--queue-timeout', type='int', default=45,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'for a request to be accepted by a worker process to be '
        'handled, taken from the time when the Apache child process '
        'originally accepted the request. Defaults to 45 seconds.')

add_option('all', '--header-timeout', type='int', default=15,
        metavar='SECONDS', help='The number of seconds allowed for '
        'receiving the request including the headers. This may be '
        'dynamically increased if a minimum rate for reading the '
        'request and headers is also specified, up to any limit '
        'imposed by a maximum header timeout. Defaults to 15 seconds.')

add_option('all', '--header-max-timeout', type='int', default=30,
        metavar='SECONDS', help='Maximum number of seconds allowed for '
        'receiving the request including the headers. This is the hard '
        'limit after taking into consideration and increases to the '
        'basic timeout due to minimum rate for reading the request and '
        'headers which may be specified. Defaults to 30 seconds.')

add_option('all', '--header-min-rate', type='int', default=500,
        metavar='BYTES', help='The number of bytes required to be sent '
        'as part of the request and headers to trigger a dynamic '
        'increase in the timeout on receiving the request including '
        'headers. Each time this number of bytes is received the timeout '
        'will be increased by 1 second up to any maximum specified by '
        'the maximum header timeout. Defaults to 500 bytes.')

add_option('all', '--body-timeout', type='int', default=15,
        metavar='SECONDS', help='The number of seconds allowed for '
        'receiving the request body. This may be dynamically increased '
        'if a minimum rate for reading the request body is also '
        'specified, up to any limit imposed by a maximum body timeout. '
        'Defaults to 15 seconds.')

add_option('all', '--body-max-timeout', type='int', default=0,
        metavar='SECONDS', help='Maximum number of seconds allowed for '
        'receiving the request body. This is the hard limit after '
        'taking into consideration and increases to the basic timeout '
        'due to minimum rate for reading the request body which may be '
        'specified. Defaults to 0 indicating there is no maximum.')

add_option('all', '--body-min-rate', type='int', default=500,
        metavar='BYTES', help='The number of bytes required to be sent '
        'as part of the request body to trigger a dynamic increase in '
        'the timeout on receiving the request body. Each time this '
        'number of bytes is received the timeout will be increased '
        'by 1 second up to any maximum specified by the maximum body '
        'timeout. Defaults to 500 bytes.')

add_option('all', '--server-backlog', type='int', default=500,
        metavar='NUMBER', help='Depth of server socket listener '
        'backlog for Apache child processes. Defaults to 500.')

add_option('unix', '--daemon-backlog', type='int', default=100,
        metavar='NUMBER', help='Depth of server socket listener '
        'backlog for daemon processes. Defaults to 100.')

add_option('unix', '--send-buffer-size', type='int', default=0,
        metavar='NUMBER', help='Size of socket buffer for sending '
        'data to daemon processes. Defaults to 0, indicating '
        'the system default socket buffer size is used.')

add_option('unix', '--receive-buffer-size', type='int', default=0,
        metavar='NUMBER', help='Size of socket buffer for receiving '
        'data from daemon processes. Defaults to 0, indicating '
        'the system default socket buffer size is used.')

add_option('unix', '--header-buffer-size', type='int', default=0,
        metavar='NUMBER', help='Size of buffer used for reading '
        'response headers from daemon processes. Defaults to 0, '
        'indicating internal default of 32768 bytes is used.')

add_option('unix', '--response-buffer-size', type='int', default=0,
        metavar='NUMBER', help='Maximum amount of response content '
        'that will be allowed to be buffered in the Apache child '
        'worker process when proxying the response from a daemon '
        'process. Defaults to 0, indicating internal default of '
        '65536 bytes is used.')

add_option('unix', '--response-socket-timeout', type='int', default=0,
        metavar='SECONDS', help='Maximum number of seconds allowed '
        'to pass before timing out on a write operation back to the '
        'HTTP client when the response buffer has filled and data is '
        'being forcibly flushed. Defaults to 0 seconds indicating that '
        'it will default to the value of the \'socket-timeout\' option.')

add_option('all', '--enable-sendfile', action='store_true',
        default=False, help='Flag indicating whether sendfile() support '
        'should be enabled. Defaults to being disabled. This should '
        'only be enabled if the operating system kernel and file system '
        'type where files are hosted supports it.')

add_option('unix', '--disable-reloading', action='store_true',
        default=False, help='Disables all reloading of daemon processes '
        'due to changes to the file containing the WSGI application '
        'entrypoint, or any other loaded source files. This has no '
        'effect when embedded mode is used as reloading is automatically '
        'disabled for embedded mode.')

add_option('unix', '--reload-on-changes', action='store_true',
        default=False, help='Flag indicating whether worker processes '
        'should be automatically restarted when any Python code file '
        'loaded by the WSGI application has been modified. Defaults to '
        'being disabled. When reloading on any code changes is disabled, '
        'unless all reloading is also disabled, the worker processes '
        'will still though be reloaded if the file containing the WSGI '
        'application entrypoint is modified.')

add_option('unix', '--user', default=default_run_user(),
        metavar='USERNAME', help='When being run by the root user, '
        'the user that the WSGI application should be run as.')

add_option('unix', '--group', default=default_run_group(),
        metavar='GROUP', help='When being run by the root user, the '
        'group that the WSGI application should be run as.')

add_option('all', '--callable-object', default='application',
        metavar='NAME', help='The name of the entry point for the WSGI '
        'application within the WSGI script file. Defaults to '
        'the name \'application\'.')

add_option('all', '--map-head-to-get', default='Auto',
        metavar='OFF|ON|AUTO', help='Flag indicating whether HEAD '
        'requests should be mapped to a GET request. By default a HEAD '
        'request will be automatically mapped to a GET request when an '
        'Apache output filter is detected that may want to see the '
        'entire response in order to set up response headers correctly '
        'for a HEAD request. This can be disable by setting to \'Off\'.')

add_option('all', '--document-root', metavar='DIRECTORY-PATH',
        help='The directory which should be used as the document root '
        'and which contains any static files.')

add_option('all', '--directory-index', metavar='FILE-NAME',
        help='The name of a directory index resource to be found in the '
        'document root directory. Requests mapping to the directory '
        'will be mapped to this resource rather than being passed '
        'through to the WSGI application.')

add_option('all', '--directory-listing', action='store_true',
        default=False, help='Flag indicating if directory listing '
        'should be enabled where static file application type is '
        'being used and no directory index file has been specified.')

add_option('all', '--allow-override', metavar='DIRECTIVE-TYPE',
        action='append', help='Allow directives to be overridden from a '
        '\'.htaccess\' file. Defaults to \'None\', indicating that any '
        '\'.htaccess\' file will be ignored with override directives '
        'not being permitted.')

add_option('all', '--mount-point', metavar='URL-PATH', default='/',
        help='The URL path at which the WSGI application will be '
        'mounted. Defaults to being mounted at the root URL of the '
        'site.')

add_option('all', '--url-alias', action='append', nargs=2,
        dest='url_aliases', metavar='URL-PATH FILE-PATH|DIRECTORY-PATH',
        help='Map a single static file or a directory of static files '
        'to a sub URL.')

add_option('all', '--error-document', action='append', nargs=2,
        dest='error_documents', metavar='STATUS URL-PATH', help='Map '
        'a specific sub URL as the handler for HTTP errors generated '
        'by the web server.')

add_option('all', '--error-override', action='store_true',
        default=False, help='Flag indicating whether Apache error '
        'documents will override application error responses.')

add_option('all', '--proxy-mount-point', action='append', nargs=2,
        dest='proxy_mount_points', metavar='URL-PATH URL',
        help='Map a sub URL such that any requests against it will be '
        'proxied to the specified URL. This is only for proxying to a '
        'site as a whole, or a sub site, not individual resources.')

add_option('all', '--proxy-url-alias', action='append', nargs=2,
        dest='proxy_mount_points', metavar='URL-PATH URL',
        help=optparse.SUPPRESS_HELP)

add_option('all', '--proxy-virtual-host', action='append', nargs=2,
        dest='proxy_virtual_hosts', metavar='HOSTNAME URL',
        help='Proxy any requests for the specified host name to the '
        'remote URL.')

add_option('all', '--trust-proxy-header', action='append', default=[],
        dest='trusted_proxy_headers', metavar='HEADER-NAME',
        help='The name of any trusted HTTP header providing details '
        'of the front end client request when proxying.')

add_option('all', '--trust-proxy', action='append', default=[],
        dest='trusted_proxies', metavar='IP-ADDRESS/SUBNET',
        help='The IP address or subnet corresponding to any trusted '
        'proxy.')

add_option('all', '--keep-alive-timeout', type='int', default=2,
        metavar='SECONDS', help='The number of seconds which a client '
        'connection will be kept alive to allow subsequent requests '
        'to be made over the same connection when a keep alive '
        'connection is requested. Defaults to 2, indicating that keep '
        'alive connections are set for 2 seconds.')

add_option('all', '--compress-responses', action='store_true',
        default=False, help='Flag indicating whether responses for '
        'common text based responses, such as plain text, HTML, XML, '
        'CSS and Javascript should be compressed.')

add_option('all', '--server-metrics', action='store_true',
        default=False, help='Flag indicating whether internal server '
        'metrics will be available within the WSGI application. '
        'Defaults to being disabled.')

add_option('all', '--server-status', action='store_true',
        default=False, help='Flag indicating whether web server status '
        'will be available at the /server-status sub URL. Defaults to '
        'being disabled.')

add_option('all', '--host-access-script', metavar='SCRIPT-PATH',
        default=None, help='Specify a Python script file for '
        'performing host access checks.')

add_option('all', '--auth-user-script', metavar='SCRIPT-PATH',
        default=None, help='Specify a Python script file for '
        'performing user authentication.')

add_option('all', '--auth-type', metavar='TYPE',
        default='Basic', help='Specify the type of authentication '
        'scheme used when authenticating users. Defaults to using '
        '\'Basic\'. Alternate schemes available are \'Digest\'.')

add_option('all', '--auth-group-script', metavar='SCRIPT-PATH',
        default=None, help='Specify a Python script file for '
        'performing group based authorization in conjunction with '
        'a user authentication script.')

add_option('all', '--auth-group', metavar='NAME',
        default='wsgi', help='Specify the group which users should '
        'be a member of when using a group based authorization script. '
        'Defaults to \'wsgi\' as a place holder but should be '
        'overridden to be the actual group you use rather than '
        'making your group name match the default.')

add_option('all', '--include-file', action='append',
        dest='include_files', metavar='FILE-PATH', help='Specify the '
        'path to an additional web server configuration file to be '
        'included at the end of the generated web server configuration '
        'file.')

add_option('all', '--rewrite-rules', metavar='FILE-PATH',
        help='Specify an alternate server configuration file which '
        'contains rewrite rules. Defaults to using the '
        '\'rewrite.conf\' stored under the server root directory.')

add_option('unix', '--envvars-script', metavar='FILE-PATH',
        help='Specify an alternate script file for user defined web '
        'server environment variables. Defaults to using the '
        '\'envvars\' stored under the server root directory.')

add_option('unix', '--lang', default=None, metavar='NAME',
        help=optparse.SUPPRESS_HELP)

add_option('all', '--locale', default=None, metavar='NAME',
        help='Specify the natural language locale for the process '
        'as normally defined by the \'LC_ALL\' environment variable. '
        'If not specified, then the default locale for this process '
        'will be used. If the default locale is however \'C\' or '
        '\'POSIX\' then an attempt will be made to use either the '
        '\'en_US.UTF-8\' or \'C.UTF-8\' locales and if that is not '
        'possible only then fallback to the default locale of this '
        'process.')

add_option('all', '--setenv', action='append', nargs=2,
        dest='setenv_variables', metavar='KEY VALUE', help='Specify '
        'a name/value pairs to be added to the per request WSGI environ '
        'dictionary')

add_option('all', '--passenv', action='append',
        dest='passenv_variables', metavar='KEY', help='Specify the '
        'names of any process level environment variables which should '
        'be passed as a name/value pair in the per request WSGI '
        'environ dictionary.')

add_option('all', '--working-directory', metavar='DIRECTORY-PATH',
        help='Specify the directory which should be used as the '
        'current working directory of the WSGI application. This '
        'directory will be searched when importing Python modules '
        'so long as the WSGI application doesn\'t subsequently '
        'change the current working directory. Defaults to the '
        'directory this script is run from.')

add_option('all', '--pid-file', metavar='FILE-PATH',
        help='Specify an alternate file to be used to store the '
        'process ID for the root process of the web server.')

add_option('all', '--server-root', metavar='DIRECTORY-PATH',
        help='Specify an alternate directory for where the generated '
        'web server configuration, startup files and logs will be '
        'stored. On Linux defaults to the sub directory specified by '
        'the TMPDIR environment variable, or /tmp if not specified. '
        'On macOS, defaults to the /var/tmp directory.')

add_option('unix', '--server-mpm', action='append',
        dest='server_mpm_variables', metavar='NAME', help='Specify '
        'preferred MPM to use when using Apache 2.4 with dynamically '
        'loadable MPMs and more than one is available. By default '
        'the MPM precedence order when no preference is given is '
        '\"event\", \"worker" and \"prefork\".')

add_option('all', '--log-directory', metavar='DIRECTORY-PATH',
        help='Specify an alternate directory for where the log files '
        'will be stored. Defaults to the server root directory.')

add_option('all', '--log-level', default='warn', metavar='NAME',
        help='Specify the log level for logging. Defaults to \'warn\'.')

add_option('all', '--access-log', action='store_true', default=False,
        help='Flag indicating whether the web server access log '
        'should be enabled. Defaults to being disabled.')

add_option('unix', '--startup-log', action='store_true', default=False,
        help='Flag indicating whether the web server startup log should '
        'be enabled. Defaults to being disabled.')

add_option('all', '--verbose-debugging', action='store_true',
        dest='verbose_debugging', help=optparse.SUPPRESS_HELP)

add_option('unix', '--log-to-terminal', action='store_true',
        default=False, help='Flag indicating whether logs should '
        'be directed back to the terminal. Defaults to being disabled. '
        'If --log-directory is set explicitly, it will override this '
        'option. If logging to the terminal is carried out, any '
        'rotating of log files will be disabled.')

add_option('all', '--access-log-format', metavar='FORMAT',
        help='Specify the format of the access log records.'),

add_option('all', '--error-log-format', metavar='FORMAT',
        help='Specify the format of the error log records.'),

add_option('all', '--error-log-name', metavar='FILE-NAME',
        default='error_log', help='Specify the name of the error '
        'log file when it is being written to the log directory.'),

add_option('all', '--access-log-name', metavar='FILE-NAME',
        default='access_log', help='Specify the name of the access '
        'log file when it is being written to the log directory.'),

add_option('unix', '--startup-log-name', metavar='FILE-NAME',
        default='startup_log', help='Specify the name of the startup '
        'log file when it is being written to the log directory.'),

add_option('unix', '--rotate-logs', action='store_true', default=False,
        help='Flag indicating whether log rotation should be performed.'),

add_option('unix', '--max-log-size', default=5, type='int',
        metavar='MB', help='The maximum size in MB the log file should '
        'be allowed to reach before log file rotation is performed.'),

add_option('unix', '--rotatelogs-executable',
        default=apxs_config.ROTATELOGS, metavar='FILE-PATH',
        help='Override the path to the rotatelogs executable.'),

add_option('all', '--python-path', action='append',
        dest='python_paths', metavar='DIRECTORY-PATH', help='Specify '
        'the path to any additional directory that should be added to '
        'the Python module search path. Note that these directories will '
        'not be processed for \'.pth\' files. If processing of \'.pth\' '
        'files is required, set the \'PYTHONPATH\' environment variable '
        'in a script specified by the \'--envvars-script\' option.')

add_option('all', '--python-eggs', metavar='DIRECTORY-PATH',
        help='Specify an alternate directory which should be used for '
        'unpacking of Python eggs. Defaults to a sub directory of '
        'the server root directory.')

add_option('unix', '--shell-executable', default=SHELL,
        metavar='FILE-PATH', help='Override the path to the shell '
        'used in the \'apachectl\' script. The \'bash\' shell will '
        'be used if available.')

add_option('unix', '--httpd-executable', default=apxs_config.HTTPD,
        metavar='FILE-PATH', help='Override the path to the Apache web '
        'server executable.')

add_option('unix', '--process-name', metavar='NAME', help='Override '
        'the name given to the Apache parent process. This might be '
        'needed when a process manager expects the process to be named '
        'a certain way but due to a sequence of exec calls the name '
        'changed.')

add_option('all', '--modules-directory', default=apxs_config.LIBEXECDIR,
        metavar='DIRECTORY-PATH', help='Override the path to the Apache '
        'web server modules directory.')

add_option('unix', '--mime-types', default=find_mimetypes(),
        metavar='FILE-PATH', help='Override the path to the mime types '
        'file used by the web server.')

add_option('unix', '--socket-prefix', metavar='DIRECTORY-PATH',
        help='Specify an alternate directory name prefix to be used '
        'for the UNIX domain sockets used by mod_wsgi to communicate '
        'between the Apache child processes and the daemon processes.')

add_option('all', '--add-handler', action='append', nargs=2,
        dest='handler_scripts', metavar='EXTENSION SCRIPT-PATH',
        help='Specify a WSGI application to be used as a special '
        'handler for any resources matched from the document root '
        'directory with a specific extension type.')

add_option('all', '--chunked-request', action='store_true',
        default=False, help='Flag indicating whether requests which '
        'use chunked transfer encoding will be accepted.')

add_option('hidden', '--with-newrelic', action='store_true',
        default=False, help='Flag indicating whether all New Relic '
        'performance monitoring features should be enabled.')

add_option('hidden', '--with-newrelic-agent', action='store_true',
        default=False, help='Flag indicating whether the New Relic '
        'Python agent should be enabled for reporting application server '
        'metrics.')

add_option('hidden', '--with-newrelic-platform', action='store_true',
        default=False, help='Flag indicating whether the New Relic '
        'platform plugin should be enabled for reporting server level '
        'metrics.')

add_option('hidden', '--newrelic-config-file', metavar='FILE-PATH',
        default='', help='Specify the location of the New Relic agent '
        'configuration file.')

add_option('hidden', '--newrelic-environment', metavar='NAME',
        default='', help='Specify the name of the environment section '
        'that should be used from New Relic agent configuration file.')

add_option('hidden', '--with-php5', action='store_true', default=False,
        help='Flag indicating whether PHP 5 support should be enabled. '
        'PHP code files must use the \'.php\' extension.')

add_option('all', '--with-cgi', action='store_true', default=False,
        help='Flag indicating whether CGI script support should be '
        'enabled. CGI scripts must use the \'.cgi\' extension and be '
        'executable')

add_option('unix', '--service-script', action='append', nargs=2,
        dest='service_scripts', metavar='SERVICE SCRIPT-PATH',
        help='Specify the name of a Python script to be loaded and '
        'executed in the context of a distinct daemon process. Used '
        'for running a managed service.')

add_option('unix', '--service-user', action='append', nargs=2,
        dest='service_users', metavar='SERVICE USERNAME',
        help='When being run by the root user, the user that the '
        'distinct daemon process started to run the managed service '
        'should be run as.')

add_option('unix', '--service-group', action='append', nargs=2,
        dest='service_groups', metavar='SERVICE GROUP',
        help='When being run by the root user, the group that the '
        'distinct daemon process started to run the managed service '
        'should be run as.')

add_option('unix', '--service-log-file', action='append', nargs=2,
        dest='service_log_files', metavar='SERVICE FILE-NAME',
        help='Specify the name of a separate log file to be used for '
        'the managed service.')

add_option('all', '--orphan-interpreter', action='store_true',
        default=False, help='Flag indicating whether should skip over '
        'destroying the Python interpreter on process shutdown.')

add_option('unix', '--embedded-mode', action='store_true', default=False,
        help='Flag indicating whether to run in embedded mode rather '
        'than the default daemon mode. Numerous daemon mode specific '
        'features will not operate when this mode is used.')

add_option('all', '--enable-docs', action='store_true', default=False,
        help='Flag indicating whether the mod_wsgi documentation should '
        'be made available at the /__wsgi__/docs sub URL.')

add_option('unix', '--debug-mode', action='store_true', default=False,
        help='Flag indicating whether to run in single process mode '
        'to allow the running of an interactive Python debugger. This '
        'will override all options related to processes, threads and '
        'communication with workers. All forms of source code reloading '
        'will also be disabled. Both stdin and stdout will be attached '
        'to the console to allow interaction with the Python debugger.')

add_option('unix', '--enable-debugger', action='store_true',
        default=False, help='Flag indicating whether post mortem '
        'debugging of any exceptions which propagate out from the '
        'WSGI application when running in debug mode should be '
        'performed. Post mortem debugging is performed using the '
        'Python debugger (pdb).'),

add_option('unix', '--debugger-startup', action='store_true',
        default=False, help='Flag indicating whether when post '
        'mortem debugging is enabled, that the debugger should '
        'also be thrown into the interactive console on initial '
        'startup of the server to allow breakpoints to be setup.'),

add_option('unix', '--enable-coverage', action='store_true',
        default=False, help='Flag indicating whether coverage analysis '
        'is enabled when running in debug mode.')

add_option('unix', '--coverage-directory', metavar='DIRECTORY-PATH',
        default='', help='Override the path to the directory into '
        'which coverage analysis will be generated when enabled under '
        'debug mode.')

add_option('unix', '--enable-profiler', action='store_true',
        default=False, help='Flag indicating whether code profiling '
        'is enabled when running in debug mode.')

add_option('unix', '--profiler-directory', metavar='DIRECTORY-PATH',
        default='', help='Override the path to the directory into '
        'which profiler data will be written when enabled under debug '
        'mode.')

add_option('unix', '--enable-recorder', action='store_true',
        default=False, help='Flag indicating whether recording of '
        'requests is enabled when running in debug mode.')

add_option('unix', '--recorder-directory', metavar='DIRECTORY-PATH',
        default='', help='Override the path to the directory into '
        'which recorder data will be written when enabled under debug '
        'mode.')

add_option('unix', '--enable-gdb', action='store_true',
        default=False, help='Flag indicating whether Apache should '
        'be run under \'gdb\' when running in debug mode. This '
        'would be use to debug process crashes.')

add_option('unix', '--gdb-executable', default='gdb',
        metavar='FILE-PATH', help='Override the path to the gdb '
        'executable.')

add_option('unix', '--setup-only', action='store_true', default=False,
        help='Flag indicating that after the configuration files have '
        'been setup, that the command should then exit and not go on '
        'to actually run up the Apache server. This is to allow for '
        'the generation of the configuration with Apache then later '
        'being started separately using the generated \'apachectl\' '
        'script.')

# add_option('unix', '--isatty', action='store_true', default=False,
#         help='Flag indicating whether should assume being run in an '
#         'interactive terminal session. In this case Apache will not '
#         'replace this wrapper script, but will be run as a sub process.'
#         'Signals such as SIGINT, SIGTERM, SIGHUP and SIGUSR1 will be '
#         'forwarded onto Apache, but SIGWINCH will be blocked so that '
#         'resizing of a terminal session window will not cause Apache '
#         'to shutdown. This is a separate option at this time rather '
#         'than being determined automatically while the reliability of '
#         'intercepting and forwarding signals is verified.')

def cmd_setup_server(params):
    formatter = optparse.IndentedHelpFormatter()
    formatter.set_long_opt_delimiter(' ')

    usage = '%prog setup-server script [options]'
    parser = optparse.OptionParser(usage=usage, option_list=option_list,
            formatter=formatter)

    (options, args) = parser.parse_args(params)

    _cmd_setup_server('setup-server', args, vars(options))

def _mpm_module_defines(modules_directory, preferred=None):
    if os.name == 'nt':
        return ['-DMOD_WSGI_MPM_ENABLE_WINNT_MODULE']

    result = []
    workers = ['event', 'worker', 'prefork']
    found = False
    for name in workers:
        if not preferred or name in preferred:
            if os.path.exists(os.path.join(modules_directory,
                    'mod_mpm_%s.so' % name)):
                if not found:
                    result.append('-DMOD_WSGI_MPM_ENABLE_%s_MODULE' % name.upper())
                    found = True
                result.append('-DMOD_WSGI_MPM_EXISTS_%s_MODULE' % name.upper())
    return result

def _cmd_setup_server(command, args, options):
    options['sys_argv'] = repr(sys.argv)

    options['mod_wsgi_so'] = where()

    options['working_directory'] = options['working_directory'] or os.getcwd()
    options['working_directory'] = os.path.abspath(options['working_directory'])

    if not options['host']:
        options['listener_host'] = None
        options['host'] = 'localhost'
    else:
        options['listener_host'] = options['host']

    if os.name == 'nt':
        options['daemon_name'] = '(wsgi:%s:%s:%s)' % (options['host'],
            options['port'], getpass.getuser())
    else:
        options['daemon_name'] = '(wsgi:%s:%s:%s)' % (options['host'],
            options['port'], os.getuid())

    if not options['server_root']:
        if os.name == 'nt':
            tmpdir = tempfile.gettempdir()
        elif sys.platform == 'darwin':
            tmpdir = '/var/tmp'
        else:
            tmpdir = os.environ.get('TMPDIR')
            tmpdir = tmpdir or '/tmp'
            tmpdir = tmpdir.rstrip('/')

        if os.name == 'nt':
            options['server_root'] = ('%s/mod_wsgi-%s-%s-%s' % (tmpdir,
                    options['host'], options['port'], getpass.getuser())
                    ).replace('\\','/')
        else:
            options['server_root'] = '%s/mod_wsgi-%s:%s:%s' % (tmpdir,
                    options['host'], options['port'], os.getuid())

    if not os.path.isdir(options['server_root']):
        os.mkdir(options['server_root'])

    if options['ssl_certificate_file']:
        options['ssl_certificate_file'] = os.path.abspath(
                options['ssl_certificate_file'])

    if options['ssl_certificate_key_file']:
        options['ssl_certificate_key_file'] = os.path.abspath(
                options['ssl_certificate_key_file'])

    if options['ssl_certificate']:
        options['ssl_certificate'] = os.path.abspath(
                options['ssl_certificate'])

        options['ssl_certificate_file'] = options['ssl_certificate']
        options['ssl_certificate_file'] += '.crt'

        options['ssl_certificate_key_file'] = options['ssl_certificate']
        options['ssl_certificate_key_file'] += '.key'

    if options['ssl_ca_certificate_file']:
        options['ssl_ca_certificate_file'] = os.path.abspath(
                options['ssl_ca_certificate_file'])

    if options['ssl_certificate_chain_file']:
        options['ssl_certificate_chain_file'] = os.path.abspath(
                options['ssl_certificate_chain_file'])

    if options['entry_point']:
        args = [options['entry_point']]

    if not args:
        if options['application_type'] != 'static':
            options['entry_point'] = posixpath.join(
                    options['server_root'], 'default.wsgi')
            options['application_type'] = 'script'
            options['enable_docs'] = True
        else:
            if not options['document_root']:
                options['document_root'] = os.getcwd()
            options['entry_point'] = '(static)'
    else:
        if options['application_type'] in ('script', 'paste'):
            options['entry_point'] = posixpath.abspath(args[0])
        elif options['application_type'] == 'static':
            if not options['document_root']:
                options['document_root'] = posixpath.abspath(args[0])
                options['entry_point'] = 'ignored'
            else:
                options['entry_point'] = 'overridden'
        else:
            options['entry_point'] = args[0]

    if options['host_access_script']:
        options['host_access_script'] = posixpath.abspath(
                options['host_access_script'])

    if options['auth_user_script']:
        options['auth_user_script'] = posixpath.abspath(
                options['auth_user_script'])

    if options['auth_group_script']:
        options['auth_group_script'] = posixpath.abspath(
                options['auth_group_script'])

    options['documentation_directory'] = os.path.join(os.path.dirname(
            os.path.dirname(__file__)), 'docs')
    options['images_directory'] = os.path.join(os.path.dirname(
            os.path.dirname(__file__)), 'images')

    if os.path.exists(posixpath.join(options['documentation_directory'],
            'index.html')):
        options['documentation_url'] = '/__wsgi__/docs/'
    else:
        options['documentation_url'] = 'http://www.modwsgi.org/'

    if not os.path.isabs(options['server_root']):
        options['server_root'] = posixpath.abspath(options['server_root'])

    if not options['document_root']:
        options['document_root'] = posixpath.join(options['server_root'],
                'htdocs')

    try:
        os.mkdir(options['document_root'])
    except Exception:
        pass

    if not options['allow_override']:
        options['allow_override'] = 'None'
    else:
        options['allow_override'] = ' '.join(options['allow_override'])

    if not options['mount_point'].startswith('/'):
        options['mount_point'] = posixpath.normpath('/' + options['mount_point'])

    # Create subdirectories for mount points in document directory
    # so that fallback resource rewrite rule will work.

    if options['mount_point'] != '/':
        parts = options['mount_point'].rstrip('/').split('/')[1:]
        subdir = options['document_root']
        try:
            for part in parts:
                subdir = posixpath.join(subdir, part)
                if not os.path.exists(subdir):
                    os.mkdir(subdir)
        except Exception:
            raise

    if not os.path.isabs(options['document_root']):
        options['document_root'] = posixpath.abspath(options['document_root'])

    if not options['log_directory']:
        options['log_directory'] = options['server_root']
    else:
        # The --log-directory option overrides --log-to-terminal.
        options['log_to_terminal'] = False

    if options['log_to_terminal']:
        # The --log-to-terminal option overrides --rotate-logs.
        options['rotate_logs'] = False

    try:
        os.mkdir(options['log_directory'])
    except Exception:
        pass

    if not os.path.isabs(options['log_directory']):
        options['log_directory'] = posixpath.abspath(options['log_directory'])

    if not options['log_to_terminal']:
        options['error_log_file'] = posixpath.join(options['log_directory'],
                options['error_log_name'])
    else:
        if os.name == 'nt':
            options['error_log_file'] = 'CON'
        else:
            try:
                with open('/dev/stderr', 'w'):
                    pass
            except IOError:
                options['error_log_file'] = '|%s' % find_program(
                        ['tee'], default='tee')
            else:
                options['error_log_file'] = '/dev/stderr'

    if not options['log_to_terminal']:
        options['access_log_file'] = posixpath.join(
                options['log_directory'], options['access_log_name'])
    else:
        try:
            with open('/dev/stdout', 'w'):
                pass
        except IOError:
            options['access_log_file'] = '|%s' % find_program(
                    ['tee'], default='tee')
        else:
            options['access_log_file'] = '/dev/stdout'

    if options['access_log_format']:
        if options['access_log_format'] in ('common', 'combined'):
            options['log_format_nickname'] = options['access_log_format']
            options['access_log_format'] = 'undefined'
        else:
            options['log_format_nickname'] = 'custom'
    else:
        options['log_format_nickname'] = 'common'
        options['access_log_format'] = 'undefined'

    options['access_log_format'] = options['access_log_format'].replace(
            '\"', '\\"')

    if options['error_log_format']:
        options['error_log_format'] = options['error_log_format'].replace(
                '\"', '\\"')

    options['pid_file'] = ((options['pid_file'] and posixpath.abspath(
            options['pid_file'])) or posixpath.join(options['server_root'],
            'httpd.pid'))

    options['python_eggs'] = (posixpath.abspath(options['python_eggs']) if
            options['python_eggs'] is not None else None)

    if options['python_eggs'] is None:
        options['python_eggs'] = posixpath.join(options['server_root'],
                'python-eggs')

    try:
        os.mkdir(options['python_eggs'])
        if os.name != 'nt' and os.getuid() == 0:
            import pwd
            import grp
            os.chown(options['python_eggs'],
                    pwd.getpwnam(options['user']).pw_uid,
                    grp.getgrnam(options['group']).gr_gid)
    except Exception:
        pass

    if options['python_paths'] is None:
        options['python_paths'] = []

    if options['debug_mode'] or options['embedded_mode']:
        if options['working_directory'] not in options['python_paths']:
            options['python_paths'].insert(0, options['working_directory'])

    if options['debug_mode']:
        options['server_mpm_variables'] = ['worker', 'prefork']

    elif options['embedded_mode']:
        if not options['server_mpm_variables']:
            options['server_mpm_variables'] = ['worker', 'prefork']

    # Special case to check for when being executed from shiv variant
    # of a zipapp application bundle. We need to work out where the
    # site packages directory is and pass it with Python module search
    # path so is known about by the Apache sub process when executed.

    site_packages = []

    if '_bootstrap' in sys.modules:
        bootstrap = sys.modules['_bootstrap']
        if 'bootstrap' in dir(bootstrap):
            frame = inspect.currentframe()
            while frame is not None:
                code = frame.f_code
                if (code and code.co_filename == bootstrap.__file__ and
                        code.co_name == 'bootstrap' and
                        'site_packages' in frame.f_locals):
                    site_packages.append(str(frame.f_locals['site_packages']))
                    break
                frame = frame.f_back

    options['python_paths'].extend(site_packages)

    options['python_path'] = ':'.join(options['python_paths'])

    options['multiprocess'] = options['processes'] is not None
    options['processes'] = options['processes'] or 1

    options['python_home'] = sys.prefix.replace('\\','/')

    options['keep_alive'] = options['keep_alive_timeout'] != 0

    request_read_timeout = ''

    if options['header_timeout'] > 0:
        request_read_timeout += 'header=%d' % options['header_timeout']
        if options['header_max_timeout'] > 0:
            request_read_timeout += '-%d' % options['header_max_timeout']
        if options['header_min_rate'] > 0:
            request_read_timeout += ',MinRate=%d' % options['header_min_rate']
        
    if options['body_timeout'] > 0:
        request_read_timeout += ' body=%d' % options['body_timeout']
        if options['body_max_timeout'] > 0:
            request_read_timeout += '-%d' % options['body_max_timeout']
        if options['body_min_rate'] > 0:
            request_read_timeout += ',MinRate=%d' % options['body_min_rate']

    options['request_read_timeout'] = request_read_timeout

    if options['server_metrics']:
        options['server_metrics_flag'] = 'On'
    else:
        options['server_metrics_flag'] = 'Off'

    if options['handler_scripts']:
        handler_scripts = []
        for extension, script in options['handler_scripts']:
            if not os.path.isabs(script):
                script = posixpath.abspath(script)
            handler_scripts.append((extension, script))
        options['handler_scripts'] = handler_scripts

    if options['newrelic_config_file']:
        options['newrelic_config_file'] = posixpath.abspath(
                options['newrelic_config_file'])

    if options['with_newrelic']:
        options['with_newrelic_agent'] = True
        options['with_newrelic_platform'] = True

    if options['with_newrelic_platform']:
        options['server_metrics'] = True

    if options['service_scripts']:
        service_scripts = []
        for name, script in options['service_scripts']:
            if not os.path.isabs(script):
                script = posixpath.abspath(script)
            service_scripts.append((name, script))
        options['service_scripts'] = service_scripts

    # Node that all the below calculations are overridden if are using
    # embedded mode.

    max_clients = options['processes'] * options['threads']

    if options['max_clients'] is not None:
        max_clients = max(options['max_clients'], max_clients)
    else:
        max_clients = 10 + max(10, int(1.5 * max_clients))

    initial_workers = options['initial_workers']
    min_spare_workers = options['minimum_spare_workers']
    max_spare_workers = options['maximum_spare_workers']

    if initial_workers is None:
        prefork_initial_workers = 0.05
    else:
        prefork_initial_workers = initial_workers

    if min_spare_workers is None:
        prefork_min_spare_workers = prefork_initial_workers
    else:
        prefork_min_spare_workers = min_spare_workers

    if max_spare_workers is None:
        prefork_max_spare_workers = 0.1
    else:
        prefork_max_spare_workers = max_spare_workers

    options['prefork_max_clients'] = max_clients
    options['prefork_server_limit'] = max_clients
    options['prefork_start_servers'] = max(1, int(
            prefork_initial_workers * max_clients))
    options['prefork_min_spare_servers'] = max(1, int(
            prefork_min_spare_workers * max_clients))
    options['prefork_max_spare_servers'] = max(1, int(
            prefork_max_spare_workers * max_clients))

    if initial_workers is None:
        worker_initial_workers = 0.2
    else:
        worker_initial_workers = initial_workers

    if min_spare_workers is None:
        worker_min_spare_workers = worker_initial_workers
    else:
        worker_min_spare_workers = min_spare_workers

    if max_spare_workers is None:
        worker_max_spare_workers = 0.6
    else:
        worker_max_spare_workers = max_spare_workers

    options['worker_max_clients'] = max_clients

    if max_clients > 20:
        options['worker_threads_per_child'] = int(max_clients /
                (int(max_clients / 20) + 1))
    else:
        options['worker_threads_per_child'] = 10

    options['worker_thread_limit'] = options['worker_threads_per_child']

    count = max_clients / options['worker_threads_per_child']
    options['worker_server_limit'] = int(math.floor(count))
    if options['worker_server_limit'] != count:
        options['worker_server_limit'] += 1

    options['worker_max_clients'] = (options['worker_server_limit'] *
            options['worker_threads_per_child'])

    options['worker_start_servers'] = max(1,
            int(worker_initial_workers * options['worker_server_limit']))
    options['worker_min_spare_threads'] = max(
            options['worker_threads_per_child'],
            int(worker_min_spare_workers * options['worker_server_limit']) *
            options['worker_threads_per_child'])
    options['worker_max_spare_threads'] = max(
            options['worker_threads_per_child'],
            int(worker_max_spare_workers * options['worker_server_limit']) *
            options['worker_threads_per_child'])

    if options['embedded_mode']:
        max_clients = options['processes'] * options['threads']

        options['prefork_max_clients'] = max_clients
        options['prefork_server_limit'] = max_clients
        options['prefork_start_servers'] = max_clients
        options['prefork_min_spare_servers'] = max_clients
        options['prefork_max_spare_servers'] = max_clients

        options['worker_max_clients'] = max_clients
        options['worker_server_limit'] = options['processes']
        options['worker_thread_limit'] = options['threads']
        options['worker_threads_per_child'] = options['threads']
        options['worker_start_servers'] = options['processes']
        options['worker_min_spare_threads'] = max_clients
        options['worker_max_spare_threads'] = max_clients

    options['httpd_conf'] = posixpath.join(options['server_root'], 'httpd.conf')

    options['httpd_executable'] = os.environ.get('HTTPD',
            options['httpd_executable'])

    if os.name != 'nt':
        if not os.path.isabs(options['httpd_executable']):
            options['httpd_executable'] = find_program(
                    [options['httpd_executable']], 'httpd', ['/usr/sbin'])

    if not options['process_name']:
        options['process_name'] = posixpath.basename(
                options['httpd_executable']) + ' (mod_wsgi-express)'

    options['process_name'] = options['process_name'].ljust(
            len(options['daemon_name']))

    options['rewrite_rules'] = (posixpath.abspath(
            options['rewrite_rules']) if options['rewrite_rules'] is
            not None else None)

    options['envvars_script'] = (posixpath.abspath(
            options['envvars_script']) if options['envvars_script'] is
            not None else None)

    if options['locale'] is None:
        options['locale'] = options['lang']

    if options['locale'] is None:
        language, encoding = locale.getdefaultlocale()
        if language is None:
            language = 'C'
        if encoding is None:
            options['locale'] = locale.normalize(language)
        else:
            options['locale'] = locale.normalize(language + '.' + encoding)

    if options['locale'].upper() in ('C', 'POSIX'):
        oldlocale = locale.setlocale(locale.LC_ALL)
        try:
            locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
            options['locale'] = 'en_US.UTF-8'
        except locale.Error:
            try:
                locale.setlocale(locale.LC_ALL, 'C.UTF-8')
                options['locale'] = 'C.UTF-8'
            except locale.Error:
                pass
        locale.setlocale(locale.LC_ALL, oldlocale)

    options['lang'] = options['locale']

    options['httpd_arguments_list'] = []

    options['trusted_proxy_headers'] = ' '.join(
            options['trusted_proxy_headers'])

    options['trusted_proxies'] = ' '.join(options['trusted_proxies'])

    if options['startup_log']:
        if not options['log_to_terminal']:
            options['startup_log_file'] = posixpath.join(
                    options['log_directory'], options['startup_log_name'])
        else:
            if os.name == 'nt':
                options['startup_log_file'] = 'CON'
            else:
                try:
                    with open('/dev/stderr', 'w'):
                        pass
                except IOError:
                    try:
                        with open('/dev/tty', 'w'):
                            pass
                    except IOError:
                        options['startup_log_file'] = None
                    else:
                        options['startup_log_file'] = '/dev/tty'
                else:
                    options['startup_log_file'] = '/dev/stderr'

        if options['startup_log_file']:
            options['httpd_arguments_list'].append('-E')
            options['httpd_arguments_list'].append(options['startup_log_file'])

    if options['verbose_debugging']:
        options['verbose_debugging_flag'] = 'On'
    else:
        options['verbose_debugging_flag'] = 'Off'

    if options['server_name']:
        host = options['server_name']
    else:
        host = options['host']

    options['server_host'] = host

    if options['port'] == 80:
        options['url'] = 'http://%s/' % host
    else:
        options['url'] = 'http://%s:%s/' % (host, options['port'])

    if options['https_port'] == 443:
        options['https_url'] = 'https://%s/' % host
    elif options['https_port'] is not None:
        options['https_url'] = 'https://%s:%s/' % (host, options['https_port'])
    else:
        options['https_url'] = None

    if options['orphan_interpreter']:
        options['httpd_arguments_list'].append('-DORPHAN_INTERPRETER')

    if options['embedded_mode']:
        options['httpd_arguments_list'].append('-DEMBEDDED_MODE')
        options['disable_reloading'] = True

    if any((options['enable_debugger'], options['enable_coverage'],
            options['enable_profiler'], options['enable_recorder'],
            options['enable_gdb'])):
        options['debug_mode'] = True

    if options['debug_mode']:
        options['httpd_arguments_list'].append('-DONE_PROCESS')

    if options['debug_mode']:
        if options['enable_coverage']:
            if not options['coverage_directory']:
                options['coverage_directory'] = posixpath.join(
                        options['server_root'], 'htmlcov')
            else:
                options['coverage_directory'] = posixpath.abspath(
                        options['coverage_directory'])

            try:
                os.mkdir(options['coverage_directory'])
            except Exception:
                pass

        if options['enable_profiler']:
            if not options['profiler_directory']:
                options['profiler_directory'] = posixpath.join(
                        options['server_root'], 'pstats')
            else:
                options['profiler_directory'] = posixpath.abspath(
                        options['profiler_directory'])

            try:
                os.mkdir(options['profiler_directory'])
            except Exception:
                pass

        if options['enable_recorder']:
            if not options['recorder_directory']:
                options['recorder_directory'] = posixpath.join(
                        options['server_root'], 'archive')
            else:
                options['recorder_directory'] = posixpath.abspath(
                        options['recorder_directory'])

            try:
                os.mkdir(options['recorder_directory'])
            except Exception:
                pass

    else:
        options['enable_debugger'] = False
        options['enable_coverage'] = False
        options['enable_profiler'] = False
        options['enable_recorder'] = False
        options['enable_gdb'] = False

    options['parent_domain'] = 'unspecified'

    if options['server_name']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_VIRTUAL_HOST')
        if options['server_name'].lower().startswith('www.'):
            options['httpd_arguments_list'].append('-DMOD_WSGI_REDIRECT_WWW')
            options['parent_domain'] = options['server_name'][4:]

    if options['http2']: 
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_HTTP2')
    if (options['https_port'] and options['ssl_certificate_file'] and
            options['ssl_certificate_key_file']):
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_HTTPS')
    if options['ssl_ca_certificate_file']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_VERIFY_CLIENT')
    if options['ssl_certificate_chain_file']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_CERTIFICATE_CHAIN')

    if options['ssl_environment']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_SSL_ENVIRONMENT')

    if options['https_only']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_HTTPS_ONLY')
    if options['hsts_policy']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_HSTS_POLICY')

    if options['server_aliases']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_SERVER_ALIAS')
        options['server_aliases'] = ' '.join(options['server_aliases'])

    if options['allow_localhost']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_ALLOW_LOCALHOST')

    if options['application_type'] == 'static':
        options['httpd_arguments_list'].append('-DMOD_WSGI_STATIC_ONLY')

    if options['enable_sendfile']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_ENABLE_SENDFILE')

    if options['server_metrics']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_SERVER_METRICS')
    if options['server_status']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_SERVER_METRICS')
        options['httpd_arguments_list'].append('-DMOD_WSGI_SERVER_STATUS')
    if options['directory_index']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_DIRECTORY_INDEX')
    if options['directory_listing']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_DIRECTORY_LISTING')
    if options['error_log_format']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_ERROR_LOG_FORMAT')
    if options['access_log']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_ACCESS_LOG')
    if options['rotate_logs']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_ROTATE_LOGS')
    if options['keep_alive'] != 0:
        options['httpd_arguments_list'].append('-DMOD_WSGI_KEEP_ALIVE')
    if options['compress_responses'] != 0:
        options['httpd_arguments_list'].append('-DMOD_WSGI_COMPRESS_RESPONSES')
    if options['multiprocess']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_MULTIPROCESS')
    if options['listener_host']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_LISTENER_HOST')
    if options['error_override']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_ERROR_OVERRIDE')
    if options['host_access_script']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_HOST_ACCESS')
    if options['auth_user_script']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_AUTH_USER')
    if options['auth_group_script']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_AUTH_GROUP')
    if options['chunked_request']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_CHUNKED_REQUEST')
    if options['with_php5']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_PHP5')
    if options['proxy_mount_points'] or options['proxy_virtual_hosts']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_PROXY')
    if options['trusted_proxy_headers']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_PROXY_HEADERS')
    if options['trusted_proxies']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_TRUSTED_PROXIES')
    if options['python_path']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_PYTHON_PATH')
    if options['socket_prefix']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_WITH_SOCKET_PREFIX')
    if options['disable_reloading']:
        options['httpd_arguments_list'].append('-DMOD_WSGI_DISABLE_RELOADING')

    if options['with_cgi']:
        if os.path.exists(posixpath.join(options['modules_directory'],
                'mod_cgid.so')):
            options['httpd_arguments_list'].append('-DMOD_WSGI_CGID_SCRIPT')
        else:
            options['httpd_arguments_list'].append('-DMOD_WSGI_CGI_SCRIPT')

    options['httpd_arguments_list'].extend(
            _mpm_module_defines(options['modules_directory'],
            options['server_mpm_variables']))

    options['python_executable'] = sys.executable

    options['shlibpath_var'] = apxs_config.SHLIBPATH_VAR
    options['shlibpath'] = apxs_config.SHLIBPATH

    if _py_dylib:
        options['httpd_arguments_list'].append('-DMOD_WSGI_LOAD_PYTHON_DYLIB')

    options['python_dylib'] = _py_dylib

    options['httpd_arguments'] = '-f %s %s' % (options['httpd_conf'],
            ' '.join(options['httpd_arguments_list']))

    generate_wsgi_handler_script(options)

    if options['with_newrelic_platform']:
        generate_server_metrics_script(options)

    print('Server URL         :', options['url'])

    if options['https_url']:
        print('Server URL (HTTPS) :', options['https_url'])

    if options['server_status']:
        print('Server Status      :', '%sserver-status' % options['url'])

    print('Server Root        :', options['server_root'])
    print('Server Conf        :', options['httpd_conf'])

    print('Error Log File     : %s (%s)' % (options['error_log_file'],
            options['log_level']))

    if options['access_log']:
        print('Access Log File    :', options['access_log_file'])

    if options['startup_log']:
        print('Startup Log File   :', options['startup_log_file'])

    if options['enable_coverage']:
        print('Coverage Output    :', posixpath.join(
                options['coverage_directory'], 'index.html'))

    if options['enable_profiler']:
        print('Profiler Output    :', options['profiler_directory'])

    if options['enable_recorder']:
        print('Recorder Output    :', options['recorder_directory'])

    if options['rewrite_rules']:
        print('Rewrite Rules      :', options['rewrite_rules'])

    if os.name != 'nt':
        if options['envvars_script']:
            print('Environ Variables  :', options['envvars_script'])

    if command == 'setup-server' or options['setup_only']:
        if not options['rewrite_rules']:
            print('Rewrite Rules      :', options['server_root'] + '/rewrite.conf')
        if os.name != 'nt':
            if not options['envvars_script']:
                print('Environ Variables  :', options['server_root'] + '/envvars')
            print('Control Script     :', options['server_root'] + '/apachectl')

    if options['debug_mode']:
        print('Operating Mode     : debug')
    elif options['embedded_mode']:
        print('Operating Mode     : embedded')
    else:
        print('Operating Mode     : daemon')

    if options['processes'] == 1:
        print('Request Capacity   : %s (%s process * %s threads)' % (
                options['processes']*options['threads'],
                options['processes'], options['threads']))
    else:
        print('Request Capacity   : %s (%s processes * %s threads)' % (
                options['processes']*options['threads'],
                options['processes'], options['threads']))

    if not options['debug_mode'] and not options['embedded_mode']:
        print('Request Timeout    : %s (seconds)' % options['request_timeout'])

        if options['startup_timeout']:
            print('Startup Timeout    : %s (seconds)' % options['startup_timeout'])

        print('Queue Backlog      : %s (connections)' % options['daemon_backlog'])

        print('Queue Timeout      : %s (seconds)' % options['queue_timeout'])

        print('Server Capacity    : %s (event/worker), %s (prefork)' % (
                options['worker_max_clients'], options['prefork_max_clients']))

    print('Server Backlog     : %s (connections)' % options['server_backlog'])

    print('Locale Setting     :', options['locale'])

    sys.stdout.flush()

    if not options['rewrite_rules']:
        options['rewrite_rules'] = options['server_root'] + '/rewrite.conf'

        if not os.path.isfile(options['rewrite_rules']):
            with open(options['rewrite_rules'], 'w') as fp:
                pass

    generate_apache_config(options)

    if os.name != 'nt':
        generate_control_scripts(options)

    return options

def cmd_start_server(params):
    formatter = optparse.IndentedHelpFormatter()
    formatter.set_long_opt_delimiter(' ')

    usage = '%prog start-server script [options]'
    parser = optparse.OptionParser(usage=usage, option_list=option_list,
            formatter=formatter)

    (options, args) = parser.parse_args(params)

    config = _cmd_setup_server('start-server', args, vars(options))

    if config['setup_only']:
        return

    if os.name == 'nt':
        print()
        print("WARNING: The ability to use the start-server option on Windows")
        print("WARNING: is highly experimental and various things don't quite")
        print("WARNING: work properly. If you understand a lot about using")
        print("WARNING: Python on Windows and Windows programming in general,")
        print("WARNING: and would like to help to get it working properly, then")
        print("WARNING: you can ask about Windows support for the start-server")
        print("WARNING: option on the mod_wsgi mailing list.")
        print()

        executable = config['httpd_executable']

        environ = copy.deepcopy(os.environ)

        environ['MOD_WSGI_MODULES_DIRECTORY'] = config['modules_directory']

        httpd_arguments = list(config['httpd_arguments_list'])
        httpd_arguments.extend(['-f', config['httpd_conf']])
        httpd_arguments.extend(['-DONE_PROCESS'])

        os.environ['MOD_WSGI_MODULES_DIRECTORY'] = config['modules_directory']

        subprocess.call([executable]+httpd_arguments)

        sys.exit(0)

    else:
        executable = posixpath.join(config['server_root'], 'apachectl')

        if sys.stdout.isatty() and not config['debug_mode']:
            process = None

            def handler(signum, frame):
                if process is None:
                    sys.exit(1)

                else:
                    if signum not in [signal.SIGWINCH]:
                        os.kill(process.pid, signum)

            signal.signal(signal.SIGINT, handler)
            signal.signal(signal.SIGTERM, handler)
            signal.signal(signal.SIGHUP, handler)
            signal.signal(signal.SIGUSR1, handler)
            signal.signal(signal.SIGWINCH, handler)

            process = subprocess.Popen([executable, 'start', '-DFOREGROUND'],
                    preexec_fn=os.setpgrp)

            process.wait()

        else:
            os.execl(executable, executable, 'start', '-DFOREGROUND')

def cmd_module_config(params):
    formatter = optparse.IndentedHelpFormatter()
    formatter.set_long_opt_delimiter(' ')

    usage = '%prog module-config'
    parser = optparse.OptionParser(usage=usage, formatter=formatter)

    (options, args) = parser.parse_args(params)

    if len(args) != 0:
        parser.error('Incorrect number of arguments.')

    if os.name == 'nt':
        real_prefix = getattr(sys, 'real_prefix', None)
        base_prefix = getattr(sys, 'base_prefix', None)

        real_prefix = real_prefix or base_prefix or sys.prefix

        library_version = sysconfig.get_config_var('VERSION')

        library_name = 'python%s.dll' % library_version
        library_path = posixpath.join(real_prefix, library_name)

        if not os.path.exists(library_path):
            library_name = 'python%s.dll' % library_version[0]
            library_path = posixpath.join(real_prefix, 'DLLs', library_name)

        if not os.path.exists(library_path):
            library_path = None

        if library_path:
            library_path = posixpath.normpath(library_path)
            library_path = library_path.replace('\\', '/')

            print('LoadFile "%s"' % library_path)

        module_path = where()
        module_path = module_path.replace('\\', '/')

        prefix = sys.prefix
        prefix = posixpath.normpath(prefix)
        prefix = prefix.replace('\\', '/')

        print('LoadModule wsgi_module "%s"' % module_path)
        print('WSGIPythonHome "%s"' % prefix)

    else:
        module_path = where()

        prefix = sys.prefix
        prefix = posixpath.normpath(prefix)

        if _py_dylib:
            print('LoadFile "%s"' % _py_dylib)

        print('LoadModule wsgi_module "%s"' % module_path)
        print('WSGIPythonHome "%s"' % prefix)

def cmd_install_module(params):
    formatter = optparse.IndentedHelpFormatter()
    formatter.set_long_opt_delimiter(' ')

    usage = '%prog install-module [options]'
    parser = optparse.OptionParser(usage=usage, formatter=formatter)

    parser.add_option('--modules-directory', metavar='DIRECTORY',
            default=apxs_config.LIBEXECDIR)

    (options, args) = parser.parse_args(params)

    if len(args) != 0:
        parser.error('Incorrect number of arguments.')

    target = posixpath.abspath(posixpath.join(options.modules_directory,
            posixpath.basename(MOD_WSGI_SO)))

    shutil.copyfile(where(), target)

    if _py_dylib:
        print('LoadFile "%s"' % _py_dylib)
    print('LoadModule wsgi_module "%s"' % target)
    print('WSGIPythonHome "%s"' % posixpath.normpath(sys.prefix))

def cmd_module_location(params):
    formatter = optparse.IndentedHelpFormatter()
    formatter.set_long_opt_delimiter(' ')

    usage = '%prog module-location'
    parser = optparse.OptionParser(usage=usage, formatter=formatter)

    (options, args) = parser.parse_args(params)

    if len(args) != 0:
        parser.error('Incorrect number of arguments.')

    print(where())

if os.name == 'nt':
    main_usage="""
    %prog command [params]

Commands:
    module-config
    module-location
"""
else:
    main_usage="""
    %prog command [params]

Commands:
    install-module
    module-config
    module-location
    setup-server
    start-server
"""

def main():
    parser = optparse.OptionParser(main_usage.strip())

    args = sys.argv[1:]

    if not args:
        parser.error('No command was specified.')

    command = args.pop(0)

    args = [os.path.expandvars(arg) for arg in args]

    if os.name == 'nt':
        if command == 'module-config':
            cmd_module_config(args)
        elif command == 'module-location':
            cmd_module_location(args)
        elif command == 'start-server':
            cmd_start_server(args)
        else:
            parser.error('Invalid command was specified.')
    else:
        if command == 'install-module':
            cmd_install_module(args)
        elif command == 'module-config':
            cmd_module_config(args)
        elif command == 'module-location':
            cmd_module_location(args)
        elif command == 'setup-server':
            cmd_setup_server(args)
        elif command == 'start-server':
            cmd_start_server(args)
        else:
            parser.error('Invalid command was specified.')

def start(*args):
    cmd_start_server(list(args))

if __name__ == '__main__':
    main()