aboutsummaryrefslogtreecommitdiffstats
path: root/configure.py
blob: 50c3f8ffebb94f036af26f0ee1d0de16c284946f (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
#!/usr/bin/env python

"""
Configuration program for botan (http://botan.randombit.net/)
  (C) 2009,2010,2011,2012,2013,2014 Jack Lloyd
  Distributed under the terms of the Botan license

Tested with CPython 2.6, 2.7, 3.1 and PyPy 1.5

Python 2.5 works if you change the exception catching syntax:
   perl -pi -e 's/except (.*) as (.*):/except $1, $2:/g' configure.py

Jython - Target detection does not work (use --os and --cpu)

CPython 2.4 and earlier are not supported

Has not been tested with IronPython
"""

import sys
import os
import os.path
import platform
import re
import shlex
import shutil
import string
import subprocess
import logging
import getpass
import time
import errno
import optparse

# Avoid useless botan_version.pyc (Python 2.6 or higher)
if 'dont_write_bytecode' in sys.__dict__:
    sys.dont_write_bytecode = True

import botan_version

def flatten(l):
    return sum(l, [])

def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i+n]

def is_official_release():
    # Assume a release date implies official release
    return (botan_version.release_datestamp > 20130000)

def get_vc_revision():

    def get_vc_revision(cmdlist):
        try:
            cmdname = cmdlist[0]

            vc = subprocess.Popen(cmdlist,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE,
                                  universal_newlines=True)

            (stdout, stderr) = vc.communicate()

            if vc.returncode != 0:
                logging.debug('Error getting rev from %s - %d (%s)'
                              % (cmdname, vc.returncode, stderr))
                return None

            rev = str(stdout).strip()
            logging.debug('%s reported revision %s' % (cmdname, rev))

            return '%s:%s' % (cmdname, rev)
        except OSError as e:
            logging.debug('Error getting rev from %s - %s' % (cmdname, e.strerror))
            return None
        except Exception as e:
            logging.debug('Error getting rev from %s - %s' % (cmdname, e))
            return None

    vc_commands = [['mtn', 'automate', 'heads'],
                   ['git', 'rev-parse', 'HEAD']]

    for vc_cmd in vc_commands:
        rev = get_vc_revision(vc_cmd)
        if rev is not None:
            return rev

    return 'unknown'

class BuildConfigurationInformation(object):

    """
    Version information
    """
    version_major = botan_version.release_major
    version_minor = botan_version.release_minor
    version_patch = botan_version.release_patch
    version_so_rev = botan_version.release_so_abi_rev

    version_release_type = botan_version.release_type

    version_datestamp = botan_version.release_datestamp

    version_vc_rev = botan_version.release_vc_rev
    version_string = '%d.%d.%d' % (version_major, version_minor, version_patch)

    """
    Constructor
    """
    def __init__(self, options, modules):

        if self.version_vc_rev is None:
            self.version_vc_rev = get_vc_revision()

        self.build_dir = os.path.join(options.with_build_dir, 'build')
        self.appobj_dir = os.path.join(self.build_dir, 'app')
        self.libobj_dir = os.path.join(self.build_dir, 'lib')

        self.doc_output_dir = os.path.join(self.build_dir, 'docs')

        self.include_dir = os.path.join(self.build_dir, 'include')
        self.botan_include_dir = os.path.join(self.include_dir, 'botan')
        self.internal_include_dir = os.path.join(self.botan_include_dir, 'internal')

        self.sources = sorted(flatten([mod.sources() for mod in modules]))
        self.internal_headers = sorted(flatten([m.internal_headers() for m in modules]))

        if options.via_amalgamation:
            self.build_sources = ['botan_all.cpp']
            self.build_internal_headers = []
        else:
            self.build_sources = self.sources
            self.build_internal_headers = self.internal_headers

        self.public_headers = sorted(flatten([m.public_headers() for m in modules]))

        self.apps_dir = os.path.join(options.base_dir, 'src/')

        def find_sources_in(srcdir):
            for (dirpath, dirnames, filenames) in os.walk(srcdir):
                for filename in filenames:
                    if filename.endswith('.cpp'):
                        yield os.path.join(dirpath, filename)

        self.app_sources = list(find_sources_in(self.apps_dir))

        self.boost_python = options.boost_python
        self.python_dir = os.path.join(options.lib_dir, 'wrap', 'python')
        self.pyobject_dir = os.path.join(self.build_dir, 'python')

        self.python_sources = sorted(
            [os.path.join(self.python_dir, file)
             for file in os.listdir(self.python_dir)
             if file.endswith('.cpp')])

        self.manual_dir = os.path.join(self. doc_output_dir, 'manual')

        def build_doc_commands():
            if options.with_sphinx:
                sphinx_config_dir = os.path.join(options.build_data, 'sphinx')
                yield 'sphinx-build -c %s $(SPHINX_OPTS) -b html doc %s' % (
                    sphinx_config_dir, self.manual_dir)
            else:
                yield '$(COPY) doc/*.rst %s' % (self.manual_dir)

            if options.with_doxygen:
                yield 'doxygen %s/botan.doxy' % (self.build_dir)

        self.build_doc_commands = '\n'.join(['\t' + s for s in build_doc_commands()])

        def build_dirs():
            yield self.appobj_dir
            yield self.libobj_dir
            yield self.botan_include_dir
            yield self.internal_include_dir
            yield os.path.join(self.doc_output_dir, 'manual')
            if options.with_doxygen:
                yield os.path.join(self.doc_output_dir, 'doxygen')

            if self.boost_python:
                yield self.pyobject_dir

        self.build_dirs = list(build_dirs())

    def pkg_config_file(self):
        return 'botan-%d.%d.pc' % (self.version_major,
                                   self.version_minor)

    def config_shell_script(self):
        return 'botan-config-%d.%d' % (self.version_major,
                                       self.version_minor)

    def username(self):
        return getpass.getuser()

    def hostname(self):
        return platform.node()

    def timestamp(self):
        return time.ctime()

