summaryrefslogtreecommitdiffstats
path: root/make/configure.py
blob: 1bac0874f6956f4c9c5f3250767ffcd2ece34601 (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
###############################################################################
##
## This script is coded for minimum version of Python 2.4 .
## Pyhthon3 is incompatible.
##
## Authors: konablend
##
###############################################################################

import fnmatch
import glob
import optparse
import os
import platform
import re
import subprocess
import sys
import time

from optparse import OptionGroup
from optparse import OptionGroup
from optparse import OptionParser
from sys import stderr
from sys import stdout

class AbortError( Exception ):
    def __init__( self, format, *args ):
        self.value = format % args
    def __str__( self ):
        return self.value

###############################################################################
##
## Main configure object.
##
## dir = containing this configure script
## cwd = current working dir at time of script launch
##
class Configure( object ):
    OUT_QUIET   = 0
    OUT_INFO    = 1
    OUT_VERBOSE = 2

    def __init__( self, verbose ):
        self._log_info    = []
        self._log_verbose = []
        self._record      = False

        self.verbose = verbose
        self.dir = os.path.dirname( sys.argv[0] )
        self.cwd = os.getcwd()

        self.build_dir = '.'

        ## compute src dir which is 2 dirs up from this script
        self.src_dir = os.path.normpath( sys.argv[0] )
        for i in range( 2 ):
            self.src_dir = os.path.dirname( self.src_dir )
        if len( self.src_dir ) == 0:
            self.src_dir = os.curdir

    def _final_dir( self, chdir, dir ):
        dir = os.path.normpath( dir )
        if not os.path.isabs( dir ):
            if os.path.isabs( chdir ):
                dir = os.path.normpath( os.path.abspath(dir ))
            else:
                dir = os.path.normpath( self.relpath( dir, chdir ))
        return dir

    ## output functions
    def errln( self, format, *args ):
        s = (format % args)
        if re.match( '^.*[!?:;.]$', s ):
            stderr.write( 'ERROR: %s configure stop.\n' % (s) )
        else:
            stderr.write( 'ERROR: %s; configure stop.\n' % (s) )
        self.record_log()
        sys.exit( 1 )
    def infof( self, format, *args ):
        line = format % args
        self._log_verbose.append( line )
        if cfg.verbose >= Configure.OUT_INFO:
            self._log_info.append( line )
            stdout.write( line )
    def verbosef( self, format, *args ):
        line = format % args
        self._log_verbose.append( line )
        if cfg.verbose >= Configure.OUT_VERBOSE:
            stdout.write( line )

    ## doc is ready to be populated
    def doc_ready( self ):
        ## compute final paths as they are after chdir into build
        self.build_final  = os.curdir
        self.src_final    = self._final_dir( self.build_dir, self.src_dir )
        self.prefix_final = self._final_dir( self.build_dir, self.prefix_dir )

        cfg.infof( 'compute: makevar SRC/    = %s\n', self.src_final )
        cfg.infof( 'compute: makevar BUILD/  = %s\n', self.build_final )
        cfg.infof( 'compute: makevar PREFIX/ = %s\n', self.prefix_final )

    ## perform chdir and enable log recording
    def chdir( self ):
        if os.path.abspath( self.build_dir ) == os.path.abspath( self.src_dir ):
            cfg.errln( 'build (scratch) directory must not be the same as top-level source root!' )

        if self.build_dir != os.curdir:
            if os.path.exists( self.build_dir ):
                if not options.force:
                    self.errln( 'build directory already exists: %s (use --force to overwrite)', self.build_dir )
            else:
                self.mkdirs( self.build_dir )
            self.infof( 'chdir: %s\n', self.build_dir )
            os.chdir( self.build_dir )

        ## enable logging
        self._record = True

    def mkdirs( self, dir ):
        if len(dir) and not os.path.exists( dir ):
            self.infof( 'mkdir: %s\n', dir )
            os.makedirs( dir )

    def open( self, *args ):
        dir = os.path.dirname( args[0] )
        if len(args) > 1 and args[1].find('w') != -1:
            self.mkdirs( dir )
        m = re.match( '^(.*)\.tmp$', args[0] )
        if m:
            self.infof( 'write: %s\n', m.group(1) )
        else:
            self.infof( 'write: %s\n', args[0] )

        try:
            return open( *args )
        except Exception, x:
            cfg.errln( 'open failure: %s', x )

    def record_log( self ):
        if not self._record:
            return
        self._record = False
        self.verbose = Configure.OUT_QUIET
        file = cfg.open( 'log/config.info.txt', 'w' )
        for line in self._log_info:
            file.write( line )
        file.close()
        file = cfg.open( 'log/config.verbose.txt', 'w' )
        for line in self._log_verbose:
            file.write( line )
        file.close()

    ## Find executable by searching path.
    ## On success, returns full pathname of executable.
    ## On fail, returns None.
    def findExecutable( self, name ):
        if len( os.path.split(name)[0] ):
            if os.access( name, os.X_OK ):
                return name
            return None
        
        if not os.environ.has_key( 'PATH' ) or os.environ[ 'PATH' ] == '':
            path = os.defpath
        else:
            path = os.environ['PATH']
        
        for dir in path.split( os.pathsep ):
            f = os.path.join( dir, name )
            if os.access( f, os.X_OK ):
                return f
        return None

    ## taken from python2.6 -- we need it
    def relpath( self, path, start=os.curdir ):
        """Return a relative version of a path"""

        if not path:
            raise ValueError("no path specified")

        start_list = os.path.abspath(start).split(os.sep)
        path_list = os.path.abspath(path).split(os.sep)

        # Work out how much of the filepath is shared by start and path.
        i = len(os.path.commonprefix([start_list, path_list]))

        rel_list = [os.pardir] * (len(start_list)-i) + path_list[i:]
        if not rel_list:
            return os.curdir
        return os.path.join(*rel_list)

    ## update with parsed cli options
    def update_cli( self, options ):
        self.src_dir    = os.path.normpath( options.src )
        self.build_dir  = os.path.normpath( options.build )
        self.prefix_dir = os.path.normpath( options.prefix )
        if options.sysroot != None:
                self.sysroot_dir = os.path.normpath( options.sysroot )
        else:
                self.sysroot_dir = ""

        if options.minver != None:
                self.minver = options.minver
        else:
                self.minver = ""

        ## special case if src == build: add build subdir
        if os.path.abspath( self.src_dir ) == os.path.abspath( self.build_dir ):
            self.build_dir = os.path.join( self.build_dir, 'build' )

###############################################################################
##
## abstract action
##
## pretext = text which immediately follows 'probe:' output prefix
## abort   = if true configure will exit on probe fail
## head    = if true probe session is stripped of all but first line
## session = output from command, including stderr
## fail    = true if probe failed
##
class Action( object ):
    actions = []

    def __init__( self, category, pretext='unknown', abort=False, head=False ):
        if self not in Action.actions:
            Action.actions.append( self )

        self.category = category
        self.pretext  = pretext
        self.abort    = abort
        self.head     = head
        self.session  = None

        self.run_done = False
        self.fail     = True
        self.msg_fail = 'fail'
        self.msg_pass = 'pass'
        self.msg_end  = 'end'

    def _actionBegin( self ):
        cfg.infof( '%s: %s...', self.category, self.pretext )

    def _actionEnd( self ):
        if self.fail:
            cfg.infof( '(%s) %s\n', self.msg_fail, self.msg_end )
            if self.abort:
                self._dumpSession( cfg.infof )
                cfg.errln( 'unable to continue' )
            self._dumpSession( cfg.verbosef )
            self._failSession()
        else:
            cfg.infof( '(%s) %s\n', self.msg_pass, self.msg_end )
            self._dumpSession( cfg.verbosef )

    def _dumpSession( self, printf ):
        if self.session and len(self.session):
            for line in self.session:
                printf( '  : %s\n', line )
        else:
            printf( '  : <NO-OUTPUT>\n' )

    def _parseSession( self ):
        pass

    def _failSession( self ):
        pass

    def run( self ):
        if self.run_done:
            return
        self.run_done = True
        self._actionBegin()
        self._action()
        if not self.fail:
            self._parseSession()
        self._actionEnd()

###############################################################################
##
## base probe: anything which runs in shell.
##
## pretext = text which immediately follows 'probe:' output prefix
## command = full command and arguments to pipe
## abort   = if true configure will exit on probe fail
## head    = if true probe session is stripped of all but first line
## session = output from command, including stderr
## fail    = true if probe failed
##
class ShellProbe( Action ):
    def __init__( self, pretext, command, abort=False, head=False ):
        super( ShellProbe, self ).__init__( 'probe', pretext, abort, head )
        self.command = command

    def _action( self ):
        ## pipe and redirect stderr to stdout; effects communicate result
        pipe = subprocess.Popen( self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )

        ## read data into memory buffers, only first element (stdout) data is used
        data = pipe.communicate()
        self.fail = pipe.returncode != 0

        if data[0]:
            self.session = data[0].splitlines()
        else:
            self.session = []

        if pipe.returncode:
            self.msg_end = 'code %d' % (pipe.returncode)

    def _dumpSession( self, printf ):
        printf( '  + %s\n', self.command )
        super( ShellProbe, self )._dumpSession( printf )

###############################################################################
##
## Compile test probe: determine if compile time feature is supported
##
## returns true if feature successfully compiles
##
##   
class CCProbe( Action ):
    def __init__( self, pretext, command, test_file ):
        super( CCProbe, self ).__init__( 'probe', pretext )
        self.command = command
        self.test_file = test_file

    def _action( self ):
        ## write program file
        file = open( 'conftest.c', 'w' )
        file.write( self.test_file )
        file.close()
        ## pipe and redirect stderr to stdout; effects communicate result
        pipe = subprocess.Popen( '%s -c -o conftest.o conftest.c' % self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )

        ## read data into memory buffers, only first element (stdout) data is used
        data = pipe.communicate()
        self.fail = pipe.returncode != 0

        if data[0]:
            self.session = data[0].splitlines()
        else:
            self.session = []

        if pipe.returncode:
            self.msg_end = 'code %d' % (pipe.returncode)
        os.remove( 'conftest.c' )
        if not self.fail:
            os.remove( 'conftest.o' )

    def _dumpSession( self, printf ):
        printf( '  + %s\n', self.command )
        super( CCProbe, self )._dumpSession( printf )


###############################################################################
##
## Compile test probe: determine if compile time feature is supported
##
## returns true if feature successfully compiles
##
##   
class LDProbe( Action ):
    def __init__( self, pretext, command, lib, test_file ):
        super( LDProbe, self ).__init__( 'probe', pretext )
        self.command = command
        self.test_file = test_file
        self.lib = lib

    def _action( self ):
        ## write program file
        file = open( 'conftest.c', 'w' )
        file.write( self.test_file )
        file.close()
        ## pipe and redirect stderr to stdout; effects communicate result
        pipe = subprocess.Popen( '%s -o conftest conftest.c %s' % (self.command, self.lib), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )

        ## read data into memory buffers, only first element (stdout) data is used
        data = pipe.communicate()
        self.fail = pipe.returncode != 0

        if data[0]:
            self.session = data[0].splitlines()
        else:
            self.session = []

        if pipe.returncode:
            self.msg_end = 'code %d' % (pipe.returncode)

        os.remove( 'conftest.c' )
        if not self.fail:
            os.remove( 'conftest' )

    def _dumpSession( self, printf ):
        printf( '  + %s\n', self.command )
        super( LDProbe, self )._dumpSession( printf )


###############################################################################
##
## GNU host tuple probe: determine canonical platform type
##
## example results from various platforms:
##
##   powerpc-apple-darwin9.6.0  (Mac OS X 10.5.6 PPC)
##   i386-apple-darwin9.6.0     (Mac OS X 10.5.6 Intel)
##   x86_64-apple-darwin10.8.0  (Mac OS X 10.6.8 Intel)
##   x86_64-apple-darwin11.2.0  (Mac OS X 10.7.2 Intel)
##   i686-pc-cygwin             (Cygwin, Microsoft Vista)
##   x86_64-unknown-linux-gnu   (Linux, Fedora 10 x86_64)
##
class HostTupleProbe( ShellProbe, list ):
    GNU_TUPLE_RE = '([^-]+)-?([^-]*)-([^0-9-]+)([^-]*)-?([^-]*)'

    def __init__( self ):
        super( HostTupleProbe, self ).__init__( 'host tuple', '%s/config.guess' % (cfg.dir), abort=True, head=True )

    def _parseSession( self ):
        if len(self.session):
            self.spec = self.session[0]
        else:
            self.spec = ''

        ## grok GNU host tuples
        m = re.match( HostTupleProbe.GNU_TUPLE_RE, self.spec )
        if not m:
            self.fail = True
            self.msg_end = 'invalid host tuple: %s' % (self.spec)
            return

        self.msg_end = self.spec

        ## assign tuple from regex
        self[:] = m.groups()

        ## for clarity
        self.machine = self[0]
        self.vendor  = self[1]
        self.system  = self[2]
        self.release = self[3]
        self.extra   = self[4]

        ## nice formal name for 'system'
        self.systemf = platform.system()

        if self.match( '*-*-cygwin*' ):
            self.systemf = self[2][0].upper() + self[2][1:]
            
    ## glob-match against spec
    def match( self, *specs ):
        for spec in specs:
            if fnmatch.fnmatch( self.spec, spec ):
                return True
        return False

###############################################################################

class BuildAction( Action, list ):
    def __init__( self ):
        super( BuildAction, self ).__init__( 'compute', 'build tuple', abort=True )

    def _action( self ):
        ## check if --cross spec was used; must maintain 5-tuple compatibility with regex
        if options.cross:
            self.spec = os.path.basename( options.cross ).rstrip( '-' )
        else:
            self.spec = arch.mode[arch.mode.mode]

        ## grok GNU host tuples
        m = re.match( HostTupleProbe.GNU_TUPLE_RE, self.spec )
        if not m:
            self.msg_end = 'invalid host tuple: %s' % (self.spec)
            return

        self.msg_end = self.spec

        ## assign tuple from regex
        self[:] = m.groups()

        ## for clarity
        self.machine = self[0]
        self.vendor  = self[1]
        self.system  = self[2]
        self.release = self[3]
        self.extra   = self[4]
        self.systemf = host.systemf

        ## when cross we need switch for platforms
        if options.cross:
            if self.match( '*mingw*' ):
                self.systemf = 'MinGW'
            elif self.systemf:
                self.systemf[0] = self.systemf[0].upper()
            self.title = '%s %s' % (build.systemf,self.machine)
        else:
            self.title = '%s %s' % (build.systemf,arch.mode.mode)
        self.fail = False

    ## glob-match against spec
    def match( self, *specs ):
        for spec in specs:
            if fnmatch.fnmatch( self.spec, spec ):
                return True
        return False

###############################################################################
##
## value wrapper; value is accepted only if one of host specs matcheds
## otherwise it is None (or a keyword-supplied val)
##
## result is attribute 'value'
##
class IfHost( object ):
    def __init__( self, value, *specs, **kwargs ):
        self.value = kwargs.get('none',None)
        for spec in specs:
            if host.match( spec ):
                self.value = value
                break

    def __nonzero__( self ):
        return self.value != None
        
    def __str__( self ):
        return self.value


###############################################################################
##
## platform conditional value; loops through list of tuples comparing
## to first host match and sets value accordingly; the first value is
## always default.
##
class ForHost( object ):
    def __init__( self, default, *tuples ):
        self.value = default
        for tuple in tuples:
            if host.match( tuple[1] ):
                self.value = tuple[0]
                break

    def __str__( self ):
        return self.value

###############################################################################

class ArchAction( Action ):
    def __init__( self ):
        super( ArchAction, self ).__init__( 'compute', 'available architectures', abort=True )
        self.mode = SelectMode( 'architecture', (host.machine,host.spec) )

    def _action( self ):
        self.fail = False

        ## some match on system should be made here; otherwise we signal a warning. 
        if host.match( '*-*-cygwin*' ):
            pass
        elif host.match( '*-*-darwin11.*' ):
            self.mode['i386']   = 'i386-apple-darwin%s'      % (host.release)
            self.mode['x86_64'] = 'x86_64-apple-darwin%s'    % (host.release)
        elif host.match( '*-*-darwin*' ):
            self.mode['i386']   = 'i386-apple-darwin%s'      % (host.release)
            self.mode['x86_64'] = 'x86_64-apple-darwin%s'    % (host.release)
            self.mode['ppc']    = 'powerpc-apple-darwin%s'   % (host.release)
            self.mode['ppc64']  = 'powerpc64-apple-darwin%s' % (host.release)

            ## special cases in that powerpc does not match gcc -arch value
            ## which we like to use; so it has to be removed.
            ## note: we don't know if apple will release Ssnow Leopad/ppc64 yet; just a guess.
            if 'powerpc' in self.mode:
                del self.mode['powerpc']
                self.mode.mode = 'ppc'
            elif 'powerpc64' in self.mode:
                del self.mode['powerpc64']
                self.mode.mode = 'ppc64'
        elif host.match( '*-*-linux*' ):
            pass
        elif host.match( '*-*-solaris*' ):
            pass
        else:
            self.msg_pass = 'WARNING'

        self.msg_end = self.mode.toString()

    ## glob-match against spec
    def match( self, spec ):
        return fnmatch.fnmatch( self.spec, spec )

###############################################################################

class CoreProbe( Action ):
    def __init__( self ):
        super( CoreProbe, self ).__init__( 'probe', 'number of CPU cores' )
        self.count = 1

    def _action( self ):
        if self.fail:
            ## good for darwin9.6.0 and linux
            try:
                self.count = os.sysconf( 'SC_NPROCESSORS_ONLN' )
                if self.count < 1:
                    self.count = 1
                self.fail = False
            except:
                pass

        if self.fail:
            ## windows
            try:
                self.count = int( os.environ['NUMBER_OF_PROCESSORS'] )
                if self.count < 1:
                    self.count = 1
                self.fail = False
            except:
                pass

        ## clamp
        if self.count < 1:
            self.count = 1
        elif self.count > 32:
            self.count = 32

        if options.launch:
            if options.launch_jobs == 0:
                self.jobs = core.count
            else:
                self.jobs = options.launch_jobs
        else:
            self.jobs = core.count

        self.msg_end = str(self.count)

###############################################################################

class SelectMode( dict ):
    def __init__( self, descr, *modes, **kwargs ):
        super( SelectMode, self ).__init__( modes )
        self.descr = descr
        self.modes = modes
        self.what  = kwargs.get('what',' mode')
        if modes:
            self.default = kwargs.get('default',modes[0][0])
        else:
            self.default = None
        self.mode = self.default

    def cli_add_option( self, parser, option ):
        parser.add_option( option, default=self.mode, metavar='MODE',
            help='select %s%s: %s' % (self.descr,self.what,self.toString()),
            action='callback', callback=self.cli_callback, type='str' )

    def cli_callback( self, option, opt_str, value, parser, *args, **kwargs ):
        if value not in self:
            raise optparse.OptionValueError( 'invalid %s%s: %s (choose from: %s)'
                % (self.descr,self.what,value,self.toString( True )) )
        self.mode = value

    def toString( self, nodefault=False ):
        keys = self.keys()
        keys.sort()
        if len(self) == 1:
            value = self.mode
        elif nodefault:
            value = ' '.join( keys )
        else:
            value = '%s [%s]' % (' '.join( keys ), self.mode )
        return value

###############################################################################
##
## Repository object.
## Holds information gleaned from subversion working dir.
##
## Builds are classed into one of the following types:
##
##  release
##      must be built from official svn with '/tags/' in the url
##  developer
##      must be built from official svn but is not a release
##  unofficial
##      all other builds
##
class RepoProbe( ShellProbe ):
    def __init__( self ):
        svn = 'svn'

        ## Possible the repo was created using an incompatible version than what is
        ## available in PATH when probe runs. Workaround by checking for file
        ## .svn/HANDBRAKE_REPO_PROBE which points to a preferred svn executable.
        try:
            hrp = os.path.join( cfg.src_dir, '.svn', 'HANDBRAKE_REPO_PROBE' )
            if os.path.isfile( hrp ) and os.path.getsize( hrp ) > 0:
                file = cfg.open( hrp, 'r' )
                line = file.readline().strip()
                file.close()
                if line:
                    svn = line
        except:
            pass

        super( RepoProbe, self ).__init__( 'svn info', '%s info %s' % (svn,cfg.src_dir) )

        self.url       = 'svn://nowhere.com/project/unknown'
        self.root      = 'svn://nowhere.com/project'
        self.branch    = 'unknown'
        self.uuid      = '00000000-0000-0000-0000-000000000000';
        self.rev       = 0
        self.date      = '0000-00-00 00:00:00 -0000'
        self.official  = 0
        self.type      = 'unofficial'

    def _parseSession( self ):
        for line in self.session:
            ## grok fields
            m = re.match( '([^:]+):\\s+(.+)', line )
            if not m:
                continue

            (name,value) = m.groups()
            if name == 'URL':
                self.url = value
            elif name == 'Repository Root':
                self.root = value
            elif name == 'Repository UUID':
                self.uuid = value
            elif name == 'Revision':
                self.rev = int( value )
            elif name == 'Last Changed Date':
                # strip chars in parens
                if value.find( ' (' ):
                    self.date = value[0:value.find(' (')]
                else:
                    self.date = value

        ## grok branch
        i = self.url.rfind( '/' )
        if i != -1 and i < len(self.url)-1:
            self.branch = self.url[i+1:]

        # type-classification via repository UUID
        if self.uuid == 'b64f7644-9d1e-0410-96f1-a4d463321fa5':
            self.official = 1
            m = re.match( '([^:]+)://([^/]+)/(.+)', self.url )
            if m and re.match( '.*tags/.*', m.group( 3 )):
                self.type = 'release'
            else:
                self.type = 'developer'

        self.msg_end = self.url

    def _failSession( self ):
        # Look for svn info in version file.
        #
        # Version file would be created manually by source packager.
        # e.g.
        # $ svn info HandBrake > HandBrake/version.txt
        # $ tar -czf handbrake-source.tgz --exclude .svn HandBrake
        cfg.infof( 'probe: version.txt...' )
        try:
            hvp = os.path.join( cfg.src_dir, 'version.txt' )
            if os.path.isfile( hvp ) and os.path.getsize( hvp ) > 0:
                file = open( hvp, 'r' )
                self.session = file.readlines()
                file.close()
                if self.session:
                    self._parseSession()
            if self.rev != 0:
                cfg.infof( '(pass)\n' )
            else:
                cfg.infof( '(fail)\n' )

        except:
            cfg.infof( '(fail)\n' )

###############################################################################
##
## project object.
##
## Contains manually updated version numbers consistent with HB releases
## and other project metadata.
##
class Project( Action ):
    def __init__( self ):
        super( Project, self ).__init__( 'compute', 'project data' )

        self.name          = 'HandBrake'
        self.acro_lower    = 'hb'
        self.acro_upper    = 'HB'
        self.url_website   = 'https://handbrake.fr'
        self.url_community = 'https://forum.handbrake.fr'
        self.url_irc       = 'irc://irc.freenode.net/handbrake'

        self.name_lower = self.name.lower()
        self.name_upper = self.name.upper()

        self.vmajor = 0
        self.vminor = 10
        self.vpoint = 0

    def _action( self ):
        ## add architecture to URL only for Mac
        if fnmatch.fnmatch( build.spec, '*-*-darwin*' ):
            url_arch = '.%s' % (arch.mode.mode)
        else:
            url_arch = ''

        if repo.type == 'release':
            self.version = '%d.%d.%d' % (self.vmajor,self.vminor,self.vpoint)
            url_ctype = ''
            url_ntype = 'stable'
            self.build = time.strftime('%Y%m%d') + '00'
            self.title = '%s %s (%s)' % (self.name,self.version,self.build)
        elif repo.type == 'developer':
            self.version = '%dsvn' % (repo.rev)
            url_ctype = '_unstable'
            url_ntype = 'unstable'
            self.build = time.strftime('%Y%m%d') + '01'
            self.title = '%s svn%d (%s)' % (self.name,repo.rev,self.build)
        else:
            self.version = 'rev%d' % (repo.rev)
            url_ctype = '_unofficial'
            url_ntype = 'unofficial'
            self.build = time.strftime('%Y%m%d') + '99'
            self.title = '%s rev%d (%s)' % (self.name,repo.rev,self.build)

        self.url_appcast = 'https://handbrake.fr/appcast%s%s.xml' % (url_ctype,url_arch)
        self.url_appnote = 'https://handbrake.fr/appcast/%s.html' % (url_ntype)

        self.msg_end = '%s (%s)' % (self.name,repo.type)
        self.fail = False

###############################################################################

class ToolProbe( Action ):
    tools = []

    def __init__( self, var, *names, **kwargs ):
        super( ToolProbe, self ).__init__( 'find', abort=kwargs.get('abort',True) )
        if not self in ToolProbe.tools:
            ToolProbe.tools.append( self )
        self.var    = var
        self.names  = []
        self.kwargs = kwargs
        for name in names:
            if name:
                self.names.append( str(name) )
        self.name = self.names[0]
        self.pretext = self.name
        self.pathname = self.names[0]
        self.minversion = kwargs.get('minversion', None)

    def _action( self ):
        self.session = []
        for i,name in enumerate(self.names):
            self.session.append( 'name[%d] = %s' % (i,name) )
        for name in self.names:
            f = cfg.findExecutable( name )
            if f:
                self.pathname = f
                self.fail = False
                self.msg_end = f
                break
        if self.fail:
            self.msg_end = 'not found'
        elif self.minversion:
            self.version = VersionProbe( [self.pathname, '--version'], minversion=self.minversion )

    def cli_add_option( self, parser ):
        parser.add_option( '--'+self.name, metavar='PROG',
            help='[%s]' % (self.pathname),
            action='callback', callback=self.cli_callback, type='str' )

    def cli_callback( self, option, opt_str, value, parser, *args, **kwargs ):
        self.__init__( self.var, value, **self.kwargs )
        self.run()

    def doc_add( self, doc ):
        doc.add( self.var, self.pathname )

###############################################################################

###############################################################################
##
## version probe: passes --version to command and only cares about first line
## of output. If probe fails, a default version of '0.0.0' results.
## The default rexpr is useful for some very simple version strings. A Custom
## expression would be required for more complex version strings.
##
## command = full command and arguments to pipe
## rexpr   = a regular expression which must return named subgroups:
##              name: mandatory. The tool name.
##              svers: mandatory. The whole version tuple to be represented as string.
##              i0: mandatory. First element of version tuple to be parsed as int.
##              i1: optional. Second element of version tuple to be parsed as int.
##              i2: optional. Third element of version tuple to be parsed as int.
##           All matching is case-insensitive.
## abort   = if true configure will exit on probe fail
## session = result. array of lines (stdout/stderr) from command
## fail    = result. true if probe failed
## svers   = result. string of version tuple
## ivers   = result. int[3] of version tuple
##
class VersionProbe( Action ):
    def __init__( self, command, minversion=None, rexpr=None, abort=False ):
        super( VersionProbe, self ).__init__( 'version probe', os.path.basename(command[0]), abort )
        self.command = command
        self.minversion = minversion
        if not rexpr:
            rexpr = '(?P<name>[^.]+)\s+(?P<svers>(?P<i0>\d+)(\.(?P<i1>\d+))?(\.(?P<i2>\d+))?)'
        self.rexpr = rexpr

    def _action( self ):
        ## pipe and redirect stderr to stdout; effects communicate result
        pipe = subprocess.Popen( self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )

        ## read data into memory buffers
        data = pipe.communicate()
        self.fail = pipe.returncode != 0

        if data[0]:
            self.session = data[0].splitlines()
        else:
            self.session = []

        self.svers = '0.0.0'
        self.ivers = [0,0,0]

        try:
            if not self.fail and self.session and len(self.session):
                self.fail = True
                self._parse()
            self.fail = False
            self.msg_end = self.svers
        except Exception, x:
            self.svers = '0.0.0'
            self.ivers = [0,0,0]
            self.msg_end = str(x)

    def _dumpSession( self, printf ):
        printf( '  + %s\n', ' '.join(self.command) )
        super( VersionProbe, self )._dumpSession( printf )

    def _parse( self ):
        mo = re.match( self.rexpr, self.session[0], re.IGNORECASE )
        md = mo.groupdict()
        self.svers = md['svers']
        if 'i0' in md and md['i0']:
            self.ivers[0] = int(md['i0'])
        if 'i1' in md and md['i1']:
            self.ivers[1] = int(md['i1'])
        if 'i2' in md and md['i2']:
            self.ivers[2] = int(md['i2'])

    def inadequate( self ):
        if not self.minversion:
            return False
        return self.lesser( self.minversion )

    def lesser( self, ivers ):
        for i in range(0,3):
            if self.ivers[i] < ivers[i]:
                return True
            elif self.ivers[i] > ivers[i]:
                return False
        return False

###############################################################################

class SelectTool( Action ):
    selects = []

    def __init__( self, var, name, *pool, **kwargs ):
        super( SelectTool, self ).__init__( 'select', abort=kwargs.get('abort',True) )
        self.pretext = name
        if not self in SelectTool.selects:
            SelectTool.selects.append( self )
        self.var      = var
        self.name     = name
        self.pool     = pool
        self.kwargs   = kwargs

    def _action( self ):
        self.session = []
        for i,(name,tool) in enumerate(self.pool):
            self.session.append( 'tool[%d] = %s (%s)' % (i,name,tool.pathname) )
        for (name,tool) in self.pool:
            if not tool.fail:
                self.selected = name
                self.fail = False
                self.msg_end = '%s (%s)' % (name,tool.pathname)
                break
        if self.fail:
            self.msg_end = 'not found'

    def cli_add_option( self, parser ):
        parser.add_option( '--'+self.name, metavar='MODE',
            help='select %s mode: %s' % (self.name,self.toString()),
            action='callback', callback=self.cli_callback, type='str' )

    def cli_callback( self, option, opt_str, value, parser, *args, **kwargs ):
        found = False
        for (name,tool) in self.pool:
            if name == value:
                found = True
                self.__init__( self.var, self.name, [name,tool], **kwargs )
                self.run()
                break
        if not found:
            raise optparse.OptionValueError( 'invalid %s mode: %s (choose from: %s)'
                % (self.name,value,self.toString( True )) )

    def doc_add( self, doc ):
        doc.add( self.var, self.selected )

    def toString( self, nodefault=False ):
        if len(self.pool) == 1:
            value = self.pool[0][0]
        else:
            s = ''
            for key,value in self.pool:
                s += ' ' + key
            if nodefault:
                value = s[1:]
            else:
                value = '%s [%s]' % (s[1:], self.selected )
        return value

###############################################################################
##
## config object used to output gnu-make or gnu-m4 output.
##
## - add() to add NAME/VALUE pairs suitable for both make/m4.
## - addBlank() to add a linefeed for both make/m4.
## - addMake() to add a make-specific line.
## - addM4() to add a m4-specific line.
##
class ConfigDocument:
    def __init__( self ):
        self._elements = []

    def _outputMake( self, file, namelen, name, value, append ):
        if append:
            if value == None or len(str(value)) == 0:
                file.write( '%-*s +=\n' % (namelen, name) )
            else:
                file.write( '%-*s += %s\n' % (namelen, name, value) )
        else:
            if value == None or len(str(value)) == 0:
                file.write( '%-*s  =\n' % (namelen, name) )
            else:
                file.write( '%-*s  = %s\n' % (namelen, name, value) )

    def _outputM4( self, file, namelen, name, value ):
        namelen += 7
        name = '<<__%s>>,' % name.replace( '.', '_' )
        file.write( 'define(%-*s  <<%s>>)dnl\n' % (namelen, name, value ))

    def add( self, name, value, append=False ):
        self._elements.append( [name,value,append] )

    def addBlank( self ):
        self._elements.append( None )

    def addComment( self, format, *args ):
        self.addMake( '## ' + format % args )
        self.addM4( 'dnl ' + format % args )

    def addMake( self, line ):
        self._elements.append( ('?make',line) )

    def addM4( self, line ):
        self._elements.append( ('?m4',line) )

    def output( self, file, type ):
        namelen = 0
        for item in self._elements:
            if item == None or item[0].find( '?' ) == 0:
                continue
            if len(item[0]) > namelen:
                namelen = len(item[0])
        for item in self._elements:
            if item == None:
                if type == 'm4':
                    file.write( 'dnl\n' )
                else:
                    file.write( '\n' )
                continue
            if item[0].find( '?' ) == 0:
                if item[0].find( type, 1 ) == 1:
                    file.write( '%s\n' % (item[1]) )
                continue

            if type == 'm4':
                self._outputM4( file, namelen, item[0], item[1] )
            else:
                self._outputMake( file, namelen, item[0], item[1], item[2] )

    def update( self, name, value ):
        for item in self._elements:
            if item == None:
                continue
            if item[0] == name:
                item[1] = value
                return
        raise ValueError( 'element not found: %s' % (name) )

    def write( self, type ):
        if type == 'make':
            fname = 'GNUmakefile'
        elif type == 'm4':
            fname = os.path.join( 'project', project.name_lower + '.m4' )
        else:
            raise ValueError, 'unknown file type: ' + type

        ftmp  = fname + '.tmp'
        try:
            try:
                file = cfg.open( ftmp, 'w' )
                self.output( file, type )
            finally:
                try:
                    file.close()
                except:
                    pass
        except Exception, x:
            try:
                os.remove( ftmp )
            except Exception, x:
                pass
            cfg.errln( 'failed writing to %s\n%s', ftmp, x )

        try:
            os.rename( ftmp, fname )
        except Exception, x:
            cfg.errln( 'failed writing to %s\n%s', fname, x )

###############################################################################
##
## create cli parser
##

## class to hook options and create CONF.args list
class Option( optparse.Option ):
    conf_args = []

    def _conf_record( self, opt, value ):
        ## filter out non-applicable options
        if re.match( '^--(force|launch).*$', opt ):
            return

        ## remove duplicates (last duplicate wins)
        for i,arg in enumerate( Option.conf_args ):
            if opt == arg[0]:
                del Option.conf_args[i]
                break

        if value:
            Option.conf_args.append( [opt,'%s=%s' % (opt,value)] )
        else:
            Option.conf_args.append( [opt,'%s' % (opt)] )

    def take_action( self, action, dest, opt, value, values, parser ):
        self._conf_record( opt, value )
        return optparse.Option.take_action( self, action, dest, opt, value, values, parser )

def createCLI():
    cli = OptionParser( 'usage: %prog [OPTIONS...] [TARGETS...]' )
    cli.option_class = Option

    cli.description = ''
    cli.description += 'Configure %s build system.' % (project.name)

    ## add hidden options
    cli.add_option( '--xcode-driver', default='bootstrap', action='store', help=optparse.SUPPRESS_HELP )
    cli.add_option( '--force', default=False, action='store_true', help='overwrite existing build config' )
    cli.add_option( '--verbose', default=False, action='store_true', help='increase verbosity' )

    ## add install options
    grp = OptionGroup( cli, 'Directory Locations' )
    h = IfHost( 'specify sysroot of SDK for Xcode builds', '*-*-darwin*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--sysroot', default=None, action='store', metavar='DIR',
        help=h )
    grp.add_option( '--src', default=cfg.src_dir, action='store', metavar='DIR',
        help='specify top-level source dir [%s]' % (cfg.src_dir) )
    grp.add_option( '--build', default=cfg.build_dir, action='store', metavar='DIR',
        help='specify build scratch/output dir [%s]' % (cfg.build_dir) )
    grp.add_option( '--prefix', default=cfg.prefix_dir, action='store', metavar='DIR',
        help='specify install dir for products [%s]' % (cfg.prefix_dir) )
    cli.add_option_group( grp )

    ## add feature options
    grp = OptionGroup( cli, 'Feature Options' )

    h = IfHost( 'enable assembly code in non-contrib modules', 'NOMATCH*-*-darwin*', 'NOMATCH*-*-linux*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-asm', default=False, action='store_true', help=h )

    h = IfHost( 'disable GTK GUI', '*-*-linux*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--disable-gtk', default=False, action='store_true', help=h )
    h = IfHost( 'disable GTK GUI update checks', '*-*-linux*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--disable-gtk-update-checks', default=False, action='store_true', help=h )
    h = IfHost( 'enable GTK GUI (mingw)', '*-*-mingw*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-gtk-mingw', default=False, action='store_true', help=h )
    h = IfHost( 'disable gstreamer (live preview)', '*-*-linux*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--disable-gst', default=False, action='store_true', help=h )
    h = IfHost( 'enable use of Intel Quick Sync Video hardware acceleration', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-qsv', default=False, action='store_true', help=h )

    h = IfHost( 'enable HWD features', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-hwd', default=False, action='store_true', help=h )
    
    h = IfHost( 'enable use of x265 encoding', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-x265', default=True, action='store_true', help=h )
    grp.add_option( '--disable-x265', dest="enable_x265", action='store_false' )

    h = IfHost( 'enable use of fdk-aac encoder', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-fdk-aac', dest="enable_fdk_aac", default=not host.match( '*-*-darwin*' ), action='store_true', help=h )
    grp.add_option( '--disable-fdk-aac', dest="enable_fdk_aac", action='store_false' )

    h = IfHost( 'enable use of libav aac encoder', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-libav-aac', dest="enable_libav_aac", default=not host.match( '*-*-darwin*' ), action='store_true', help=h )
    grp.add_option( '--disable-libav-aac', dest="enable_libav_aac", action='store_false' )

    cli.add_option_group( grp )

    ## add launch options
    grp = OptionGroup( cli, 'Launch Options' )
    grp.add_option( '--launch', default=False, action='store_true',
        help='launch build, capture log and wait for completion' )
    grp.add_option( '--launch-jobs', default=1, action='store', metavar='N', type='int',
        help='allow N jobs at once; 0 to match CPU count [1]' )
    grp.add_option( '--launch-args', default=None, action='store', metavar='ARGS',
        help='specify additional ARGS for launch command' )
    grp.add_option( '--launch-quiet', default=False, action='store_true',
        help='do not echo build output while waiting' )
    cli.add_option_group( grp )

    ## add compile options
    grp = OptionGroup( cli, 'Compiler Options' )
    debugMode.cli_add_option( grp, '--debug' )
    optimizeMode.cli_add_option( grp, '--optimize' )
    arch.mode.cli_add_option( grp, '--arch' )
    grp.add_option( '--cross', default=None, action='store', metavar='SPEC',
        help='specify GCC cross-compilation spec' )
    h = IfHost( 'specify Mac OS X deployment target for Xcode builds', '*-*-darwin*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--minver', default=None, action='store', metavar='VER',
        help=h )

    h = IfHost( 'Build and use local yasm', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-local-yasm', default=False, action='store_true', help=h )
    h = IfHost( 'Build and use local autotools', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-local-autotools', default=False, action='store_true', help=h )
    h = IfHost( 'Build and use local cmake', '*-*-*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-local-cmake', default=False, action='store_true', help=h )
    h = IfHost( 'Build and use local pkg-config', '*-*-darwin*', none=optparse.SUPPRESS_HELP ).value
    grp.add_option( '--enable-local-pkgconfig', default=False, action='store_true', help=h )

    cli.add_option_group( grp )

    ## add Xcode options
    if host.match( '*-*-darwin*' ):
        grp = OptionGroup( cli, 'Xcode Options' )
        grp.add_option( '--disable-xcode', default=False, action='store_true',
            help='disable Xcode' )
        grp.add_option( '--xcode-symroot', default='xroot', action='store', metavar='DIR',
            help='specify root of the directory hierarchy that contains product files and intermediate build files' )
        xcconfigMode.cli_add_option( grp, '--xcode-config' )
        cli.add_option_group( grp )

    ## add tool locations
    grp = OptionGroup( cli, 'Tool Basenames and Locations' )
    for tool in ToolProbe.tools:
        tool.cli_add_option( grp )
    cli.add_option_group( grp )

    ## add tool modes
    grp = OptionGroup( cli, 'Tool Options' )
    for select in SelectTool.selects:
        select.cli_add_option( grp )
    cli.add_option_group( grp )
    return cli

###############################################################################
##
## launcher - used for QuickStart method; launch; build and capture log.
##
class Launcher:
    def __init__( self, targets ):
        # open build logfile
        self._file = cfg.open( 'log/build.txt', 'w' )

        cmd = '%s -j%d' % (Tools.gmake.pathname,core.jobs)
        if options.launch_args:
            cmd += ' ' + options.launch_args
        if len(targets):
            cmd += ' ' + ' '.join(targets)

        ## record begin
        timeBegin = time.time()
        self.infof( 'time begin: %s\n', time.asctime() )
        self.infof( 'launch: %s\n', cmd )
        if options.launch_quiet:
            stdout.write( 'building to %s ...\n' % (os.path.abspath( cfg.build_final )))
        else:
            stdout.write( '%s\n' % ('-' * 79) )

        ## launch/pipe
        try:
            pipe = subprocess.Popen( cmd, shell=True, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
        except Exception, x:
            cfg.errln( 'launch failure: %s', x )
        for line in pipe.stdout:
            self.echof( '%s', line )
        pipe.wait()

        ## record end
        timeEnd = time.time()
        elapsed = timeEnd - timeBegin

        if pipe.returncode:
            result = 'FAILURE (code %d)' % pipe.returncode
        else:
            result = 'SUCCESS'

        ## present duration in decent format
        seconds = elapsed
        hours = int(seconds / 3600)
        seconds -= hours * 3600
        minutes = int(seconds / 60)
        seconds -= minutes * 60

        segs = []
        duration = ''

        if hours == 1:
            segs.append( '%d hour' % hours )
        elif hours > 1:
            segs.append( '%d hours' % hours )

        if len(segs) or minutes == 1:
            segs.append( '%d minute' % minutes )
        elif len(segs) or  minutes > 1:
            segs.append( '%d minutes' % minutes )

        if seconds == 1:
            segs.append( '%d second' % seconds )
        else:
            segs.append( '%d seconds' % seconds )

        if not options.launch_quiet:
            stdout.write( '%s\n' % ('-' * 79) )
        self.infof( 'time end: %s\n', time.asctime() )
        self.infof( 'duration: %s (%.2fs)\n', ', '.join(segs), elapsed )
        self.infof( 'result: %s\n', result )

        ## cleanup
        self._file.close()

    def echof( self, format, *args ):
        line = format % args
        self._file.write( line )
        if not options.launch_quiet:
            stdout.write( '  : %s' % line )
            stdout.flush()

    def infof( self, format, *args ):
        line = format % args
        self._file.write( line )
        cfg.infof( '%s', line )

###############################################################################
##
## main program
##
try:
    ## we need to pre-check argv for -h or --help or --verbose to deal with
    ## initializing Configure correctly.
    verbose = Configure.OUT_INFO
    for arg in sys.argv:
        if arg == '-h' or arg == '--help':
            verbose = Configure.OUT_QUIET
            break
        if arg == '--verbose':
            verbose = Configure.OUT_VERBOSE

    ## create main objects; actions/probes run() is delayed.
    ## if any actions must be run earlier (eg: for configure --help purposes)
    ## then run() must be invoked earlier. subequent run() invocations
    ## are ignored.
    cfg   = Configure( verbose )
    host  = HostTupleProbe(); host.run()

    cfg.prefix_dir = ForHost( '/usr/local', ['/Applications','*-*-darwin*'] ).value

    build = BuildAction()
    arch  = ArchAction(); arch.run()

    ## create remaining main objects
    core    = CoreProbe()
    repo    = RepoProbe()
    project = Project()

    ## create tools in a scope
    class Tools:
        ar    = ToolProbe( 'AR.exe',    'ar' )
        cp    = ToolProbe( 'CP.exe',    'cp' )
        curl  = ToolProbe( 'CURL.exe',  'curl', abort=False )
        gcc   = ToolProbe( 'GCC.gcc',   'gcc', IfHost( 'gcc-4', '*-*-cygwin*' ))

        if host.match( '*-*-darwin*' ):
            gmake = ToolProbe( 'GMAKE.exe', 'make', 'gmake' )
        else:
            gmake = ToolProbe( 'GMAKE.exe', 'gmake', 'make' )

        m4       = ToolProbe( 'M4.exe',       'm4' )
        mkdir    = ToolProbe( 'MKDIR.exe',    'mkdir' )
        patch    = ToolProbe( 'PATCH.exe',    'gpatch', 'patch' )
        rm       = ToolProbe( 'RM.exe',       'rm' )
        ranlib   = ToolProbe( 'RANLIB.exe',   'ranlib' )
        strip    = ToolProbe( 'STRIP.exe',    'strip' )
        tar      = ToolProbe( 'TAR.exe',      'gtar', 'tar' )
        wget     = ToolProbe( 'WGET.exe',     'wget', abort=False )
        yasm     = ToolProbe( 'YASM.exe',     'yasm', abort=False, minversion=[1,2,0] )
        autoconf = ToolProbe( 'AUTOCONF.exe', 'autoconf', abort=False )
        automake = ToolProbe( 'AUTOMAKE.exe', 'automake', abort=False )
        cmake    = ToolProbe( 'CMAKE.exe',    'cmake', abort=False )
        libtool  = ToolProbe( 'LIBTOOL.exe',  'libtool', abort=False )
        pkgconfig = ToolProbe( 'PKGCONFIG.exe', 'pkg-config', abort=False )

        xcodebuild = ToolProbe( 'XCODEBUILD.exe', 'xcodebuild', abort=False )
        lipo       = ToolProbe( 'LIPO.exe',       'lipo', abort=False )

        fetch = SelectTool( 'FETCH.select', 'fetch', ['wget',wget], ['curl',curl] )

    ## run tool probes
    for tool in ToolProbe.tools:
        tool.run()
    for select in SelectTool.selects:
        select.run()

    debugMode = SelectMode( 'debug', ('none','none'), ('min','min'), ('std','std'), ('max','max') )
    optimizeMode = SelectMode( 'optimize', ('none','none'), ('speed','speed'), ('size','size'), default='speed' )

    ## find xcconfig values
    xcconfigMode = SelectMode( 'xcconfig', ('none',None), what='' )
    if host.match( '*-*-darwin*' ):
        for xc in glob.glob( os.path.join(cfg.dir, '../macosx/xcconfig/*.xcconfig') ):
            bname = os.path.basename( xc )
            xname = os.path.splitext( bname )
            if xname and xname[0]:
                xcconfigMode[xname[0]] = bname
        if not 'native' in xcconfigMode:
            raise Exception( 'native xcconfig not found' )
        xcconfigMode.default = 'native'
        xcconfigMode.mode = xcconfigMode.default

    ## create CLI and parse
    cli = createCLI()
    (options,args) = cli.parse_args()

    ## update cfg with cli directory locations
    cfg.update_cli( options )

    ## prepare list of targets and NAME=VALUE args to pass to make
    targets = []
    exports = []
    rx_exports = re.compile( '([^=]+)=(.*)' )
    for arg in args:
        m = rx_exports.match( arg )
        if m:
            exports.append( m.groups() )
        else:
            targets.append( arg )

    ## re-run tools with cross-compilation needs
    if options.cross:
        for tool in ( Tools.ar, Tools.gcc, Tools.ranlib, Tools.strip ):
            tool.__init__( tool.var, '%s-%s' % (options.cross,tool.name), **tool.kwargs )
            tool.run()

    ## run delayed actions
    for action in Action.actions:
        action.run()

    ## enable local yasm when yasm probe fails or version is too old
    ## x264 requires 1.2.0+
    if not options.enable_local_yasm:
        if Tools.yasm.fail:
            stdout.write( 'note: enabling local yasm: missing system yasm\n' )
            options.enable_local_yasm = True
        elif Tools.yasm.version.inadequate():
            stdout.write( 'note: enabling local yasm: minimum required version is %s and %s is %s\n' % ('.'.join([str(i) for i in Tools.yasm.version.minversion]),Tools.yasm.pathname,Tools.yasm.version.svers) )
            options.enable_local_yasm = True

    ## enable local autotools when any of { autoconf, automake, libtool } probe fails
    if not options.enable_local_autotools and (Tools.autoconf.fail or Tools.automake.fail or Tools.libtool.fail):
        stdout.write( 'note: enabling local autotools\n' )
        options.enable_local_autotools = True

    ## enable local cmake when cmake probe fails
    if not options.enable_local_cmake and (Tools.cmake.fail):
        stdout.write( 'note: enabling local cmake\n' )
        options.enable_local_cmake = True

    ## enable local pkg-config when probe fails
    if not options.enable_local_pkgconfig and Tools.pkgconfig.fail:
        stdout.write( 'note: enabling local pkgconfig\n' )
        options.enable_local_pkgconfig = True

    if build.system == 'mingw':
        dlfcn_test = """
#include <dlfcn.h>
#include <stdio.h>

void fnord() { int i=42;}
int main ()
{
  void *self = dlopen (0, RTLD_GLOBAL|RTLD_NOW);
  int status = 1;

  if (self)
    {
      if (dlsym (self,"fnord"))       status = 0;
      else if (dlsym( self,"_fnord")) status = 0;
      /* dlclose (self); */
    }
  else
    puts (dlerror ());

  return status;
}
"""
        dlfcn = LDProbe( 'static dlfcn', '%s -static' % Tools.gcc.pathname, '-ldl', dlfcn_test )
        dlfcn.run()

        pthread_test = """
#include <stdio.h>
#include <pthread.h>
int main ()
{
  pthread_t thread;
  pthread_create (&thread, NULL, NULL, NULL);
  return 0;
}
"""
        pthread = LDProbe( 'static pthread', '%s -static' % Tools.gcc.pathname, '-lpthreadGC2', pthread_test )
        pthread.run()

        bz2_test = """
#include <stdio.h>
#include <bzlib.h>
int main ()
{
  BZ2_bzReadOpen(NULL, NULL, 0, 0, NULL, 0);
  return 0;
}
"""
        bz2 = LDProbe( 'static bz2', '%s -static' % Tools.gcc.pathname, '-lbz2', bz2_test )
        bz2.run()

        libz_test = """
#include <stdio.h>
#include <zlib.h>
int main ()
{
  compress(NULL, NULL, NULL, 0);
  return 0;
}
"""
        libz = LDProbe( 'static zlib', '%s -static' % Tools.gcc.pathname, '-lz', libz_test )
        libz.run()

        iconv_test = """
#include <stdio.h>
#include <iconv.h>
int main ()
{
  iconv_open(NULL, NULL);
  return 0;
}
"""
        iconv = LDProbe( 'static iconv', '%s -static' % Tools.gcc.pathname, '-liconv', iconv_test )
        iconv.run()

        regex_test = """
#include <stdio.h>
#include <regex.h>

int match(regex_t *x, char *s)
{
    regmatch_t matches[1];
    return regexec(x, s, 1, matches, 0);
}

int main()
{
    int     rv;
    regex_t exp;

    rv = regcomp(&exp, "^[0-9]+$";", REG_EXTENDED);
    if (rv != 0) {
        return 1;
    }

    if (match(&exp, "7") != 0)
    {
        return 1;
    }
    if (match(&exp, "foo") == 0)
    {
        return 1;
    }

    regfree(&exp);
    return 0;
}
"""
        regex = LDProbe( 'static regex', '%s -static' % Tools.gcc.pathname, '-lregex', regex_test )
        regex.run()

    ## cfg hook before doc prep
    cfg.doc_ready()

    ## create document object
    doc = ConfigDocument()
    doc.addComment( 'generated by configure on %s', time.strftime( '%c' ))

    ## add configure line for reconfigure purposes
    doc.addBlank()
    args = []
    for arg in Option.conf_args:
        args.append( arg[1] )
    doc.add( 'CONF.args', ' '.join( args ))

    doc.addBlank()
    doc.add( 'HB.title',       project.title )
    doc.add( 'HB.name',        project.name )
    doc.add( 'HB.name.lower',  project.name_lower )
    doc.add( 'HB.name.upper',  project.name_upper )
    doc.add( 'HB.acro.lower',  project.acro_lower )
    doc.add( 'HB.acro.upper',  project.acro_upper )

    doc.add( 'HB.url.website',    project.url_website )
    doc.add( 'HB.url.community',  project.url_community )
    doc.add( 'HB.url.irc',        project.url_irc )
    doc.add( 'HB.url.appcast',    project.url_appcast )
    doc.add( 'HB.url.appnote',    project.url_appnote )

    doc.add( 'HB.version.major',  project.vmajor )
    doc.add( 'HB.version.minor',  project.vminor )
    doc.add( 'HB.version.point',  project.vpoint )
    doc.add( 'HB.version',        project.version )
    doc.add( 'HB.version.hex',    '%04x%02x%02x%08x' % (project.vmajor,project.vminor,project.vpoint,repo.rev) )

    doc.add( 'HB.build', project.build )

    doc.add( 'HB.repo.url',       repo.url )
    doc.add( 'HB.repo.root',      repo.root )
    doc.add( 'HB.repo.branch',    repo.branch )
    doc.add( 'HB.repo.uuid',      repo.uuid )
    doc.add( 'HB.repo.rev',       repo.rev )
    doc.add( 'HB.repo.date',      repo.date )
    doc.add( 'HB.repo.official',  repo.official )
    doc.add( 'HB.repo.type',      repo.type )

    doc.addBlank()
    doc.add( 'HOST.spec',    host.spec )
    doc.add( 'HOST.machine', host.machine )
    doc.add( 'HOST.vendor',  host.vendor )
    doc.add( 'HOST.system',  host.system )
    doc.add( 'HOST.systemf', host.systemf )
    doc.add( 'HOST.release', host.release )
    doc.add( 'HOST.extra',   host.extra )
    doc.add( 'HOST.title',   '%s %s' % (host.systemf,arch.mode.default) )
    doc.add( 'HOST.ncpu',    core.count )

    doc.addBlank()
    doc.add( 'BUILD.spec',    build.spec )
    doc.add( 'BUILD.machine', build.machine )
    doc.add( 'BUILD.vendor',  build.vendor )
    doc.add( 'BUILD.system',  build.system )
    doc.add( 'BUILD.systemf', build.systemf )
    doc.add( 'BUILD.release', build.release )
    doc.add( 'BUILD.extra',   build.extra )
    doc.add( 'BUILD.title',   build.title )
    doc.add( 'BUILD.ncpu',    core.count )
    doc.add( 'BUILD.jobs',    core.jobs )

    doc.add( 'BUILD.cross', int(options.cross != None or arch.mode.mode != arch.mode.default) )
    if options.cross:
        doc.add( 'BUILD.cross.prefix', '%s-' % (options.cross) )
    else:
        doc.add( 'BUILD.cross.prefix', '' )

    doc.add( 'BUILD.date',   time.strftime('%c') )
    doc.add( 'BUILD.arch',   arch.mode.mode )

    doc.addBlank()
    doc.add( 'SRC',     cfg.src_final )
    doc.add( 'SRC/',    cfg.src_final + os.sep )
    doc.add( 'BUILD',   cfg.build_final )
    doc.add( 'BUILD/',  cfg.build_final + os.sep )
    doc.add( 'PREFIX',  cfg.prefix_final )
    doc.add( 'PREFIX/', cfg.prefix_final + os.sep )
    
    doc.addBlank()
    doc.add( 'FEATURE.local_yasm', int( options.enable_local_yasm ))
    doc.add( 'FEATURE.local_autotools', int( options.enable_local_autotools ))
    doc.add( 'FEATURE.local_cmake', int( options.enable_local_cmake ))
    doc.add( 'FEATURE.local_pkgconfig', int( options.enable_local_pkgconfig ))
    doc.add( 'FEATURE.asm',        'disabled' )
    doc.add( 'FEATURE.gtk',        int( not options.disable_gtk ))
    doc.add( 'FEATURE.gtk.update.checks', int( not options.disable_gtk_update_checks ))
    doc.add( 'FEATURE.gtk.mingw',  int( options.enable_gtk_mingw ))
    doc.add( 'FEATURE.gst',        int( not options.disable_gst ))
    doc.add( 'FEATURE.fdk_aac',    int( options.enable_fdk_aac ))
    doc.add( 'FEATURE.libav_aac',  int( options.enable_libav_aac ))
    doc.add( 'FEATURE.qsv',        int( options.enable_qsv ))
    doc.add( 'FEATURE.hwd',        int( options.enable_hwd ))
    doc.add( 'FEATURE.xcode',      int( not (Tools.xcodebuild.fail or options.disable_xcode or options.cross) ))
    doc.add( 'FEATURE.x265',       int( options.enable_x265 ))

    if not Tools.xcodebuild.fail and not options.disable_xcode:
        doc.addBlank()
        doc.add( 'XCODE.driver', options.xcode_driver )
        if os.path.isabs(options.xcode_symroot):
            doc.add( 'XCODE.symroot', options.xcode_symroot )
        else:
            doc.add( 'XCODE.symroot', os.path.abspath(os.path.join(cfg.build_dir,options.xcode_symroot)) )
        doc.add( 'XCODE.xcconfig', xcconfigMode[xcconfigMode.mode] )

    if build.system == 'mingw':
        doc.addBlank()
        if not dlfcn.fail:
            doc.add( 'HAS.dlfcn', 1 )
        if not pthread.fail:
            doc.add( 'HAS.pthread', 1 )
        if not bz2.fail:
            doc.add( 'HAS.bz2', 1 )
        if not libz.fail:
            doc.add( 'HAS.libz', 1 )
        if not iconv.fail:
            doc.add( 'HAS.iconv', 1 )
        if not regex.fail:
            doc.add( 'HAS.regex', 1 )

    doc.addMake( '' )
    doc.addMake( '## define debug mode and optimize before other includes' )
    doc.addMake( '## since it is tested in some module.defs' )
    doc.add( 'GCC.g', debugMode.mode )
    doc.add( 'GCC.O', optimizeMode.mode )
    doc.addBlank()
    doc.addMake( '## include definitions' )
    doc.addMake( 'include $(SRC/)make/include/main.defs' )

    doc.addBlank()
    for tool in ToolProbe.tools:
        tool.doc_add( doc )

    doc.addBlank()
    for select in SelectTool.selects:
        select.doc_add( doc )

    doc.addBlank()
    if build.match( '*-*-darwin*' ):
        doc.add( 'GCC.archs', arch.mode.mode )
        doc.add( 'GCC.sysroot', cfg.sysroot_dir )
        doc.add( 'GCC.minver', cfg.minver )
    else:
        doc.add( 'GCC.archs', '' )
        doc.add( 'GCC.sysroot', '' )
        doc.add( 'GCC.minver', '' )

    if build.match( 'i?86-*' ):
        doc.add( 'LIBHB.GCC.D', 'ARCH_X86_32', append=True )
    elif build.match( 'x86_64-*' ):
        doc.add( 'LIBHB.GCC.D', 'ARCH_X86_64', append=True )

    if options.enable_asm and ( not Tools.yasm.fail or options.enable_local_yasm ):
        asm = ''
        if build.match( 'i?86-*' ):
            asm = 'x86'
            doc.add( 'LIBHB.GCC.D', 'HAVE_MMX', append=True )
            doc.add( 'LIBHB.YASM.D', 'ARCH_X86', append=True )
            if build.match( '*-*-darwin*' ):
                doc.add( 'LIBHB.YASM.f', 'macho32' )
            else:
                doc.add( 'LIBHB.YASM.f', 'elf32' )
            doc.add( 'LIBHB.YASM.m', 'x86' )
        elif build.match( 'x86_64-*' ):
            asm = 'x86'
            doc.add( 'LIBHB.GCC.D', 'HAVE_MMX ARCH_X86_64', append=True )
            if build.match( '*-*-darwin*' ):
                doc.add( 'LIBHB.YASM.D', 'ARCH_X86_64 PIC', append=True )
                doc.add( 'LIBHB.YASM.f', 'macho64' )
            else:
                doc.add( 'LIBHB.YASM.D', 'ARCH_X86_64', append=True )
                doc.add( 'LIBHB.YASM.f', 'elf64' )
            doc.add( 'LIBHB.YASM.m', 'amd64' )
        doc.update( 'FEATURE.asm', asm )

    ## add exports to make
    if len(exports):
        doc.addBlank()
        doc.addComment( 'overrides via VARIABLE=VALUE on command-line' )
        for nv in exports:
            doc.add( nv[0], nv[1] )

    doc.addMake( '' )
    doc.addMake( '## include custom definitions' )
    doc.addMake( '-include $(SRC/)custom.defs' )
    doc.addMake( '-include $(BUILD/)GNUmakefile.custom.defs' )

    doc.addMake( '' )
    doc.addMake( '## include rules' )
    doc.addMake( 'include $(SRC/)make/include/main.rules' )
    doc.addMake( '-include $(SRC/)custom.rules' )
    doc.addMake( '-include $(BUILD/)GNUmakefile.custom.rules' )

    ## chdir
    cfg.chdir()

    ## perform
    doc.write( 'make' )
    doc.write( 'm4' )
    if options.launch:
        Launcher( targets )

    cfg.record_log()

    if os.path.normpath( cfg.build_dir ) == os.curdir:
        nocd = True
    else:
        nocd = False

    stdout.write( '%s\n' % ('-' * 79) )
    if options.launch:
        stdout.write( 'Build is finished!\n' )
        if nocd:
            stdout.write( 'You may now examine the output.\n' )
        else:
            stdout.write( 'You may now cd into %s and examine the output.\n' % (cfg.build_dir) )
    else:
        stdout.write( 'Build is configured!\n' )
        if nocd:
            stdout.write( 'You may now run make (%s).\n' % (Tools.gmake.pathname) )
        else:
            stdout.write( 'You may now cd into %s and run make (%s).\n' % (cfg.build_dir,Tools.gmake.pathname) )

except AbortError, x:
    stderr.write( 'ERROR: %s\n' % (x) )
    try:
        cfg.record_log()
    except:
        pass        
    sys.exit( 1 )    

sys.exit( 0 )