"""
Handle command line options
"""
def process_command_line(args):

    parser = optparse.OptionParser(
        formatter = optparse.IndentedHelpFormatter(max_help_position = 50),
        version = BuildConfigurationInformation.version_string)

    parser.add_option('--verbose', action='store_true', default=False,
                      help='Show debug messages')
    parser.add_option('--quiet', action='store_true', default=False,
                      help='Show only warnings and errors')

    target_group = optparse.OptionGroup(parser, 'Target options')

    target_group.add_option('--cpu',
                            help='set the target processor type/model')

    target_group.add_option('--os',
                            help='set the target operating system')

    target_group.add_option('--cc', dest='compiler',
                            help='set the desired build compiler')

    target_group.add_option('--cc-bin', dest='compiler_binary',
                            metavar='BINARY',
                            help='set the name of the compiler binary')

    target_group.add_option('--cc-abi-flags', metavar='FLAG',
                            help='set compiler ABI flags',
                            default='')

    target_group.add_option('--chost', help=optparse.SUPPRESS_HELP)

    target_group.add_option('--with-endian', metavar='ORDER', default=None,
                            help='override guess of CPU byte order')

    target_group.add_option('--with-unaligned-mem',
                            dest='unaligned_mem', action='store_true',
                            default=None,
                            help='enable unaligned memory accesses')

    target_group.add_option('--without-unaligned-mem',
                            dest='unaligned_mem', action='store_false',
                            help=optparse.SUPPRESS_HELP)

    for isa_extn_name in ['SSE2', 'SSSE3', 'AVX2', 'AES-NI', 'AltiVec']:
        isa_extn = isa_extn_name.lower()

        target_group.add_option('--disable-%s' % (isa_extn),
                                help='disable use of %s intrinsics' % (isa_extn_name),
                                action='append_const',
                                const=isa_extn,
                                dest='disable_intrinsics')

    build_group = optparse.OptionGroup(parser, 'Build options')

    build_group.add_option('--enable-shared', dest='build_shared_lib',
                           action='store_true', default=True,
                            help=optparse.SUPPRESS_HELP)
    build_group.add_option('--disable-shared', dest='build_shared_lib',
                           action='store_false',
                           help='disable building a shared library')

    build_group.add_option('--enable-asm', dest='asm_ok',
                           action='store_true', default=True,
                           help=optparse.SUPPRESS_HELP)
    build_group.add_option('--disable-asm', dest='asm_ok',
                           action='store_false',
                           help='disallow use of assembler')

    build_group.add_option('--enable-debug', dest='debug_build',
                           action='store_true', default=not is_official_release(),
                           help='enable debug build')
    build_group.add_option('--disable-debug', dest='debug_build',
                           action='store_false', help=optparse.SUPPRESS_HELP)

    build_group.add_option('--no-optimizations', dest='no_optimizations',
                           action='store_true', default=False,
                           help=optparse.SUPPRESS_HELP)

    build_group.add_option('--gen-amalgamation', dest='gen_amalgamation',
                           default=False, action='store_true',
                           help='generate amalgamation files')

    build_group.add_option('--via-amalgamation', dest='via_amalgamation',
                           default=False, action='store_true',
                           help='build via amalgamation')

    build_group.add_option('--with-build-dir',
                           metavar='DIR', default='',
                           help='setup the build in DIR')

    build_group.add_option('--link-method',
                           default=None,
                           metavar='METHOD',
                           help='choose how links are created')

    build_group.add_option('--makefile-style', metavar='STYLE', default=None,
                           help='choose a makefile style (unix or nmake)')

    build_group.add_option('--with-local-config',
                           dest='local_config', metavar='FILE',
                           help='include the contents of FILE into build.h')

    build_group.add_option('--distribution-info', metavar='STRING',
                           help='set distribution specific versioning',
                           default='unspecified')

    build_group.add_option('--with-sphinx', action='store_true',
                           default=None,
                           help='Use Sphinx to generate HTML manual')

    build_group.add_option('--without-sphinx', action='store_false',
                           dest='with_sphinx', help=optparse.SUPPRESS_HELP)

    build_group.add_option('--with-visibility', action='store_true',
                           default=None, help=optparse.SUPPRESS_HELP)

    build_group.add_option('--without-visibility', action='store_false',
                           dest='with_visibility', help=optparse.SUPPRESS_HELP)

    build_group.add_option('--with-doxygen', action='store_true',
                           default=False,
                           help='Use Doxygen to generate HTML API docs')

    build_group.add_option('--without-doxygen', action='store_false',
                           dest='with_doxygen', help=optparse.SUPPRESS_HELP)

    build_group.add_option('--maintainer-mode', dest='maintainer_mode',
                           action='store_true',
                           default=not is_official_release(),
                           help="Enable extra warnings")

    build_group.add_option('--release-mode', dest='maintainer_mode',
                           action='store_false',
                           help=optparse.SUPPRESS_HELP)

    build_group.add_option('--dirty-tree', dest='clean_build_tree',
                           action='store_false', default=True,
                           help=optparse.SUPPRESS_HELP)

    wrapper_group = optparse.OptionGroup(parser, 'Wrapper options')

    wrapper_group.add_option('--with-boost-python', dest='boost_python',
                             default=False, action='store_true',
                             help='enable Boost.Python wrapper')

    wrapper_group.add_option('--without-boost-python',
                             dest='boost_python',
                             action='store_false',
                             help=optparse.SUPPRESS_HELP)

    wrapper_group.add_option('--with-python-version', dest='python_version',
                             metavar='N.M',
                             default='.'.join(map(str, sys.version_info[0:2])),
                             help='specify Python to build against (eg %default)')

    mods_group = optparse.OptionGroup(parser, 'Module selection')

    mods_group.add_option('--enable-modules', dest='enabled_modules',
                          metavar='MODS', action='append',
                          help='enable specific modules')
    mods_group.add_option('--disable-modules', dest='disabled_modules',
                          metavar='MODS', action='append',
                          help='disable specific modules')
    mods_group.add_option('--list-modules', dest='list_modules',
                          action='store_true',
                          help='list available modules')
    mods_group.add_option('--no-autoload', action='store_true', default=False,
                          help='disable automatic loading')

    for mod in ['boost', 'sqlite3', 'zlib', 'bzip2', 'lzma', 'gnump', 'openssl']:

        mods_group.add_option('--with-%s' % (mod),
                              help='add support for using %s' % (mod),
                              action='append_const',
                              const=mod,
                              dest='enabled_modules')

        mods_group.add_option('--without-%s' % (mod),
                              help=optparse.SUPPRESS_HELP,
                              action='append_const',
                              const=mod,
                              dest='disabled_modules')

    install_group = optparse.OptionGroup(parser, 'Installation options')

    install_group.add_option('--prefix', metavar='DIR',
                             help='set the base install directory')
    install_group.add_option('--docdir', metavar='DIR',
                             help='set the documentation install directory')
    install_group.add_option('--libdir', metavar='DIR',
                             help='set the library install directory')
    install_group.add_option('--includedir', metavar='DIR',
                             help='set the include file install directory')

    parser.add_option_group(target_group)
    parser.add_option_group(build_group)
    parser.add_option_group(mods_group)
    parser.add_option_group(wrapper_group)
    parser.add_option_group(install_group)

    # These exist only for autoconf compatability (requested by zw for mtn)
    compat_with_autoconf_options = [
        'bindir',
        'datadir',
        'datarootdir',
        'dvidir',
        'exec-prefix',
        'htmldir',
        'infodir',
        'libexecdir',
        'localedir',
        'localstatedir',
        'mandir',
        'oldincludedir',
        'pdfdir',
        'psdir',
        'sbindir',
        'sharedstatedir',
        'sysconfdir'
        ]

    for opt in compat_with_autoconf_options:
        parser.add_option('--' + opt, help=optparse.SUPPRESS_HELP)

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

    if args != []:
        raise Exception('Unhandled option(s): ' + ' '.join(args))
    if options.with_endian != None and \
       options.with_endian not in ['little', 'big']:
        raise Exception('Bad value to --with-endian "%s"' % (
            options.with_endian))

    def parse_multiple_enable(modules):
        if modules is None:
            return []
        return sorted(set(flatten([s.split(',') for s in modules])))

    options.enabled_modules = parse_multiple_enable(options.enabled_modules)
    options.disabled_modules = parse_multiple_enable(options.disabled_modules)

    options.disable_intrinsics = parse_multiple_enable(options.disable_intrinsics)

    return options

"""
Generic lexer function for info.txt and src/build-data files
"""
def lex_me_harder(infofile, to_obj, allowed_groups, name_val_pairs):

    # Format as a nameable Python variable
    def py_var(group):
        return group.replace(':', '_')

    class LexerError(Exception):
        def __init__(self, msg, line):
            self.msg = msg
            self.line = line

        def __str__(self):
            return '%s at %s:%d' % (self.msg, infofile, self.line)

    (dirname, basename) = os.path.split(infofile)

    to_obj.lives_in = dirname
    if basename == 'info.txt':
        (obj_dir,to_obj.basename) = os.path.split(dirname)
        if os.access(os.path.join(obj_dir, 'info.txt'), os.R_OK):
            to_obj.parent_module = os.path.basename(obj_dir)
        else:
            to_obj.parent_module = None
    else:
        to_obj.basename = basename.replace('.txt', '')

    lexer = shlex.shlex(open(infofile), infofile, posix=True)
    lexer.wordchars += '|:.<>/,-!+' # handle various funky chars in info.txt

    for group in allowed_groups:
        to_obj.__dict__[py_var(group)] = []
    for (key,val) in name_val_pairs.items():
        to_obj.__dict__[key] = val

    def lexed_tokens(): # Convert to an interator
        token = lexer.get_token()
        while token != None:
            yield token
            token = lexer.get_token()

    for token in lexed_tokens():
        match = re.match('<(.*)>', token)

        # Check for a grouping
        if match is not None:
            group = match.group(1)

            if group not in allowed_groups:
                raise LexerError('Unknown group "%s"' % (group),
                                 lexer.lineno)

            end_marker = '</' + group + '>'

            token = lexer.get_token()
            while token != end_marker:
                to_obj.__dict__[py_var(group)].append(token)
                token = lexer.get_token()
                if token is None:
                    raise LexerError('Group "%s" not terminated' % (group),
                                     lexer.lineno)

        elif token in name_val_pairs.keys():
            if type(to_obj.__dict__[token]) is list:
                to_obj.__dict__[token].append(lexer.get_token())

                # Dirty hack
                if token == 'define':
                    nxt = lexer.get_token()
                    if not re.match('^[0-9]{8}$', nxt):
                        raise LexerError('Bad API rev "%s"' % (nxt), lexer.lineno)
                    to_obj.__dict__[token].append(nxt)
            else:
                to_obj.__dict__[token] = lexer.get_token()

        else: # No match -> error
            raise LexerError('Bad token "%s"' % (token), lexer.lineno)

"""
Convert a lex'ed map (from build-data files) from a list to a dict
"""
def force_to_dict(l):
    return dict(zip(l[::3],l[2::3]))

"""
Represents the information about a particular module
"""
class ModuleInfo(object):

    def __init__(self, infofile):

        lex_me_harder(infofile, self,
                      ['source', 'header:internal', 'header:public',
                       'requires', 'os', 'arch', 'cc', 'libs',
                       'comment', 'warning'],
                      {
                        'load_on': 'auto',
                        'define': [],
                        'need_isa': '',
                        'mp_bits': 0 })

        def extract_files_matching(basedir, suffixes):
            for (dirpath, dirnames, filenames) in os.walk(basedir):
                if dirpath == basedir:
                    for filename in filenames:
                        if filename.startswith('.'):
                            continue

                        for suffix in suffixes:
                            if filename.endswith(suffix):
                                yield filename

        if self.need_isa == '':
            self.need_isa = []
        else:
            self.need_isa = self.need_isa.split(',')

        if self.source == []:
            self.source = list(extract_files_matching(self.lives_in, ['.cpp', '.S']))

        if self.header_internal == [] and self.header_public == []:
            self.header_public = list(extract_files_matching(self.lives_in, ['.h']))

        # Coerce to more useful types
        def convert_lib_list(l):
            result = {}
            for (targetlist, vallist) in zip(l[::3], l[2::3]):
                vals = vallist.split(',')
                for target in targetlist.split(','):
                    result[target] = result.setdefault(target, []) + vals
            return result

        self.libs = convert_lib_list(self.libs)

        def add_dir_name(filename):
            if filename.count(':') == 0:
                return os.path.join(self.lives_in, filename)

            # modules can request to add files of the form
            # MODULE_NAME:FILE_NAME to add a file from another module
            # For these, assume other module is always in a
            # neighboring directory; this is true for all current uses
            return os.path.join(os.path.split(self.lives_in)[0],
                                *filename.split(':'))

        self.source = [add_dir_name(s) for s in self.source]
        self.header_internal = [add_dir_name(s) for s in self.header_internal]
        self.header_public = [add_dir_name(s) for s in self.header_public]

        for src in self.source + self.header_internal + self.header_public:
            if os.access(src, os.R_OK) == False:
                logging.warning("Missing file %s in %s" % (src, infofile))

        self.mp_bits = int(self.mp_bits)

        if self.comment != []:
            self.comment = ' '.join(self.comment)
        else:
            self.comment = None

        if self.warning != []:
            self.warning = ' '.join(self.warning)
        else:
            self.warning = None

        intersection = set(self.header_public) & set(self.header_internal)

        if len(intersection) > 0:
            logging.warning('Headers %s marked both public and internal' % (' '.join(intersection)))

    def sources(self):
        return self.source

    def public_headers(self):
        return self.header_public

    def internal_headers(self):
        return self.header_internal

    def defines(self):
        return ['HAS_' + d[0] + ' ' + d[1] for d in chunks(self.define, 2)]

    def compatible_cpu(self, archinfo, options):

        arch_name = archinfo.basename
        cpu_name = options.cpu

        if self.arch != []:
            if arch_name not in self.arch and cpu_name not in self.arch:
                return False

            for isa in self.need_isa:
                if isa in options.disable_intrinsics:
                    return False # explicitly disabled

                if isa not in archinfo.isa_extensions:
                    return False

        return True

    def compatible_os(self, os):
        return self.os == [] or os in self.os

    def compatible_compiler(self, cc):
        return self.cc == [] or cc in self.cc

    def dependencies(self):
        # utils is an implicit dep (contains types, etc)
        deps = self.requires + ['utils']
        if self.parent_module != None:
            deps.append(self.parent_module)
        return deps

    """
    Ensure that all dependencies of this module actually exist, warning
    about any that do not
    """
    def dependencies_exist(self, modules):
        all_deps = [s.split('|') for s in self.dependencies()]

        for missing in [s for s in flatten(all_deps) if s not in modules]:
            logging.warn("Module '%s', dep of '%s', does not exist" % (
                missing, self.basename))

    def __cmp__(self, other):
        if self.basename < other.basename:
            return -1
        if self.basename == other.basename:
            return 0
        return 1

class ArchInfo(object):
    def __init__(self, infofile):
        lex_me_harder(infofile, self,
                      ['aliases', 'submodels', 'submodel_aliases', 'isa_extensions'],
                      { 'endian': None,
                        'family': None,
                        'unaligned': 'no',
                        'wordsize': 32
                        })

        self.submodel_aliases = force_to_dict(self.submodel_aliases)

        self.unaligned_ok = (1 if self.unaligned == 'ok' else 0)

        self.wordsize = int(self.wordsize)

    """
    Return a list of all submodels for this arch, ordered longest
    to shortest
    """
    def all_submodels(self):
        return sorted([(k,k) for k in self.submodels] +
                      [k for k in self.submodel_aliases.items()],
                      key = lambda k: len(k[0]), reverse = True)

    """
    Return CPU-specific defines for build.h
    """
    def defines(self, options):
        def form_macro(cpu_name):
            return cpu_name.upper().replace('.', '').replace('-', '_')

        macros = ['TARGET_ARCH_IS_%s' %
                  (form_macro(self.basename.upper()))]

        if self.basename != options.cpu:
            macros.append('TARGET_CPU_IS_%s' % (form_macro(options.cpu)))

        enabled_isas = set(self.isa_extensions)
        disabled_isas = set(options.disable_intrinsics)

        isa_extensions = sorted(enabled_isas - disabled_isas)

        for isa in isa_extensions:
            macros.append('TARGET_SUPPORTS_%s' % (form_macro(isa)))

        endian = options.with_endian or self.endian

        if endian != None:
            macros.append('TARGET_CPU_IS_%s_ENDIAN' % (endian.upper()))
            logging.info('Assuming CPU is %s endian' % (endian))

        unaligned_ok = options.unaligned_mem
        if unaligned_ok is None:
            unaligned_ok = self.unaligned_ok
            if unaligned_ok:
                logging.info('Assuming unaligned memory access works')

        if self.family is not None:
            macros.append('TARGET_CPU_IS_%s_FAMILY' % (self.family.upper()))

        macros.append('TARGET_CPU_NATIVE_WORD_SIZE %d' % (self.wordsize))

        if self.wordsize == 64:
            macros.append('TARGET_CPU_HAS_NATIVE_64BIT')

        macros.append('TARGET_UNALIGNED_MEMORY_ACCESS_OK %d' % (unaligned_ok))

        return macros

class CompilerInfo(object):
    def __init__(self, infofile):
        lex_me_harder(infofile, self,
                      ['so_link_flags', 'mach_opt', 'mach_abi_linking', 'isa_flags'],
                      { 'binary_name': None,
                        'macro_name': None,
                        'compile_option': '-c ',
                        'output_to_option': '-o ',
                        'add_include_dir_option': '-I',
                        'add_lib_dir_option': '-L',
                        'add_lib_option': '-l',
                        'lib_opt_flags': '',
                        'app_opt_flags': '',
                        'debug_flags': '',
                        'no_debug_flags': '',
                        'shared_flags': '',
                        'lang_flags': '',
                        'warning_flags': '',
                        'maintainer_warning_flags': '',
                        'visibility_build_flags': '',
                        'visibility_attribute': '',
                        'ar_command': None,
                        'makefile_style': ''
                        })

        self.so_link_flags = force_to_dict(self.so_link_flags)
        self.mach_abi_linking = force_to_dict(self.mach_abi_linking)
        self.isa_flags = force_to_dict(self.isa_flags)

        self.mach_opt_flags = {}

        while self.mach_opt != []:
            proc = self.mach_opt.pop(0)
            if self.mach_opt.pop(0) != '->':
                raise Exception('Parsing err in %s mach_opt' % (self.basename))

            flags = self.mach_opt.pop(0)
            regex = ''

            if len(self.mach_opt) > 0 and \
               (len(self.mach_opt) == 1 or self.mach_opt[1] != '->'):
                regex = self.mach_opt.pop(0)

            self.mach_opt_flags[proc] = (flags,regex)

        del self.mach_opt

    """
    Return the shared library build flags, if any
    """
    def gen_shared_flags(self, options):
        def flag_builder():
            if options.build_shared_lib:
                yield self.shared_flags
                if options.with_visibility:
                    yield self.visibility_build_flags

        return ' '.join(list(flag_builder()))

    def gen_visibility_attribute(self, options):
        if options.build_shared_lib and options.with_visibility:
            return self.visibility_attribute
        return ''

    """
    Return the machine specific ABI flags
    """
    def mach_abi_link_flags(self, options):
        def all():
            if options.debug_build:
                return 'all-debug'
            return 'all'

        abi_link = set()
        for what in [all(), options.os, options.arch, options.cpu]:
            if self.mach_abi_linking.get(what) != None:
                abi_link.add(self.mach_abi_linking.get(what))

        for flag in options.cc_abi_flags.split(' '):
            abi_link.add(flag)

        if len(abi_link) == 0:
            return ''
        return ' ' + ' '.join(sorted(list(abi_link)))


    """
    Return the optimization flags to use for the library
    """
    def library_opt_flags(self, options):
        def gen_flags():
            if options.debug_build:
                yield self.debug_flags
            else:
                yield self.no_debug_flags

            if options.no_optimizations:
                return

            yield self.lib_opt_flags

            def submodel_fixup(flags, tup):
                return tup[0].replace('SUBMODEL', flags.replace(tup[1], ''))

            if options.cpu != options.arch:
                if options.cpu in self.mach_opt_flags:
                    yield submodel_fixup(options.cpu, self.mach_opt_flags[options.cpu])
                elif options.arch in self.mach_opt_flags:
                    yield submodel_fixup(options.cpu, self.mach_opt_flags[options.arch])

            all_arch = 'all_%s' % (options.arch)

            if all_arch in self.mach_opt_flags:
                yield self.mach_opt_flags[all_arch][0]

        return (' '.join(gen_flags())).strip()

    """
    Return the command needed to link a shared object
    """
    def so_link_command_for(self, osname):
        if osname in self.so_link_flags:
            return self.so_link_flags[osname]
        if 'default' in self.so_link_flags:
            return self.so_link_flags['default']
        return ''

    """
    Return defines for build.h
    """
    def defines(self):
        return ['BUILD_COMPILER_IS_' + self.macro_name]

class OsInfo(object):
    def __init__(self, infofile):
        lex_me_harder(infofile, self,
                      ['aliases', 'target_features'],
                      { 'os_type': None,
                        'obj_suffix': 'o',
                        'so_suffix': 'so',
                        'static_suffix': 'a',
                        'ar_command': 'ar crs',
                        'ar_needs_ranlib': False,
                        'install_root': '/usr/local',
                        'header_dir': 'include',
                        'lib_dir': 'lib',
                        'doc_dir': 'share/doc',
                        'build_shared': 'yes',
                        'install_cmd_data': 'install -m 644',
                        'install_cmd_exec': 'install -m 755'
                        })

        self.ar_needs_ranlib = bool(self.ar_needs_ranlib)

        self.build_shared = (True if self.build_shared == 'yes' else False)

    def ranlib_command(self):
        return ('ranlib' if self.ar_needs_ranlib else 'true')

    def defines(self):
        return ['TARGET_OS_IS_%s' % (self.basename.upper())] + \
               ['TARGET_OS_HAS_' + feat.upper()
                for feat in sorted(self.target_features)]

def fixup_proc_name(proc):
    proc = proc.lower().replace(' ', '')
    for junk in ['(tm)', '(r)']:
        proc = proc.replace(junk, '')
    return proc

def canon_processor(archinfo, proc):
    proc = fixup_proc_name(proc)

    # First, try to search for an exact match
    for ainfo in archinfo.values():
        if ainfo.basename == proc or proc in ainfo.aliases:
            return (ainfo.basename, ainfo.basename)

        for (match,submodel) in ainfo.all_submodels():
            if proc == submodel or proc == match:
                return (ainfo.basename, submodel)

    logging.debug('Could not find an exact match for CPU "%s"' % (proc))

    # Now, try searching via regex match
    for ainfo in archinfo.values():
        for (match,submodel) in ainfo.all_submodels():
            if re.search(match, proc) != None:
                logging.debug('Possible match "%s" with "%s" (%s)' % (
                    proc, match, submodel))
                return (ainfo.basename, submodel)

    logging.debug('Known CPU names: ' + ' '.join(
        sorted(flatten([[ainfo.basename] + \
                        ainfo.aliases + \
                        [x for (x,_) in ainfo.all_submodels()]
                        for ainfo in archinfo.values()]))))

    raise Exception('Unknown or unidentifiable processor "%s"' % (proc))

def guess_processor(archinfo):
    base_proc = platform.machine()

    if base_proc == '':
        raise Exception('Could not determine target CPU; set with --cpu')

    full_proc = fixup_proc_name(platform.processor()) or base_proc

    for ainfo in archinfo.values():
        if ainfo.basename == base_proc or base_proc in ainfo.aliases:
            for (match,submodel) in ainfo.all_submodels():
                if re.search(match, full_proc) != None:
                    return (ainfo.basename, submodel)

            return canon_processor(archinfo, ainfo.basename)

    # No matches, so just use the base proc type
    return canon_processor(archinfo, base_proc)

"""
Read a whole file into memory as a string
"""
def slurp_file(filename):
    if filename is None:
        return ''
    return ''.join(open(filename).readlines())

"""
Perform template substitution
"""
def process_template(template_file, variables):
    class PercentSignTemplate(string.Template):
        delimiter = '%'

    try:
        template = PercentSignTemplate(slurp_file(template_file))
        return template.substitute(variables)
    except KeyError as e:
        raise Exception('Unbound var %s in template %s' % (e, template_file))

"""
Create the template variables needed to process the makefile, build.h, etc
"""
def create_template_vars(build_config, options, modules, cc, arch, osinfo):
    def make_cpp_macros(macros):
        return '\n'.join(['#define BOTAN_' + macro for macro in macros])

    """
    Figure out what external libraries are needed based on selected modules
    """
    def link_to():
        libs = set()
        for module in modules:
            for (osname,link_to) in module.libs.items():
                if osname == 'all' or osname == osinfo.basename:
                    libs |= set(link_to)
                else:
                    match = re.match('^all!(.*)', osname)
                    if match is not None:
                        exceptions = match.group(1).split(',')
                        if osinfo.basename not in exceptions:
                            libs |= set(link_to)
        return sorted(libs)

    def objectfile_list(sources, obj_dir):
        for src in sources:
            (dir,file) = os.path.split(os.path.normpath(src))

            if dir.startswith('lib/'):
                parts = dir.split(os.sep)[1:]

                # Handle src/X/X.cpp -> X.o
                if file == parts[-1] + '.cpp':
                    name = '_'.join(dir.split(os.sep)[1:]) + '.cpp'
                else:
                    name = '_'.join(dir.split(os.sep)[1:]) + '_' + file

                # Special case hack cause I'm lazy
                name = name.replace('tls_tls_', 'tls_')
            else:
                name = file

            for src_suffix in ['.cpp', '.S']:
                name = name.replace(src_suffix, '.' + osinfo.obj_suffix)

            yield os.path.join(obj_dir, name)

    def choose_mp_bits():
        mp_bits = [mod.mp_bits for mod in modules if mod.mp_bits != 0]

        if mp_bits == []:
            logging.debug('Using arch default MP bits %d' % (arch.wordsize))
            return arch.wordsize

        # Check that settings are consistent across modules
        for mp_bit in mp_bits[1:]:
            if mp_bit != mp_bits[0]:
                raise Exception('Incompatible mp_bits settings found')

        logging.debug('Using MP bits %d' % (mp_bits[0]))
        return mp_bits[0]

    def get_isa_specific_flags(cc, isas):
        flags = []
        for isa in isas:
            if isa not in cc.isa_flags:
                raise Exception('Compiler does not support %s' % (isa))
            flags.append(cc.isa_flags[isa])
        return '' if len(flags) == 0 else (' ' + ' '.join(sorted(list(flags))))

    def isa_specific_flags(cc, src):
        for mod in modules:
            if src in mod.sources():
                return get_isa_specific_flags(cc, mod.need_isa)
        return ''

    def all_isa_specific_flags():
        all_isas = set()
        for mod in modules:
            for isa in mod.need_isa:
                all_isas.add(isa)
        return get_isa_specific_flags(cc, all_isas)

    """
    Form snippets of makefile for building each source file
    """
    def build_commands(sources, obj_dir, flags):
        for (obj_file,src) in zip(objectfile_list(sources, obj_dir), sources):
            yield '%s: %s\n\t$(CXX)%s $(%s_FLAGS) %s%s %s$? %s$@\n' % (
                obj_file, src,
                isa_specific_flags(cc, src),
                flags,
                cc.add_include_dir_option,
                build_config.include_dir,
                cc.compile_option,
                cc.output_to_option)

    def makefile_list(items):
        items = list(items) # force evaluation so we can slice it
        return (' '*16).join([item + ' \\\n' for item in items[:-1]] +
                             [items[-1]])

    def prefix_with_build_dir(path):
        if options.with_build_dir != None:
            return os.path.join(options.with_build_dir, path)
        return path

    def warning_flags(normal_flags,
                      maintainer_flags,
                      maintainer_mode):
        if maintainer_mode and maintainer_flags != '':
            return maintainer_flags + ' ' + normal_flags
        else:
            return normal_flags

    def innosetup_arch(os, arch):
        if os != 'windows':
            return None

        if arch == 'x86_32':
            return '' # allow 32-bit installs on 64 bit systems
        elif arch == 'x86_64':
            return 'x64'
        elif arch == 'ia64':
            return 'ia64'

        logging.warn('Unknown arch in innosetup_arch %s' % (arch))
        return None

    return {
        'version_major':  build_config.version_major,
        'version_minor':  build_config.version_minor,
        'version_patch':  build_config.version_patch,
        'version_vc_rev': build_config.version_vc_rev,
        'so_abi_rev':     build_config.version_so_rev,
        'version':        build_config.version_string,

        'release_type':   build_config.version_release_type,

        'distribution_info': options.distribution_info,

        'version_datestamp': build_config.version_datestamp,

        'timestamp': build_config.timestamp(),
        'user':      build_config.username(),
        'hostname':  build_config.hostname(),
        'command_line': ' '.join(sys.argv),
        'local_config': slurp_file(options.local_config),
        'makefile_style': options.makefile_style or cc.makefile_style,

        'makefile_path': prefix_with_build_dir('Makefile'),

        'prefix': options.prefix or osinfo.install_root,
        'libdir': options.libdir or osinfo.lib_dir,
        'includedir': options.includedir or osinfo.header_dir,
        'docdir': options.docdir or osinfo.doc_dir,

        'build_dir': build_config.build_dir,
        'doc_output_dir': build_config.doc_output_dir,

        'build_doc_commands': build_config.build_doc_commands,

        'python_dir': build_config.python_dir,

        'os': options.os,
        'arch': options.arch,
        'submodel': options.cpu,

        'innosetup_arch': innosetup_arch(options.os, options.arch),

        'mp_bits': choose_mp_bits(),

        'cc': (options.compiler_binary or cc.binary_name) + cc.mach_abi_link_flags(options) +
              ('' if not options.via_amalgamation else all_isa_specific_flags()),

        'lib_opt': cc.library_opt_flags(options),
        'app_opt': '' if options.no_optimizations else cc.app_opt_flags,
        'lang_flags': cc.lang_flags,
        'warn_flags': warning_flags(cc.warning_flags,
                                    cc.maintainer_warning_flags,
                                    options.maintainer_mode),

        'shared_flags': cc.gen_shared_flags(options),
        'visibility_attribute': cc.gen_visibility_attribute(options),

        'so_link': cc.so_link_command_for(osinfo.basename),

        'link_to': ' '.join([cc.add_lib_option + lib for lib in link_to()]),

        'module_defines': make_cpp_macros(sorted(flatten([m.defines() for m in modules]))),

        'target_os_defines': make_cpp_macros(osinfo.defines()),

        'target_compiler_defines': make_cpp_macros(cc.defines()),

        'target_cpu_defines': make_cpp_macros(arch.defines(options)),

        'include_files': makefile_list(build_config.public_headers),

        'lib_objs': makefile_list(
            objectfile_list(build_config.build_sources,
                            build_config.libobj_dir)),

        'app_objs': makefile_list(
            objectfile_list(build_config.app_sources,
                            build_config.appobj_dir)),

        'lib_build_cmds': '\n'.join(
            build_commands(build_config.build_sources,
                           build_config.libobj_dir, 'LIB')),

        'app_build_cmds': '\n'.join(
            build_commands(build_config.app_sources,
                           build_config.appobj_dir, 'APP')),

        'python_obj_dir': build_config.pyobject_dir,

        'python_objs': makefile_list(
            objectfile_list(build_config.python_sources,
                            build_config.pyobject_dir)),

        'python_build_cmds': '\n'.join(
            build_commands(build_config.python_sources,
                           build_config.pyobject_dir, 'PYTHON')),

        'ar_command': cc.ar_command or osinfo.ar_command,
        'ranlib_command': osinfo.ranlib_command(),
        'install_cmd_exec': osinfo.install_cmd_exec,
        'install_cmd_data': osinfo.install_cmd_data,

        'app_prefix': prefix_with_build_dir(''),
        'lib_prefix': prefix_with_build_dir(''),

        'static_suffix': osinfo.static_suffix,
        'so_suffix': osinfo.so_suffix,

        'botan_config': prefix_with_build_dir(
            os.path.join(build_config.build_dir,
                         build_config.config_shell_script())),

        'botan_pkgconfig': prefix_with_build_dir(
            os.path.join(build_config.build_dir,
                         build_config.pkg_config_file())),

        'mod_list': '\n'.join(sorted([m.basename for m in modules])),

        'python_version': options.python_version
        }

"""
Determine which modules to load based on options, target, etc
"""
def choose_modules_to_use(modules, archinfo, options):

    for mod in modules.values():
        mod.dependencies_exist(modules)

    to_load = []
    maybe_dep = []
    not_using_because = {}

    def cannot_use_because(mod, reason):
        not_using_because.setdefault(reason, []).append(mod)

    for modname in options.enabled_modules:
        if modname not in modules:
            logging.warning("Unknown enabled module %s" % (modname))

    for modname in options.disabled_modules:
        if modname not in modules:
            logging.warning("Unknown disabled module %s" % (modname))

    for (modname, module) in modules.items():
        if modname in options.disabled_modules:
            cannot_use_because(modname, 'disabled by user')
        elif modname in options.enabled_modules:
            to_load.append(modname) # trust the user

        elif not module.compatible_os(options.os):
            cannot_use_because(modname, 'incompatible OS')
        elif not module.compatible_compiler(options.compiler):
            cannot_use_because(modname, 'incompatible compiler')
        elif not module.compatible_cpu(archinfo, options):
            cannot_use_because(modname, 'incompatible CPU')

        else:
            if module.load_on == 'never':
                cannot_use_because(modname, 'disabled as buggy')
            elif module.load_on == 'request':
                cannot_use_because(modname, 'by request only')
            elif module.load_on == 'dep':
                maybe_dep.append(modname)

            elif module.load_on == 'always':
                to_load.append(modname)

            elif module.load_on == 'asm_ok':
                if options.asm_ok:
                    if options.no_autoload:
                        maybe_dep.append(modname)
                    else:
                        to_load.append(modname)
                else:
                    cannot_use_because(modname,
                                       'uses assembly and --disable-asm set')
            elif module.load_on == 'auto':
                if options.no_autoload:
                    maybe_dep.append(modname)
                else:
                    to_load.append(modname)
            else:
                logging.warning('Unknown load_on %s in %s' % (
                    module.load_on, modname))

    dependency_failure = True

    while dependency_failure:
        dependency_failure = False
        for modname in to_load:
            for deplist in [s.split('|') for s in modules[modname].dependencies()]:

                dep_met = False
                for mod in deplist:
                    if dep_met is True:
                        break

                    if mod in to_load:
                        dep_met = True
                    elif mod in maybe_dep:
                        maybe_dep.remove(mod)
                        to_load.append(mod)
                        dep_met = True

                if dep_met == False:
                    dependency_failure = True
                    if modname in to_load:
                        to_load.remove(modname)
                    if modname in maybe_dep:
                        maybe_dep.remove(modname)
                    cannot_use_because(modname, 'dependency failure')

    for not_a_dep in maybe_dep:
        cannot_use_because(not_a_dep, 'loaded only if needed by dependency')

    for reason in sorted(not_using_because.keys()):
        disabled_mods = sorted(set([mod for mod in not_using_because[reason]]))

        if disabled_mods != []:
            logging.info('Skipping, %s - %s' % (
                reason, ' '.join(disabled_mods)))

    for mod in sorted(to_load):
        if mod.startswith('mp_'):
            logging.info('Using MP module ' + mod)
        if mod.startswith('simd_') and mod != 'simd_engine':
            logging.info('Using SIMD module ' + mod)

    for mod in sorted(to_load):
        if modules[mod].comment:
            logging.info('%s: %s' % (mod, modules[mod].comment))
        if modules[mod].warning:
            logging.warning('%s: %s' % (mod, modules[mod].warning))

    logging.info('Loading modules %s', ' '.join(sorted(to_load)))

    return [modules[mod] for mod in to_load]

"""
Load the info files about modules, targets, etc
"""
def load_info_files(options):

    def find_files_named(desired_name, in_path):
        for (dirpath, dirnames, filenames) in os.walk(in_path):
            if desired_name in filenames:
                yield os.path.join(dirpath, desired_name)

    modules = dict([(mod.basename, mod) for mod in
                    [ModuleInfo(info) for info in
                     find_files_named('info.txt', options.lib_dir)]])

    def list_files_in_build_data(subdir):
        for (dirpath, dirnames, filenames) in \
                os.walk(os.path.join(options.build_data, subdir)):
            for filename in filenames:
                if filename.endswith('.txt'):
                    yield os.path.join(dirpath, filename)

    def form_name(filepath):
        return os.path.basename(filepath).replace('.txt', '')

    archinfo = dict([(form_name(info), ArchInfo(info))
                     for info in list_files_in_build_data('arch')])

    osinfo   = dict([(form_name(info), OsInfo(info))
                      for info in list_files_in_build_data('os')])

    ccinfo = dict([(form_name(info), CompilerInfo(info))
                    for info in list_files_in_build_data('cc')])

    def info_file_load_report(type, num):
        if num > 0:
            logging.debug('Loaded %d %s info files' % (num, type))
        else:
            logging.warning('Failed to load any %s info files' % (type))

    info_file_load_report('CPU', len(archinfo));
    info_file_load_report('OS', len(osinfo))
    info_file_load_report('compiler', len(ccinfo))

    return (modules, archinfo, ccinfo, osinfo)

"""
Perform the filesystem operations needed to setup the build
"""
def setup_build(build_config, options, template_vars):

    """
    Choose the link method based on system availablity and user request
    """
    def choose_link_method(req_method):

        def useable_methods():
            if 'symlink' in os.__dict__:
                yield 'symlink'
            if 'link' in os.__dict__:
                yield 'hardlink'
            yield 'copy'

        for method in useable_methods():
            if req_method is None or req_method == method:
                return method

        logging.warning('Could not use requested link method "%s", defaulting to copy' % (req_method))
        return 'copy'

    """
    Copy or link the file, depending on what the platform offers
    """
    def portable_symlink(filename, target_dir, method):

        if not os.access(filename, os.R_OK):
            logging.warning('Missing file %s' % (filename))
            return

        if method == 'symlink':
            def count_dirs(dir, accum = 0):
                if dir in ['', '/', os.path.curdir]:
                    return accum
                (dir,basename) = os.path.split(dir)
                return accum + 1 + count_dirs(dir)

            dirs_up = count_dirs(target_dir)

            source = os.path.join(os.path.join(*[os.path.pardir]*dirs_up),
                                  filename)

            target = os.path.join(target_dir, os.path.basename(filename))

            os.symlink(source, target)

        elif method == 'hardlink':
            os.link(filename,
                    os.path.join(target_dir, os.path.basename(filename)))

        elif method == 'copy':
            shutil.copy(filename, target_dir)

        else:
            raise Exception('Unknown link method %s' % (method))

    def choose_makefile_template(style):
        if style == 'nmake':
            return 'nmake.in'
        elif style == 'unix':
            return ('unix_shr.in' if options.build_shared_lib else 'unix.in')
        else:
            raise Exception('Unknown makefile style "%s"' % (style))

    # First delete the build tree, if existing
    try:
        if options.clean_build_tree:
            shutil.rmtree(build_config.build_dir)
    except OSError as e:
        if e.errno != errno.ENOENT:
            logging.error('Problem while removing build dir: %s' % (e))

    for dir in build_config.build_dirs:
        try:
            os.makedirs(dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                logging.error('Error while creating "%s": %s' % (dir, e))

    makefile_template = os.path.join(
        options.makefile_dir,
        choose_makefile_template(template_vars['makefile_style']))

    logging.debug('Using makefile template %s' % (makefile_template))

    templates_to_proc = {
        makefile_template: template_vars['makefile_path']
        }

    def templates_to_use():
        yield (options.build_data, 'buildh.in', 'build.h')
        yield (options.build_data, 'botan.doxy.in', 'botan.doxy')

        if options.os != 'windows':
            yield (options.build_data, 'botan.pc.in', build_config.pkg_config_file())
            yield (options.build_data, 'botan-config.in', build_config.config_shell_script())

        if options.os == 'windows':
            yield (options.build_data, 'innosetup.in', 'botan.iss')

        if options.boost_python:
            yield (options.makefile_dir, 'python.in', 'Makefile.python')

    for (template_dir, template, sink) in templates_to_use():
        source = os.path.join(template_dir, template)
        if template_dir == options.build_data:
            sink = os.path.join(build_config.build_dir, sink)
        templates_to_proc[source] = sink

    for (template, sink) in templates_to_proc.items():
        try:
            f = open(sink, 'w')
            f.write(process_template(template, template_vars))
        finally:
            f.close()

    link_method = choose_link_method(options.link_method)
    logging.info('Using %s to link files into build directory (use --link-method to change)' % (link_method))

    def link_headers(header_list, type, dir):
        logging.debug('Linking %d %s header files in %s' % (
            len(header_list), type, dir))

        for header_file in header_list:
            try:
                portable_symlink(header_file, dir, link_method)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    logging.error('Error linking %s into %s: %s' % (
                        header_file, dir, e))

    link_headers(build_config.public_headers, 'public',
                 build_config.botan_include_dir)

    link_headers(build_config.build_internal_headers, 'internal',
                 build_config.internal_include_dir)

"""
Generate the amalgamation
"""
def generate_amalgamation(build_config):
    def strip_header_goop(header_name, contents):
        header_guard = re.compile('^#define BOTAN_.*_H__$')

        while len(contents) > 0:
            if header_guard.match(contents[0]):
                contents = contents[1:]
                break

            contents = contents[1:]

        if len(contents) == 0:
            raise Exception("No header guard found in " + header_name)

        while contents[0] == '\n':
            contents = contents[1:]

        while contents[-1] == '\n':
            contents = contents[0:-1]
        if contents[-1] == '#endif\n':
            contents = contents[0:-1]

        return contents

    botan_include = re.compile('#include <botan/(.*)>$')
    std_include = re.compile('#include <([^/\.]+|stddef.h)>$')
    any_include = re.compile('#include <(.*)>$')

    class Amalgamation_Generator:
        def __init__(self, input_list):

            self.included_already = set()
            self.all_std_includes = set()

            self.file_contents = {}
            for f in sorted(input_list):
                contents = strip_header_goop(f, open(f).readlines())
                self.file_contents[os.path.basename(f)] = contents

            self.contents = ''
            for name in self.file_contents:
                self.contents += ''.join(list(self.header_contents(name)))

            self.header_includes = ''
            for std_header in self.all_std_includes:
                self.header_includes += '#include <%s>\n' % (std_header)
            self.header_includes += '\n'

        def header_contents(self, name):
            name = name.replace('internal/', '')

            if name in self.included_already:
                return

            self.included_already.add(name)

            if name not in self.file_contents:
                return

            for line in self.file_contents[name]:
                match = botan_include.search(line)
                if match:
                    for c in self.header_contents(match.group(1)):
                        yield c
                else:
                    match = std_include.search(line)

                    if match:
                        self.all_std_includes.add(match.group(1))
                    else:
                        yield line

    amalg_basename = 'botan_all'

    header_name = '%s.h' % (amalg_basename)
    source_name = '%s.cpp' % (amalg_basename)

    logging.info('Writing amalgamation to %s and %s' % (header_name, source_name))

    botan_h = open(header_name, 'w')

    pub_header_amalag = Amalgamation_Generator(build_config.public_headers)

    amalg_header = """/*
* Botan %s Amalgamation
* (C) 1999-2013 Jack Lloyd and others
*
* Distributed under the terms of the Botan license
*/
""" % (build_config.version_string)

    botan_h.write(amalg_header)

    botan_h.write("""
#ifndef BOTAN_AMALGAMATION_H__
#define BOTAN_AMALGAMATION_H__

""")

    botan_h.write(pub_header_amalag.header_includes)
    botan_h.write(pub_header_amalag.contents)
    botan_h.write("\n#endif\n")

    internal_headers = Amalgamation_Generator(
        [s for s in build_config.internal_headers
         if s.find('asm_macr_') == -1])

    headers_written = pub_header_amalag.all_std_includes.union(internal_headers.all_std_includes)

    botan_cpp = open(source_name, 'w')

    botan_cpp.write(amalg_header)

    botan_cpp.write('\n#include "%s"\n' % (header_name))

    botan_cpp.write(internal_headers.header_includes)
    botan_cpp.write(internal_headers.contents)

    for src in build_config.sources:
        if src.endswith('.S'):
            continue

        contents = open(src).readlines()
        for line in contents:
            if botan_include.search(line):
                continue

            match = any_include.search(line)
            if match:
                header = match.group(1)
                if header in headers_written:
                    continue

                botan_cpp.write(line)
                headers_written.add(header)
            else:
                botan_cpp.write(line)

"""
Test for the existence of a program
"""
def have_program(program):

    def exe_test(path, program):
        exe_file = os.path.join(path, program)

        if os.path.exists(exe_file) and os.access(exe_file, os.X_OK):
            logging.debug('Found program %s in %s' % (program, path))
            return True
        else:
            return False

    exe_suffixes = ['', '.exe']

    for path in os.environ['PATH'].split(os.pathsep):
        for suffix in exe_suffixes:
            if exe_test(path, program + suffix):
                return True

    return False

"""
Main driver
"""
def main(argv = None):
    if argv is None:
        argv = sys.argv

    logging.basicConfig(stream = sys.stdout,
                        format = '%(levelname) 7s: %(message)s')

    options = process_command_line(argv[1:])

    def log_level():
        if options.verbose:
            return logging.DEBUG
        if options.quiet:
            return logging.WARNING
        return logging.INFO

    logging.getLogger().setLevel(log_level())

    logging.debug('%s invoked with options "%s"' % (
        argv[0], ' '.join(argv[1:])))

    logging.debug('Platform: OS="%s" machine="%s" proc="%s"' % (
        platform.system(), platform.machine(), platform.processor()))

    if options.os == "java":
        raise Exception("Jython detected: need --os and --cpu to set target")

    options.base_dir = os.path.dirname(argv[0])
    options.src_dir = os.path.join(options.base_dir, 'src')
    options.lib_dir = os.path.join(options.base_dir, 'lib')

    options.build_data = os.path.join(options.src_dir, 'build-data')
    options.makefile_dir = os.path.join(options.build_data, 'makefile')

    (modules, archinfo, ccinfo, osinfo) = load_info_files(options)

    if options.list_modules:
        print("Listing modules available for enablement:")
        for k in sorted(modules.keys()):
            print(" - " + k)
        sys.exit(0)

    if options.chost:
        chost = options.chost.split('-')

        if options.cpu is None and len(chost) > 0:
            options.cpu = chost[0]

        if options.os is None and len(chost) > 2:
            options.os = '-'.join(chost[2:])

    if options.compiler is None:
        if options.os == 'windows':
            if have_program('g++') and not have_program('cl'):
                options.compiler = 'gcc'
            else:
                options.compiler = 'msvc'
        else:
            options.compiler = 'gcc'
        logging.info('Guessing to use compiler %s (use --cc to set)' % (
            options.compiler))

    if options.os is None:
        options.os = platform.system().lower()

        if re.match('^cygwin_.*', options.os):
            logging.debug("Converting '%s' to 'cygwin'", options.os)
            options.os = 'cygwin'

        if options.os == 'windows' and options.compiler == 'gcc':
            logging.warning('Detected GCC on Windows; use --os=cygwin or --os=mingw?')

        logging.info('Guessing target OS is %s (use --os to set)' % (options.os))

    if options.compiler not in ccinfo:
        raise Exception('Unknown compiler "%s"; available options: %s' % (
            options.compiler, ' '.join(sorted(ccinfo.keys()))))

    if options.os not in osinfo:

        def find_canonical_os_name(os):
            for (name, info) in osinfo.items():
                if os in info.aliases:
                    return name
            return os # not found

        options.os = find_canonical_os_name(options.os)

        if options.os not in osinfo:
            raise Exception('Unknown OS "%s"; available options: %s' % (
                options.os, ' '.join(sorted(osinfo.keys()))))

    if options.cpu is None:
        (options.arch, options.cpu) = guess_processor(archinfo)
        logging.info('Guessing target processor is a %s/%s (use --cpu to set)' % (
            options.arch, options.cpu))
    else:
        cpu_from_user = options.cpu
        (options.arch, options.cpu) = canon_processor(archinfo, options.cpu)
        logging.info('Canonicalizized CPU target %s to %s/%s' % (
            cpu_from_user, options.arch, options.cpu))

    logging.info('Target is %s-%s-%s-%s' % (
        options.compiler, options.os, options.arch, options.cpu))

    cc = ccinfo[options.compiler]

    if options.with_visibility is None:
        options.with_visibility = True

    if options.with_sphinx is None:
        if have_program('sphinx-build'):
            logging.info('Found sphinx-build, will use it ' +
                         '(use --without-sphinx to disable)')
            options.with_sphinx = True

    if options.via_amalgamation:
        options.gen_amalgamation = True

    if options.gen_amalgamation:
        if options.asm_ok:
            logging.info('Disabling assembly code, cannot use in amalgamation')
            options.asm_ok = False

    modules_to_use = choose_modules_to_use(modules,
                                           archinfo[options.arch],
                                           options)

    if not osinfo[options.os].build_shared:
        if options.build_shared_lib:
            logging.info('Disabling shared lib on %s' % (options.os))
            options.build_shared_lib = False

    build_config = BuildConfigurationInformation(options, modules_to_use)
    build_config.public_headers.append(
        os.path.join(build_config.build_dir, 'build.h'))

    template_vars = create_template_vars(build_config, options,
                                         modules_to_use,
                                         cc,
                                         archinfo[options.arch],
                                         osinfo[options.os])

    # Performs the I/O
    setup_build(build_config, options, template_vars)

    if options.gen_amalgamation:
        generate_amalgamation(build_config)

    def release_date(datestamp):
        if datestamp == 0:
            return 'undated'
        return 'dated %d' % (datestamp)

    logging.info('Botan %s (%s %s) build setup is complete' % (
        build_config.version_string,
        build_config.version_release_type,
        release_date(build_config.version_datestamp)))

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logging.error(e)
        import traceback
        logging.debug(traceback.format_exc())
        sys.exit(1)
    sys.exit(0)