summaryrefslogtreecommitdiffstats
path: root/src/tdedistutils.py
blob: f5e034cfbcec4c87b491852996dc4d5ccd0d783f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
#!/usr/bin/python
###########################################################################
# tdedistutils - description                                              #
# ------------------------------                                          #
# begin     : Thu Apr 21 2005                                             #
# copyright : (C) 2005 by Simon Edwards                                   #
# email     : simon@simonzone.com                                         #
#                                                                         #
###########################################################################
#                                                                         #
#   This program is free software; you can redistribute it and/or modify  #
#   it under the terms of the GNU Library General Public License as       #
#   published by the Free Software Foundation; either version 2 of the    #
#   License, or (at your option) any later version.                       #
#                                                                         #
###########################################################################

import distutils.core
from distutils.core import Extension
from distutils.cmd import Command
from distutils.dist import Distribution
from distutils.command.build import build
from distutils.command.install import install
from distutils.command.install_scripts import install_scripts
from distutils.command.install_data import install_data
from distutils.command.install_lib import install_lib
from distutils.util import change_root, convert_path
from distutils.spawn import find_executable,spawn
from distutils import sysconfig
from distutils import log
from distutils import file_util
from distutils import dir_util
from distutils.util import byte_compile
import qtuicompiler
import stat
import os,os.path,imp,glob
import sys
from types import StringType

INSTALL_LIST = 'install_log.txt'


###########################################################################
def setup(**arg_dict):

    if 'cmdclass' not in arg_dict:
        arg_dict['cmdclass'] = {}

    cmdclass = arg_dict['cmdclass']

    arg_dict.setdefault('data_files',[])

    kdecmdclass = {'install' : InstallKDE,
        'install_executable_links' : InstallExecutableLinks,
        'install_application_data' : InstallApplicationDataAndLinks,
        'build_messages' : BuildI18NMessages,
        'install_messages' : InstallI18NMessages,
        'update_messages' : UpdateI18NMessages,
        'checkpyqt' : CheckPyQt,
        'checkpytde' : CheckPyTDE,
        'uninstall' : Uninstall,
        'build' : BuildKDE,
        'build_kcm' : BuildKControlModule,
        'install_kcm' : InstallKControlModule,
        'build_html' : BuildDocbookHTML,
        'install_html' : InstallDocbookHTML,
        'install_lib' : InstallLibWithRoot,
        'build_tdeioslave' : BuildTdeioslave,
        'install_tdeioslave' : InstallTdeioslave}

    for key in kdecmdclass.iterkeys():
        cmdclass.setdefault(key,kdecmdclass[key])

    arg_dict.setdefault('distclass',KDEDistribution)

    apply(distutils.core.setup,[],arg_dict)

###########################################################################
class KDEDistribution(Distribution):
    def __init__(self,attrs=None):
        self.min_kde_version = None
        self.min_qt_version = None
        self.kcontrol_modules = None
        self.tdeioslaves = None
        self.executable_links = None
        self.docbooks = None
        self.application_data = None
        self.i18n = None
        Distribution.__init__(self,attrs)

###########################################################################
def has_kcms(self):
    if self.distribution.kcontrol_modules is None:
        return 0
    return  len(self.distribution.kcontrol_modules)!=0

def has_docbook_html(self):
    if self.distribution.docbooks is None:
        return 0
    return  len(self.distribution.docbooks)!=0

def has_messages(self):
    if self.distribution.i18n is None:
        return 0
    return  len(self.distribution.i18n)!=0

def has_application_data(self):
    if self.distribution.application_data is None:
        return 0
    return  len(self.distribution.application_data)!=0

def has_tdeioslaves(self):
    if self.distribution.tdeioslaves is None:
        return 0
    return  len(self.distribution.tdeioslaves)!=0

###########################################################################
# Our slightly extended build command. This also does kcontrol modules.
class BuildKDE(build):

    user_options = build.user_options[:]
    user_options.append( ('msgfmt-exe=',None,'Path to the msgfmt executable') )
    user_options.append( ('meinproc-exe=',None,'Path to the meinproc executable') )

    sub_commands = build.sub_commands[:]
    sub_commands.append( ('build_kcm',has_kcms) )
    sub_commands.append( ('build_tdeioslave',has_tdeioslaves) )
    sub_commands.append( ('build_html',has_docbook_html) )
    sub_commands.append( ('build_messages',has_messages) )

    def __init__(self,dist):
        build.__init__(self,dist)
        self.has_kcms = has_kcms
        self.has_tdeioslaves = has_tdeioslaves
        self.has_docbook_html = has_docbook_html
        self.has_messages = has_messages

    def initialize_options(self):
        self.msgfmt_exe = None
        self.meinproc_exe = None
        build.initialize_options(self)

    def finalize_options(self):
        build.finalize_options(self)

        if self.msgfmt_exe is None:
            # Find msgfmt
            canidatepaths = []
            canidatepaths.append( ask_kde_config('--install exe --expandvars').strip() )
            self.msgfmt_exe = FindExeOnPath('msgfmt',canidatepaths)
            if self.msgfmt_exe is None:
                raise SystemExit, "Unable to find 'msgfmt', needed to build i18n messages."

        if self.meinproc_exe is None:
            # Find meinproc
            canidatepaths = []
            canidatepaths.append( ask_kde_config('--install exe --expandvars').strip() )
            self.meinproc_exe = FindExeOnPath('meinproc',canidatepaths)
            if self.meinproc_exe is None:
                raise SystemExit, "Unable to find 'meinproc', needed to generate Docbook HTML documentation."

###########################################################################
def has_executable_links(self):
    if self.distribution.executable_links is None:
        return 0
    return  len(self.distribution.executable_links)!=0

###########################################################################
class InstallKDE(install):
    user_options = install.user_options[:]
    user_options.append( ('kde-prefix=',None,"TDE installation prefix") )
    user_options.append( ('install-messages=',None,"installation directory for i18n message files") )
    user_options.append( ('install-html=',None,"installation directory for Docbook HTML files") )
    user_options.append( ('install-cmd=',None,"Command to use to install the files") )
    user_options.append( ('install-xdg-apps=',None,"directory for XDG app files") )
    user_options.append( ('install-kcm=',None,"directory for kcm library files") )
    user_options.append( ('install-tdeioslave',None,"directory for tdeioslave library files") )
    user_options.append( ('install-protocol',None,"directory for tdeioslave protocol files") )

    sub_commands = install.sub_commands[:]
    sub_commands.insert(0, ('checkpytde',None) )
    sub_commands.insert(0, ('checkpyqt',None) )
    sub_commands.append( ('install_executable_links',has_executable_links) )
    sub_commands.append( ('install_messages',has_messages) )
    sub_commands.append( ('install_html',has_docbook_html) )
    sub_commands.append( ('install_kcm',has_kcms) )
    sub_commands.append( ('install_tdeioslave',has_tdeioslaves) )
    sub_commands.append( ('install_application_data',has_application_data) )

    def initialize_options(self):
        self.kde_prefix = None
        self.install_messages = None
        self.install_html = None
        self.install_cmd = None
        self.install_xdg_apps = None
        self.install_kcm = None
        self.install_tdeioslave = None
        self.install_protocol = None
        self.install_application_data = None
        install.initialize_options(self)

    def finalize_options(self):
        # If no install prefix was provided, then we try to detect the KDE install prefix.
        self.user_supplied_kde_prefix = True

        if self.install_scripts is None:
            if self.kde_prefix is not None:
                self.install_scripts = os.path.join(self.kde_prefix,'bin')
            else:
                self.announce("Detecting TDE 'bin' directory...")
                self.install_scripts = ask_kde_config('--install exe --expandvars').strip()
                self.announce("   ...TDE 'bin' directory is %s" % self.install_scripts)

        if self.install_application_data is None:
            if self.kde_prefix is not None:
                self.install_application_data = os.path.join(self.kde_prefix,'share/apps',self.distribution.metadata.name)
            else:
                self.announce("Detecting TDE application directory...")
                kdeappdir = ask_kde_config('--install data --expandvars').strip()
                self.announce("  ...TDE application directory is %s" % self.install_application_data)
                self.install_application_data = os.path.join(kdeappdir,self.distribution.metadata.name)

        if self.install_messages is None:
            if self.kde_prefix is not None:
                self.install_messages = os.path.join(self.kde_prefix,'share/locale')
            else:
                self.announce("Detecting TDE messages directory...")
                self.install_messages = ask_kde_config('--install locale --expandvars').strip()
                self.announce("  ...TDE messages directory is %s" % self.install_messages)

        if self.install_html is None:
            if self.kde_prefix is not None:
                self.install_html = os.path.join(self.kde_prefix,'share/doc/tde/HTML')
            else:
                self.announce("Detecting TDE HTML directory...")
                self.install_html = ask_kde_config('--install html --expandvars').strip()
                self.announce("  ...TDE HTML directory is %s" % self.install_html)

        if self.kde_prefix is None:
            self.announce("Detecting TDE install prefix...")
            self.kde_prefix = ask_kde_config('--prefix').strip()
            self.announce("  ...TDE install prefix is %s" % self.kde_prefix)
            self.user_supplied_kde_prefix = False

        if self.install_cmd is None:
            self.announce("Detecting 'install' command...")
            # Ok, time to find the install command.
            self.install_cmd = find_executable('install')
            if self.install_cmd is None:
                raise SystemExit, "Unable to find the 'install' command, needed to install libraries."
            self.announce("  ...'install' command is %s" % self.install_cmd)

        if self.install_xdg_apps is None:
            self.announce("Detecting XDG apps directory...")
            self.install_xdg_apps = ask_kde_config('--install xdgdata-apps --expandvars').strip()
            self.announce("  ...XDG apps directory is %s" % self.install_xdg_apps)

        if self.install_kcm is None:
            self.announce("Detecting kcm library directory...")
            self.install_kcm = ask_kde_config('--install module --expandvars').strip()
            self.announce("  ...kcm library directory is %s" % self.install_kcm)

        if self.install_tdeioslave is None:
            self.announce("Detecting tdeioslave library directory...")
            self.install_tdeioslave = ask_kde_config('--install module --expandvars').strip()
            self.announce("  ...tdeioslave library directory is %s" % self.install_tdeioslave)

        if self.install_protocol is None:
            self.announce("Detecting tdeioslave protocol directory...")
            self.install_protocol = ask_kde_config('--install services --expandvars').strip()
            self.announce("  ...tdeioslave protocol directory is %s" % self.install_protocol)

        install.finalize_options(self)

        if self.root is not None:
            self.change_roots('application_data','html','messages','xdg_apps','kcm')

    def get_command_name(self):
        return 'install'

    def run(self):
        global INSTALL_LIST
        install.run(self)

        # Write out the uninstall list.
        fhandle = open(INSTALL_LIST,'w')
        for item in self.get_outputs():
            fhandle.write(item)
            fhandle.write('\n')
        fhandle.close()

###########################################################################
class InstallApplicationDataAndLinks(install_data):
    def get_command_name(self):
        return 'install_application_data'

    def initialize_options(self):
        install_data.initialize_options(self)

        self.data_files = self.distribution.application_data

    def finalize_options(self):
        self.set_undefined_options('install',
                                   ('install_application_data', 'install_dir'),
                                   ('root', 'root'),
                                   ('force', 'force'),
                                  )

    def run(self):
        self.outfiles.extend(self.mkpath(self.install_dir))
        for f in self.data_files:
            if type(f) is StringType:
                # it's a simple file, so copy it
                f = convert_path(f)
                if self.warn_dir:
                    self.warn("setup script did not provide a directory for "
                              "'%s' -- installing right in '%s'" %
                              (f, self.install_dir))
                if os.path.isfile(f):
                    (out, _) = self.copy_file(f, self.install_dir)
                    self.outfiles.append(out)
                elif os.path.isdir(f):
                    out = self.copy_tree(f,os.path.join(self.install_dir,f))
                    self.outfiles.extend(out)
                else:
                    self.warn("Setup script can't find file or directory %s needed for installation." % f)
            else:
                # it's a tuple with path to install to and a list of files
                dir = convert_path(f[0])
                if not os.path.isabs(dir):
                    dir = change_root(self.install_dir, dir)
                elif self.root:
                    dir = change_root(self.root, dir)
                self.outfiles.extend(self.mkpath(dir))

                if f[1] == []:
                    # If there are no files listed, the user must be
                    # trying to create an empty directory, so add the
                    # directory to the list of output files.
                    self.outfiles.append(dir)
                else:
                    # Copy files, adding them to the list of output files.
                    for data in f[1]:
                        data = convert_path(data)
                        if os.path.islink(data):
                            # Transplant the link to the new location without changing
                            # where it points to. (ie it is _not_ relocated).
                            dest = os.path.join(dir, os.path.basename(data))
                            if os.path.exists(dest):
                                os.remove(dest)
                            os.symlink(os.readlink(data),dest)
                            log.info("moving link %s -> %s" % (data,dest) )
                            #os.chmod(dest, os.stat(data)[stat.ST_MODE])
                        elif os.path.isdir(data):
                            out = self.copy_tree(data,dir)
                            self.outfiles.extend(out)
                        else:
                            (out, _) = self.copy_file(data, dir)
                            self.outfiles.append(out)

        # Compile the .ui files
        install_cmd = self.get_finalized_command('install')
        prefix = self.install_dir
        if prefix[-1] != os.sep:
            prefix = prefix + os.sep
        self.outfiles.extend(compile_tqtdesigner(self.outfiles, force=1, prefix=prefix, base_dir=install_cmd.prefix, dry_run=self.dry_run))

        # Byte compile the .py files
        from distutils.util import byte_compile
        byte_compile(self.outfiles, optimize=0, force=1, prefix=prefix, base_dir=install_cmd.prefix, dry_run=self.dry_run)

        # Add the .pyc files to the list of outfiles.
        self.outfiles.extend( [item+'c' for item in self.outfiles if item.endswith('.py')] )

    def mkpath(self, name, mode=0777):
        return dir_util.mkpath(name, mode, dry_run=self.dry_run)

###########################################################################
class InstallExecutableLinks(Command):
    description = "Install symlinks"

    user_options = []

    def initialize_options(self):
        self.outfiles = []

    def finalize_options(self):
        pass

    def get_command_name(self):
        return 'install_executable_links'

    def run(self):
        # FIXME add cmd options?
        install_script_cmd = self.get_finalized_command('install_scripts')
        install_data_cmd = self.get_finalized_command('install_application_data')

        destination_dir = install_data_cmd.install_dir

        if not os.path.exists(install_script_cmd.install_dir):
            self.outfiles.extend(self.mkpath(install_script_cmd.install_dir))

        if self.distribution.executable_links is not None:
            for link in self.distribution.executable_links:
                symname = os.path.join(install_script_cmd.install_dir,link[0])
                target = os.path.join(destination_dir,link[1])
                log.info("symlinking %s -> %s", symname, target)
                if not self.dry_run:
                    if os.path.islink(symname):
                        os.remove(symname)
                    os.symlink(target,symname)
                self.outfiles.append(symname)

    def get_outputs(self):
        return self.outfiles or []

    def mkpath(self, name, mode=0777):
        return dir_util.mkpath(name, mode, dry_run=self.dry_run)

###########################################################################
# Fix the --root option for the install_lib command.
class InstallLibWithRoot(install_lib):
    user_options = install_lib.user_options[:]
    user_options.append( ('root=',None,"install everything relative to this alternate root directory") )

    def initialize_options(self):
        install_lib.initialize_options(self)
        self.root = None

    def finalize_options(self):
        own_install_dir = self.install_dir is not None

        install_lib.finalize_options(self)
        self.set_undefined_options('install', ('root', 'root'))

        if self.root is not None and own_install_dir:
            self.install_dir = change_root(self.root, self.install_dir)

###########################################################################
class Uninstall(Command):
    description = "Remove all installed files"

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def get_command_name(self):
        return 'uninstall'

    def run(self):
        global INSTALL_LIST

        if not os.path.isfile(INSTALL_LIST):
            self.announce("Unable to uninstall, can't find the file list %s." % INSTALL_LIST)
            return

        # Suck in the file list.
        fhandle = open(INSTALL_LIST,'r')
        file_list = fhandle.readlines()
        fhandle.close()

        # Remove the files first.
        for item in file_list:
            item = item.strip()
            if os.path.isfile(item) or os.path.islink(item):
                self.announce("removing '%s'" % item)
                if not self.dry_run:
                    try:
                        os.remove(item)
                    except OSError, details:
                        self.warn("Could not remove file: %s" % details)
            elif not os.path.isdir(item):
                self.announce("skipping removal of '%s' (does not exist)" % item)

        # Remove the directories.
        file_list.sort()
        file_list.reverse()
        # Starting with the longest paths first.
        for item in file_list:
            item = item.strip()
            if os.path.isdir(item):
                self.announce("removing '%s'" % item)
                if not self.dry_run:
                    try:
                        os.rmdir(item)
                    except OSError, details:
                        self.warn("Could not remove directory: %s" % details)

###########################################################################
class BuildKControlModule(Command):
    description = "Build KControl extensions"

    user_options = [('no-kcontrol',None,"Don't build kcontrol extensions"),
                    ('build-dir=','b', "build directory (where to install from)"),
                    ('python-dir=',None,'Directory containing the Python installation'),
                    ('python-inc-dir=',None,'Directory containing C Header files for Python'),
                    ('kde-inc-dir=',None,'Directory containing C++ header files for KDE'),
                    ('kde-lib-dir=',None,'Directory containing library files for KDE'),
                    ('kde-kcm-lib-dir=',None,'Directory for KDE kcm library files'),
                    ('qt-inc-dir=',None,'Directory containing C++ header files for Qt'),
                    ('qt-lib-dir=',None,'Directory containing library files for Qt'),
                    ('sip-dir=',None,'Directory containing the sip library files'),
                    ('clib=',None,'gcc library and path'),
                    ('pyqt-dir=',None,'PyQt module directory'),
                    ('pytde-dir=',None,'PyTDE module directory'),
                    ('data-dir=',None,'installation directory for data (script) files')]

    def initialize_options(self):
        self.no_kcontrol = 0
        self.build_dir = None
        self.python_inc_dir = None
        self.python_dir = None
        self.kde_inc_dir = None
        self.kde_lib_dir = None
        self.kde_kcm_lib_dir = None
        self.qt_inc_dir = None
        self.qt_lib_dir = None
        self.sip_dir = None
        self.clib = None
        self.pyqt_dir = None
        self.pytde_dir = None
        self.data_dir = None

    def finalize_options(self):
        if self.no_kcontrol==0:
            self.set_undefined_options('install', ('build_base', 'build_dir'),('install_application_data','data_dir'))

            install = self.get_finalized_command('install')
            self.install_prefix = ask_kde_config('--prefix').strip()

            # KDE inc dir: find it!
            if self.kde_inc_dir is None:
                canidatepaths = []
                tdedir = os.getenv("TDEDIR")
                if tdedir!=None:
                    canidatepaths.append(os.path.join(tdedir,"include"))
                canidatepaths.append(os.path.join(install.prefix,"include"))
                canidatepaths.append(os.path.join(self.install_prefix,'include'))
                canidatepaths.append(os.path.join(self.install_prefix,'include','tde'))
                self.kde_inc_dir = FindFileInPaths('tdeapplication.h',canidatepaths)
            if self.kde_inc_dir is None:
                raise SystemExit, "Failed to find the KDE header file directory."
            if FindFileInPaths('tdeapplication.h',[self.kde_inc_dir]) is None:
                raise SystemExit, "Failed to find KDE header files in: %s" % self.kde_inc_dir
            self.announce("Using %s for KDE header files" % self.kde_inc_dir)

            # KDE lib dir
            if self.kde_lib_dir is None:
                self.kde_lib_dir = os.path.join(self.install_prefix,"lib")
            self.announce("Using %s for KDE library files" % self.kde_lib_dir)

            # KDE KCM lib dir
            if self.kde_kcm_lib_dir is None:
                self.kde_kcm_lib_dir = os.path.join(self.kde_lib_dir,"trinity")
            if FindFileInPaths('*kcm*.so',[self.kde_kcm_lib_dir]) is None:
                raise SystemExit, "Failed to find KDE KCM files in: %s" % self.kde_kcm_lib_dir
            self.announce("Using %s for KDE KCM library files" % self.kde_kcm_lib_dir)

            # Qt inc dir
            if self.qt_inc_dir is None:
                canidatepaths = []
                qtinc = os.getenv("QTINC")
                if qtinc != None:
                    canidatepaths.append(qtinc)
                qtdir = os.getenv("TQTDIR")
                if qtdir != None:
                    canidatepaths.append(os.path.join(qtdir,"include"))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/include"))
                canidatepaths.append(os.path.join(install.prefix,"lib/qt3/include"))
                canidatepaths.append(os.path.join(install.prefix,"include"))
                canidatepaths.append("/opt/tqt3/include")
                canidatepaths.append("/opt/qt/include")
                canidatepaths.append("/opt/qt/lib/include")
                canidatepaths.append("/opt/qt3/lib/include")
		canidatepaths.append("/usr/include/tqt3")
		canidatepaths.append("/usr/include/qt3")
                self.qt_inc_dir = FindFileInPaths('ntqstring.h',canidatepaths)
            if self.qt_inc_dir is None:
                self.qt_inc_dir = FindFileInPaths('qstring.h',canidatepaths)
            if self.qt_inc_dir is None:
                raise SystemExit,"Failed to find the Qt header file directory"
            if FindFileInPaths('ntqstring.h',[self.qt_inc_dir]) is None:
                if FindFileInPaths('qstring.h',[self.qt_inc_dir]) is None:
                    raise SystemExit, "Failed to find Qt header files in: %s" % self.qt_inc_dir
            self.announce("Using %s for Qt header files" % self.qt_inc_dir)

            # Qt lib dir
            if self.qt_lib_dir is None:
                canidatepaths = []
                tqtlib = os.getenv("TQTLIB")
                if tqtlib != None:
                    canidatepaths.append(tqtlib)
                qtdir = os.getenv("TQTDIR")
                if qtdir != None:
                    canidatepaths.append(os.path.join(qtdir,get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,get_libdir_name()))
                canidatepaths.append("/opt/tqt3/"+get_libdir_name())
                canidatepaths.append("/opt/tqt/"+get_libdir_name())
                canidatepaths.append("/opt/tqt/lib/"+get_libdir_name())
                canidatepaths.append("/opt/tqt3/lib/"+get_libdir_name())
                self.qt_lib_dir = FindFileInPaths('libtqt*',canidatepaths)
            if self.qt_lib_dir is None:
                canidatepaths = []
                tqtlib = os.getenv("TQTLIB")
                if tqtlib != None:
                    canidatepaths.append(tqtlib)
                qtdir = os.getenv("TQTDIR")
                if qtdir != None:
                    canidatepaths.append(os.path.join(qtdir,get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/qt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,get_libdir_name()))
                canidatepaths.append("/opt/tqt3/"+get_libdir_name())
                canidatepaths.append("/opt/qt/"+get_libdir_name())
                canidatepaths.append("/opt/qt/lib/"+get_libdir_name())
                canidatepaths.append("/opt/qt3/lib/"+get_libdir_name())
                self.qt_lib_dir = FindFileInPaths('libtqt*',canidatepaths)
            if self.qt_lib_dir is None:
                raise SystemExit, "Failed to find Qt library files"
            self.announce("Using %s for Qt library files" % self.qt_lib_dir)

            # Python dir
            if self.python_dir is None:
                self.python_dir = os.path.split(sysconfig.get_config_var("LIBP"))[0]
            self.announce("Using %s for the python directory" % self.python_dir)

            # Python include dir.
            if self.python_inc_dir is None:
                # Find the Python include directory.
                self.python_inc_dir = sysconfig.get_config_var("INCLUDEPY")
            self.announce("Using %s for Python header files" % self.python_inc_dir)

            # PyQt dir
            if self.pyqt_dir is None:
                self.pyqt_dir = FindFileInPaths("python_tqt", sys.path)
            if self.pyqt_dir is None:
                self.pyqt_dir = os.path.join(sysconfig.get_python_lib(), 'python_tqt')
            if (FindFileInPaths("libtqtcmodule*",[self.pyqt_dir]) is None) and (FindFileInPaths("qt*",[self.pyqt_dir]) is None):
                raise SystemExit, "Failed to find the PyQt directory: %s" % self.pyqt_dir
            self.announce("Using %s for PyQt modules" % self.pyqt_dir)

            # PyTDE dir
            if self.pytde_dir is None:
                self.pytde_dir = sysconfig.get_python_lib()
            if (FindFileInPaths("libtdecorecmodule*",[self.pytde_dir]) is None) and (FindFileInPaths("tdecore*",[self.pytde_dir]) is None):
                raise SystemExit, "Failed to find the PyTDE directory: %s" % self.pytde_dir
            self.announce("Using %s for PyTDE modules" % self.pytde_dir)

            # Sip dir
            if self.sip_dir is None:
                self.sip_dir = os.path.dirname(FindFileInPaths("sip_tqt*", sys.path))
            if self.sip_dir is None:
                self.sip_dir = sysconfig.get_python_lib()
            if (FindFileInPaths("libsip_tqt*", [self.sip_dir]) is None) and (FindFileInPaths("sip_tqt*", [self.sip_dir]) is None):
                raise SystemExit, "Failed to find libsip files in directory: %s" % self.sip_dir
            self.announce("Using %s for libsip files" % self.sip_dir)

            # Find the C library (libgcc, libgcc_s or some other variation).
            if self.clib is None:
                canidatepaths = ["/usr/"+get_libdir_name(), "/usr/local/"+get_libdir_name(), "/usr/lib" ]
                self.clib = FindFileInPaths("libgcc*.so",canidatepaths)
                if self.clib!=None:
                    self.clib = glob.glob(os.path.join(self.clib,'libgcc*.so'))[0]
                else:
                    self.clib = FindFileInPaths("libgcc*.a",canidatepaths)
                    if self.clib!=None:
                        self.clib = glob.glob(os.path.join(self.clib,'libgcc*.a'))[0]
            if self.clib is None:
                raise SystemExit, "tdedistutils.py (1): Failed to find a suitable libgcc library"
            self.announce("Using %s for clib" % self.clib)

            # Make a list of places to look for python .so modules
            self.python_sub_dirs = sysconfig.get_config_var("LIBSUBDIRS").split()
            base = sysconfig.get_config_var("LIBP")
            self.python_sub_dirs = [ os.path.join(base,item) for item in self.python_sub_dirs ]
            self.python_sub_dirs.append(base)

    def get_command_name(self):
        return 'build_kcm'

    def run(self):
        if self.no_kcontrol:
            self.announce("Skipping KControl modules")
            return

        if not os.path.isdir(self.build_dir):
            os.mkdir(self.build_dir)

        for moduletuple in self.distribution.kcontrol_modules:
            self.announce("Building KControl module from desktop file %s." % moduletuple[0])

            # Read the desktop file
            factoryfunction = None
            libraryname = None
            cmodulecategory = None
            try:
                fhandle = open(moduletuple[0],'r')
                for line in fhandle.readlines():
                    parts = line.strip().split('=')
                    try:
                        if parts[0]=="X-TDE-Library":
                            libraryname = parts[1]
                        elif parts[0]=="Exec":
                            shellcmd = parts[1].split()
                            modulepath = shellcmd[-1]
                            if '/' in modulepath:
                                cmodulecategory = os.path.dirname(modulepath)
                            else:
                                cmodulecategory = ""
                        elif parts[0]=="X-TDE-FactoryName":
                            factoryfunction = 'create_'+parts[1]
                    except IndexError:
                        pass
                fhandle.close()
            except IOError:
                raise SystemExit, "Failed to find kcontrol desktop file: %s" % moduletuple[0]

            # Sanity check.
            if factoryfunction is None:
                raise SystemExit, "Failed to find factory name (Was there a X-TDE-FactoryName entry in the desktop file?)"
            if libraryname is None:
                raise SystemExit, "Failed to find library name (Was there a X-TDE-Library entry in the desktop file?)"
            if cmodulecategory is None:
                raise SystemExit, "Failed to find the kcontrol category name (Was there a Exec entry in the desktop file?)"

            modulename = os.path.basename(moduletuple[1])
            if modulename.endswith('.py'):
                modulename = modulename[:-3]
            desktopfilename = moduletuple[0]

            stub_cpp_name = 'kcm_'+libraryname+'.cpp'
            stub_so_name = 'kcm_'+libraryname+'.so'
            stub_la_name = 'kcm_'+libraryname+'.la'
            python_version = '%i.%i' % (sys.version_info[0],sys.version_info[1])

            # Build the 'stub' code.
            cppcode = self.cpptemplate % {"moduledir": self.data_dir,
                                            "extramodule": os.getenv("EXTRA_MODULE_DIR"),
                                            "modulename": modulename,
                                            "factoryfunction": factoryfunction,
                                            "python_version": python_version}

            # Put it on disk.
            cppfile = os.path.join(os.path.dirname(moduletuple[0]),stub_cpp_name)
            try:
                fhandle = open(cppfile,'w')
                fhandle.write(cppcode)
                fhandle.close()
            except IOError:
                raise SystemExit, "Could not write the C++ stub: %s" % cppfile

            # Compile the stub library.
            cmdlist = ['libtool']

            # Couldn't get it to pass without this ...
            cmdlist.append("--mode=compile")
            cmdlist.append("--tag=CXX")

            # Find the compiler flags and options
            # CXX is empty on some Systems, let's do it 'the hard way'.
            # FIXME :: get CXX from make.conf for Gentoo.
            if len(sysconfig.get_config_var("CXX").split()) >= 2:
                cmdlist.extend(sysconfig.get_config_var("CXX").split())
            else:
                cmdlist.extend(['g++', '-pthread'])

            #cmdlist.extend(sysconfig.get_config_var("CXX").split())

            # cc_flags
            cmdlist.append("-c")
            cmdlist.append("-g")

            # The 4 is randomly chosen!
            # FIXME :: get CFLAGS from make.conf for Gentoo.
            if len(sysconfig.get_config_var("CFLAGS").split()) >=4:
                cmdlist.extend(sysconfig.get_config_var("CFLAGS").split())
            else:
                # On Gentoo systems, CFLAGS are not in the environment.
                raw = os.popen('emerge info 2> /dev/null|grep CFLAGS')
                lines = raw.readlines()
                if len(lines):
                    cflags = lines[0].split('"')[1].split()
                    print "Got CFLAGS from emerge info."
                    cmdlist.extend(cflags)
                else:
                    # Still no CFLAGS found, use these ...
                    cmdlist.extend(['-fno-strict-aliasing', '-DNDEBUG', '-g', '-O3', '-Wall', '-Wstrict-prototypes'])

            #sysconfig.get_config_var("CFLAGS").split()
            # includes
            cmdlist.append("-I" + sysconfig.get_config_var("INCLUDEDIR"))
            cmdlist.append("-I" + sysconfig.get_config_var("INCLUDEDIR"))
            cmdlist.append("-I" + sysconfig.get_config_var("INCLUDEPY"))
            cmdlist.append("-I" + self.python_inc_dir)
            cmdlist.append("-I" + self.kde_inc_dir)
            cmdlist.append("-I" + self.kde_inc_dir + "/tde")
            cmdlist.append("-I" + self.qt_inc_dir)
            cmdlist.append("-I/usr/include/tqt")
            cmdlist.append("-I.")
            # input
            cmdlist.append(cppfile)
            # output
            outputfile = os.path.join(self.build_dir,libraryname+'.lo')
            cmdlist.append("-o")
            cmdlist.append(outputfile)
            spawn(cmdlist) # Execute!!!
            print

            # Link the resulting object file to create a shared library.
            cmdlist = ['libtool']
            cmdlist.append("--mode=link")
            cmdlist.append("--tag=LD")

            # Grab the linker command name
            cmdlist.append(sysconfig.get_config_var("LDSHARED").split()[0])
            # link_flags
            cmdlist.append("-module")
            cmdlist.append("-avoid-version")
            cmdlist.append("-shared")
            cmdlist.append("-export-dynamic")
            # object
            cmdlist.append(outputfile)
            cmdlist.append("-rpath"); cmdlist.append(self.kde_kcm_lib_dir)
            cmdlist.append("-o"); cmdlist.append(os.path.join(self.build_dir,stub_la_name))
            # Link libs
            linklist = []
            linklist.append("-lpython%s" % python_version)
            linklist.extend(sysconfig.get_config_var("LIBS").split())

            # FIXME I doubt half of these libraries need to be here.
            linklist.append(self.sip_dir+"/sip_tqt.so")
            # PyQt libs
            linklist.append(self.pyqt_dir+"/qt.so")
            # PyTDE libs
            linklist.append(self.pytde_dir+"/tdecore.so")
            linklist.append(self.pytde_dir+"/tdeui.so")

#            linklist.append("-L"+self.sip_dir); linklist.append("-lsip_tqt")
#            # PyQt libs
#            linklist.append("-L"+self.pyqt_dir); linklist.append("-lqtcmodule")
#            # PyTDE libs
#            linklist.append("-L"+self.pytde_dir); linklist.append("-ltdecorecmodule"); linklist.append("-ltdeuicmodule")

            linklist.append("-L"+self.kde_lib_dir); linklist.append("-L/opt/trinity/lib"); linklist.append("-ltdecore"); linklist.append("-lpythonize")
            linklist.append("-L"+self.qt_lib_dir); linklist.append("-ltqt-mt")
            linklist.append("-lm")
            linklist.append("-lc")
            linklist.append(self.clib)

            linklist.append("-R"); linklist.append(self.python_dir)
            linklist.append("-R"); linklist.append(self.qt_lib_dir)
            linklist.append("-R"); linklist.append(self.sip_dir)
            linklist.append("-R"); linklist.append(self.pyqt_dir)
            linklist.append("-R"); linklist.append(self.pytde_dir)
            linklist.append("-R"); linklist.append(self.kde_lib_dir)

            cmdlist.extend(linklist)
            spawn(cmdlist) # Execute!!
            print

    cpptemplate = r"""
/*
 * pykcm_launcher.cpp
 *
 * Launch Control Centre modules written in Python using an embedded Python
 * interpreter.
 * Based on David Boddie's PyTDE-components.
 */

// pythonize.h must be included first.
#include <pythonize.h>
#include <tdecmodule.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <klibloader.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <tqstring.h>
#include <sip-tqt.h>

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif  // _GNU_SOURCE
#include <dlfcn.h>

#define MODULE_DIR "%(moduledir)s"
#define EXTRA_MODULE_DIR "%(extramodule)s"
#define MODULE_NAME "%(modulename)s"
#define FACTORY "%(factoryfunction)s"
#define CPP_FACTORY %(factoryfunction)s
#define debug 1

static TDECModule *report_error(const char *msg) {
    if (debug) printf ("error: %%s\n", msg);
    return NULL;
}

static TDECModule* return_instance( TQWidget *parent, const char *name ) {
    TDECModule* tdecmodule;
    PyObject *pyTDECModuleTuple;
    PyObject *pyTDECModule;
    Pythonize *pyize;  // Pythonize object to manage the Python interpreter.

    // Try to determine what py script we're loading. Note that "name"
    // typically appears to be NULL.
    TQString script(MODULE_NAME);

    // Reload this module, but this time tell the runtime linker to make the
    // symbols global and available for later loaded libraries/module.
    Dl_info info;
    if (!dladdr((const void *)(&return_instance), &info) || !info.dli_fname ||  !dlopen(info.dli_fname, RTLD_GLOBAL|RTLD_NOW)) {
        return report_error ("***Unable to export symbols\n");
    }

    // Start the interpreter.
    pyize = initialize();
    if (!pyize) {
        return report_error ("***Failed to start interpreter\n");
    }

    // Add the path to the python script to the interpreter search path.
    TQString path = TQString(MODULE_DIR);
    if(path == TQString::null) {
        return report_error ("***Failed to locate script path");
    }
    if(!pyize->appendToSysPath (path.latin1 ())) {
        return report_error ("***Failed to set sys.path\n");
    }

    // Add the extra path to the python script to the interpreter search path.
    TQString extrapath = TQString(EXTRA_MODULE_DIR);
    if(!pyize->appendToSysPath (extrapath.latin1 ())) {
      return report_error ("***Failed to set extra sys.path\n");
    }

    // Load the Python script.
    PyObject *pyModule = pyize->importModule ((char *)script.latin1 ());
    if(!pyModule) {
        PyErr_Print();
        return report_error ("***failed to import module\n");
    }

    // Inject a helper function
    TQString bridge = TQString("import sip_tqt\n"
                            "from python_tqt import qt\n"
                            "def kcontrol_bridge_" FACTORY "(parent,name):\n"
                             "    if parent!=0:\n"
                             "        wparent = sip_tqt.wrapinstance(parent,qt.TQWidget)\n"
                             "    else:\n"
                             "        wparent = None\n"
                             "    inst = " FACTORY "(wparent, name)\n"
                             "    return (inst,sip_tqt.unwrapinstance(inst))\n");
    PyRun_String(bridge.latin1(),Py_file_input,PyModule_GetDict(pyModule),PyModule_GetDict(pyModule));

    // Get the Python module's factory function.
    PyObject *kcmFactory = pyize->getNewObjectRef(pyModule, "kcontrol_bridge_" FACTORY);
    if(!kcmFactory) {
        return report_error ("***failed to find module factory\n");
    }

    // Call the factory function. Set up the args.
    PyObject *pyParent = PyLong_FromVoidPtr(parent);
    PyObject *pyName = PyString_FromString(MODULE_NAME);
        // Using NN here is effect gives our references to the arguement away.
    PyObject *args = Py_BuildValue ("NN", pyParent, pyName);
    if(pyName && pyParent && args) {
        // run the factory function
        pyTDECModuleTuple = pyize->runFunction(kcmFactory, args);
        if(!pyTDECModuleTuple) {
            PyErr_Print();
            return report_error ("*** runFunction failure\n;");
        }
    } else {
        return report_error ("***failed to create args\n");
    }
    // cleanup a bit
    pyize->decref(args);
    pyize->decref(kcmFactory);

    // Stop this from getting garbage collected.
    Py_INCREF(PyTuple_GET_ITEM(pyTDECModuleTuple,0));

    // convert the TDECModule PyObject to a real C++ TDECModule *.
    pyTDECModule = PyTuple_GET_ITEM(pyTDECModuleTuple,1);
    tdecmodule = (TDECModule *)PyLong_AsVoidPtr(pyTDECModule);
    if(!tdecmodule) {
        return report_error ("***failed sip-tqt conversion to C++ pointer\n");
    }
    pyize->decref(pyTDECModuleTuple);

    // PyTDE can't run the module without this - Pythonize
    // grabs the lock at initialization and we have to give
    // it back before exiting. At this point, we no longer need
    // it.
    //pyize->releaseLock ();

    // take care of any translation info
    TDEGlobal::locale()->insertCatalogue(script);

    // Return the pointer to our new TDECModule
    return tdecmodule;
}

extern "C" {
    // Factory function that kcontrol will call.
    TDECModule* CPP_FACTORY(TQWidget *parent, const char *name) {
        return return_instance(parent, name);
    }
}
"""

###########################################################################
class InstallKControlModule(Command):
    description = "Install Kcontrol module files"

    user_options = [
        ('install-dir=', 'd', "base directory for installing kcontrol module files"),
        ('install-cmd=', None, "Command to use to install the files"),
        ('xdg-apps-dir=',None,"directory for XDG app files"),
        ('build-dir=','b', "build directory (where to install from)"),
        ('root=', None, "install everything relative to this alternate root directory"),
        ('force', 'f', "force installation (overwrite existing files)"),
        ('skip-build', None, "skip the build steps"),
        ]
    boolean_options = ['force', 'skip-build']

    def initialize_options(self):
        self.build_dir = None
        self.install_dir = None
        self.install_cmd = None
        self.xdg_apps_dir = None
        self.outfiles = []
        self.root = None
        self.force = 0
        self.warn_dir = 1
        self.skip_build = None

    def finalize_options(self):
        own_install_dir = self.install_dir is not None
        own_xdg_apps_dir = self.xdg_apps_dir is not None

        self.set_undefined_options('install',
                                    ('build_base', 'build_dir'),
                                    ('install_kcm', 'install_dir'),
                                    ('install_xdg_apps','xdg_apps_dir'),
                                    ('root', 'root'),
                                    ('force', 'force'),
                                    ('skip_build', 'skip_build'),
                                    ('install_cmd', 'install_cmd')
                                    )

        if own_install_dir and self.root is not None:
            self.install_dir = change_root(self.root,self.installdir)
        if own_xdg_apps_dir and self.root is not None:
            self.xdg_apps_dir = change_root(self.root,self.xdg_apps_dir)

    def get_command_name(self):
        return 'install_kcm'

    def run(self):
        if not self.skip_build:
            self.run_command('build_kcm')

        self.announce("Installing Kcontrol module files...")

        for moduletuple in self.distribution.kcontrol_modules:
            self.announce("Building KControl module from desktop file %s." % moduletuple[0])

            # Read the desktop file
            libraryname = None
            cmodulecategory = None
            try:
                fhandle = open(moduletuple[0],'r')
                for line in fhandle.readlines():
                    parts = line.strip().split('=')
                    try:
                        if parts[0]=="X-TDE-Library":
                            libraryname = parts[1]
                        elif parts[0]=="Exec":
                            shellcmd = parts[1].split()
                            modulepath = shellcmd[-1]
                            if '/' in modulepath:
                                cmodulecategory = os.path.dirname(modulepath)
                            else:
                                cmodulecategory = ""
                    except IndexError:
                        pass
                fhandle.close()
            except IOError:
                raise SystemExit, "Failed to find kcontrol desktop file: %s" % moduletuple[0]

            if libraryname is None:
                raise SystemExit, "Failed to find library name (Was there a X-TDE-Library entry in the desktop file?)"
            if cmodulecategory is None:
                raise SystemExit, "Failed to find the kcontrol category name (Was there a Exec entry in the desktop file?)"

            desktopfilename = moduletuple[0]
            self.outfiles.extend(self.mkpath(self.xdg_apps_dir))
            desktopfile_dest = os.path.join(self.xdg_apps_dir,os.path.basename(desktopfilename))
            self.copy_file(desktopfilename, desktopfile_dest)

            stub_la_name = 'kcm_'+libraryname+'.la'

            self.outfiles.extend(self.mkpath(self.install_dir))

            # Install the library.
            cmdlist = ['libtool']
            cmdlist.append("--mode=install")
            cmdlist.append(self.install_cmd)
            cmdlist.append("-c")
            cmdlist.append(os.path.join(self.build_dir,stub_la_name))
            cmdlist.append(os.path.join(self.install_dir,stub_la_name))
            spawn(cmdlist) # Execute!!
            print

            self.outfiles = [os.path.join(self.install_dir,os.path.basename(file)) for file in glob.glob(os.path.join(self.build_dir,'.libs','kcm_'+libraryname+'*'))]
            self.outfiles.append(desktopfile_dest)

        self.announce("Done installing Kcontrol module files.")

    def get_outputs(self):
        return self.outfiles or []

    def mkpath(self, name, mode=0777):
        return dir_util.mkpath(name, mode, dry_run=self.dry_run)

###########################################################################
class BuildDocbookHTML(Command):
    description = "Build Docbook HTML documentation"

    user_options = [('meinproc-exe=',None,"Path to the meinproc executable")]

    def initialize_options(self):
        self.html_prefix = None
        self.meinproc_exe = None

    def finalize_options(self):
        self.set_undefined_options('build', ('meinproc_exe', 'meinproc_exe') )

    def get_command_name(self):
        return 'build_docbook'

    def run(self):
        for docbook_tuple in self.distribution.docbooks:
            input_dir = docbook_tuple[0]
            language_code = docbook_tuple[1]

            self.announce("Building Docbook documentation from directory %s." % input_dir)

            indexdoc_file_name = os.path.join(input_dir,'index.docbook')
            if not os.path.exists(indexdoc_file_name):
                raise SystemExit, "File %s is missing." % indexdoc_file_name

            cwd = os.getcwd()
            os.chdir(input_dir)
            try:
                spawn([self.meinproc_exe,"--check","--cache",'index.cache.bz2', 'index.docbook'])
                spawn([self.meinproc_exe, 'index.docbook'])
            finally:
                os.chdir(cwd)

###########################################################################
class InstallDocbookHTML(Command):
    description = "Install Docbook HTML files"

    user_options = [
        ('install-dir=', 'd',"base directory for installing docbook HTML files"),
        ('root=', None, "install everything relative to this alternate root directory"),
        ('force', 'f', "force installation (overwrite existing files)"),
        ('skip-build', None, "skip the build steps"),
        ]
    boolean_options = ['force', 'skip-build']

    def initialize_options(self):
        self.install_dir = None
        self.outfiles = []
        self.root = None
        self.force = 0
        self.warn_dir = 1
        self.skip_build = None

    def finalize_options(self):
        own_install_dir = self.install_dir is not None

        self.set_undefined_options('install',
                                   ('install_html', 'install_dir'),
                                   ('root', 'root'),
                                   ('force', 'force'),
                                   ('skip_build', 'skip_build'),
                                  )

        if own_install_dir and self.root is not None:
            self.install_dir = change_root(self.root,self.installdir)

    def get_command_name(self):
        return 'install_html'

    def run(self):
        if not self.skip_build:
            self.run_command('build_html')

        self.announce("Installing HTML files...")
        counter = 0
        for docbook_tuple in self.distribution.docbooks:
            input_dir = docbook_tuple[0]
            language_code = docbook_tuple[1]

            self.announce("Install Docbook documentation from directory %s." % input_dir)
            source_file = os.path.join(input_dir,'index.cache.bz2')
            if not os.path.exists(source_file):
                raise SystemExit, "File %s is missing." % source_file

            dest_path = os.path.join(self.install_dir, language_code, self.distribution.metadata.name)
            self.outfiles.extend(self.mkpath(dest_path))
            dest_file = os.path.join(dest_path,'index.cache.bz2')

            self.copy_file(source_file, dest_file)
            self.outfiles.append(dest_file)
            counter += 1

            # Also install any lose HTML files.
            for source_file in glob.glob(os.path.join(input_dir,'*.html')):
                htmlfile = os.path.basename(source_file)
                dest_file = os.path.join(dest_path,htmlfile)
                self.copy_file(source_file, dest_file)
                self.outfiles.append(dest_file)
                counter += 1

            if len(docbook_tuple)==3:
                extra_files = docbook_tuple[2]
                for file in extra_files:
                    source_file = os.path.join(input_dir,file)
                    dest_file = os.path.join(self.install_dir, language_code, self.distribution.metadata.name,file)
                    self.copy_file(source_file, dest_file)
                    self.outfiles.append(dest_file)
                    counter += 1

        self.announce("Done installing %i HTML files." % counter)

    def get_outputs(self):
        return self.outfiles or []

    def mkpath(self, name, mode=0777):
        return dir_util.mkpath(name, mode, dry_run=self.dry_run)

###########################################################################
class UpdateI18NMessages(Command):
    description = "Extract and update messages for translation"

    user_options = [('xgettext-exe=',None,'Full path to the xgetext executable'),\
                    ('kde-pot=',None,'Location of the the KDE pot file'),\
                    ('msgmerge-exe=',None,'Full path to the msgmerge executable')]

    def initialize_options(self):
        self.xgettext_exe = None
        self.msgmerge_exe = None
        self.kde_pot = None

    def finalize_options(self):
        if self.xgettext_exe is None:
            install = self.get_finalized_command('install')

            canidate_paths = []
            if install.user_supplied_kde_prefix:
                canidate_paths.append(os.path.join(install.kde_prefix,'bin'))

            self.announce("Detecting xgettext...")
            canidate_paths.append(ask_kde_config('--install exe --expandvars').strip())
            self.xgettext_exe = FindExeOnPath('xgettext',canidate_paths)
            if self.xgettext_exe is None:
                raise SystemExit, "Unable to find 'xgettext'."
            self.announce("  ...xgettext found at %s" % self.xgettext_exe)

        if self.msgmerge_exe is None:
            install = self.get_finalized_command('install')

            canidate_paths = []
            if install.user_supplied_kde_prefix:
                canidate_paths.append(os.path.join(install.kde_prefix,'bin'))

            self.announce("Detecting msgmerge...")
            canidate_paths.append(ask_kde_config('--install exe --expandvars').strip())
            self.msgmerge_exe = FindExeOnPath('msgmerge',canidate_paths)
            if self.msgmerge_exe is None:
                raise SystemExit, "Unable to find 'xgettext'."
            self.announce("  ...msgmerge found at %s" % self.msgmerge_exe)

        if self.kde_pot is None:
            self.announce("Detecting kde.pot...")
            canidatepaths = []
            tdedir = os.getenv("TDEDIR")
            if tdedir!=None:
                canidatepaths.append(os.path.join(tdedir,"include"))
            install = self.get_finalized_command('install')
            canidatepaths.append(os.path.join(install.kde_prefix,"include"))
            canidatepaths.append('/opt/trinity/include')
            canidatepaths.append('/opt/kde/include')
            kde_pot_dir = FindFileInPaths('kde.pot',canidatepaths)

            if kde_pot_dir is None:
                raise SystemExit, "Failed to find the kde.pot file."

            self.kde_pot = os.path.join(kde_pot_dir,'kde.pot')
            self.announce("   ...kde.pot found at %s" % self.kde_pot)

    def get_command_name(self):
        return 'update_messages'

    def run(self):
        if self.distribution.i18n is None: return

        self.announce("Extracting and merging i18n messages...")
        po_dir = self.distribution.i18n[0]

        # FIXME : .rc and .ui files
        input_files = []

        # Compile any UI files
        for dir in self.distribution.i18n[1]:
            for file in glob.glob(os.path.join(dir,'*.ui')):
                qtuicompiler.UpdateUI(file,kde=True)

        # Fetch all of the python files.
        for dir in self.distribution.i18n[1]:
            input_files.extend(glob.glob(os.path.join(dir,'*.py')))

        target_pot = os.path.join(po_dir,self.distribution.metadata.name+".pot")

        cmd = [self.xgettext_exe, '-o', target_pot, '-ki18n', '-ktr2i18n', \
                '-kI18N_NOOP', '-ktranslate', '-kaliasLocale','-x',self.kde_pot]
        cmd.extend(input_files)
        spawn(cmd)

        for po_file in glob.glob(os.path.join(po_dir,'*.po')):
            temp_po = po_file + '.temp'
            cmd = [self.msgmerge_exe,'-q','-o',temp_po,po_file,target_pot]
            spawn(cmd)
            os.rename(temp_po,po_file)

        self.announce("Finished with i18n messages.")

###########################################################################
class BuildI18NMessages(Command):
    description = "Build i18n messages"

    user_options = [('msgfmt-exe=',None,'Path to the msgfmt executable')]

    def initialize_options(self):
        self.msgfmt_exe = None

    def finalize_options(self):
        self.set_undefined_options('build', ('msgfmt_exe', 'msgfmt_exe'))

    def get_command_name(self):
        return 'build_messages'

    def run(self):
        if self.distribution.i18n is None: return

        self.announce("Building i18n messages...")
        po_dir = self.distribution.i18n[0]

        i = 0
        for po_file in [file for file in os.listdir(po_dir) if file.endswith('.po')]:
            source = os.path.join(po_dir,po_file)
            target = source[:-3]+'.gmo'
            cmd = [self.msgfmt_exe,'-o',target, source]
            spawn(cmd)
            i += 1
        self.announce("Done building %i i18n messages." % i)

###########################################################################
class InstallI18NMessages(Command):
    description = "Install messages"

    user_options = [
        ('install-dir=', 'd',"base directory for installing message files (default: installation base dir)"),
        ('root=', None, "install everything relative to this alternate root directory"),
        ('force', 'f', "force installation (overwrite existing files)"),
        ('skip-build', None, "skip the build steps"),
        ]

    boolean_options = ['force', 'skip-build']

    def initialize_options(self):
        self.install_dir = None
        self.outfiles = []
        self.root = None
        self.force = 0
        self.warn_dir = 1
        self.skip_build = None

    def finalize_options(self):
        own_install_dir = self.install_dir is not None

        self.set_undefined_options('install',
                                   ('install_messages', 'install_dir'),
                                   ('root', 'root'),
                                   ('force', 'force'),
                                   ('skip_build', 'skip_build'),
                                  )

        if own_install_dir and self.root is not None:
            self.install_dir = change_root(self.root,self.installdir)

    def get_command_name(self):
        return 'install_messages'

    def run(self):
        if not self.skip_build:
            self.run_command('build_messages')

        self.announce("Installing i18n messages...")
        po_dir = self.distribution.i18n[0]

        counter = 0
        for po_file in os.listdir(po_dir):
            if po_file.endswith('.po'):
                source_file = os.path.join(po_dir,po_file[:-3]) + '.gmo'

                # Setup installation of the translation file.
                dest_path = os.path.join(self.install_dir, po_file[:-3],'LC_MESSAGES')
                self.outfiles.extend(self.mkpath(dest_path))
                dest_file = os.path.join(dest_path, self.distribution.metadata.name+'.mo')

                self.copy_file(source_file, dest_file)
                self.outfiles.append(dest_file)
                counter += 1
        self.announce("Done installing %i i18n messages." % counter)

    def get_outputs(self):
        return self.outfiles

    def mkpath(self, name, mode=0777):
        return dir_util.mkpath(name, mode, dry_run=self.dry_run)


###########################################################################
class BuildTdeioslave(Command):
    description = "Build Tdeioslaves"

    user_options = [('no-tdeioslave',None,"Don't build tdeioslaves"),
                    ('build-dir=','b', "build directory (where to install from)"),
                    ('python-dir=',None,'Directory containing the Python installation'),
                    ('python-inc-dir=',None,'Directory containing C Header files for Python'),
                    ('kde-inc-dir=',None,'Directory containing C++ header files for KDE'),
                    ('kde-lib-dir=',None,'Directory containing library files for KDE'),
                    ('kde-tdeioslave-lib-dir=',None,'Directory for KDE tdeioslave library files'),
                    ('kde-protocol-dir=',None,'Directory for KDE tdeioslave protocol files'),
                    ('qt-inc-dir=',None,'Directory containing C++ header files for Qt'),
                    ('qt-lib-dir=',None,'Directory containing library files for Qt'),
                    ('sip-dir=','/usr/lib/pyshared/python*','Directory containing the sip library files'),
                    ('clib=',None,'gcc library and path'),
                    ('pyqt-dir=','/usr/lib/pyshared/python*','PyQt module directory'),
                    ('pytde-dir=',None,'PyTDE module directory'),
                    ('data-dir=',None,'installation directory for data (script) files')]

    def initialize_options(self):
        self.no_tdeioslave = 0
        self.build_dir = None
        self.python_inc_dir = None
        self.python_dir = None
        self.kde_inc_dir = None
        self.kde_lib_dir = None
        self.kde_tdeioslave_lib_dir = None
        self.kde_protocol_dir = None
        self.qt_inc_dir = None
        self.qt_lib_dir = None
        self.sip_dir = None
        self.clib = None
        self.pyqt_dir = None
        self.pytde_dir = None
        self.data_dir = None

    def finalize_options(self):
        if self.no_tdeioslave==0:
            self.set_undefined_options('install', ('build_base', 'build_dir'),('install_application_data','data_dir'))

            install = self.get_finalized_command('install')
            self.install_prefix = ask_kde_config('--prefix').strip()

            # KDE inc dir: find it!
            if self.kde_inc_dir is None:
                canidatepaths = []
                tdedir = os.getenv("TDEDIR")
                if tdedir!=None:
                    canidatepaths.append(os.path.join(tdedir,"include"))
                canidatepaths.append(os.path.join(install.prefix,"include"))
                canidatepaths.append(os.path.join(self.install_prefix,'include'))
                canidatepaths.append(os.path.join(self.install_prefix,'include','tde'))
                self.kde_inc_dir = FindFileInPaths('tdeapplication.h',canidatepaths)
            if self.kde_inc_dir is None:
                raise SystemExit, "Failed to find the KDE header file directory."
            if FindFileInPaths('tdeapplication.h',[self.kde_inc_dir]) is None:
                raise SystemExit, "Failed to find KDE header files in: %s" % self.kde_inc_dir
            self.announce("Using %s for KDE header files" % self.kde_inc_dir)

            # KDE lib dir
            if self.kde_lib_dir is None:
                self.kde_lib_dir = os.path.join(self.install_prefix,"lib")
            self.announce("Using %s for KDE library files" % self.kde_lib_dir)

            # KDE tdeioslave lib dir
            if self.kde_tdeioslave_lib_dir is None:
                self.kde_tdeioslave_lib_dir = os.path.join(self.kde_lib_dir,"trinity")
            if FindFileInPaths('tdeio_*.so',[self.kde_tdeioslave_lib_dir]) is None:
                raise SystemExit, "Failed to find KDE Tdeioslave library files in: %s" % self.kde_tdeioslave_lib_dir
            self.announce("Using %s for KDE Tdeioslave library files" % self.kde_tdeioslave_lib_dir)

            # Qt inc dir
            if self.qt_inc_dir is None:
                canidatepaths = []
                qtinc = os.getenv("QTINC")
                if qtinc != None:
                    canidatepaths.append(qtinc)
                qtdir = os.getenv("TQTDIR")
                if qtdir != None:
                    canidatepaths.append(os.path.join(qtdir,"include"))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/include"))
                canidatepaths.append(os.path.join(install.prefix,"lib/qt3/include"))
                canidatepaths.append(os.path.join(install.prefix,"include"))
                canidatepaths.append("/opt/tqt3/include")
                canidatepaths.append("/opt/qt/include")
                canidatepaths.append("/opt/qt/lib/include")
                canidatepaths.append("/opt/qt3/lib/include")
                self.qt_inc_dir = FindFileInPaths('ntqstring.h',canidatepaths)
            if self.qt_inc_dir is None:
                self.qt_inc_dir = FindFileInPaths('qstring.h',canidatepaths)
            if self.qt_inc_dir is None:
                raise SystemExit,"Failed to find the Qt header file directory"
            if FindFileInPaths('ntqstring.h',[self.qt_inc_dir]) is None:
                if FindFileInPaths('qstring.h',[self.qt_inc_dir]) is None:
                    raise SystemExit, "Failed to find Qt header files in: %s" % self.qt_inc_dir
            self.announce("Using %s for Qt header files" % self.qt_inc_dir)

            # Qt lib dir
            if self.qt_lib_dir is None:
                canidatepaths = []
                tqtlib = os.getenv("TQTLIB")
                if tqtlib != None:
                    canidatepaths.append(tqtlib)
                qtdir = os.getenv("TQTDIR")
                if qtdir != None:
                    canidatepaths.append(os.path.join(qtdir,get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,get_libdir_name()))
                canidatepaths.append("/opt/tqt3/"+get_libdir_name())
                canidatepaths.append("/opt/tqt/"+get_libdir_name())
                canidatepaths.append("/opt/tqt/lib/"+get_libdir_name())
                canidatepaths.append("/opt/tqt3/lib/"+get_libdir_name())
                self.qt_lib_dir = FindFileInPaths('libtqt*',canidatepaths)
            if self.qt_lib_dir is None:
                canidatepaths = []
                tqtlib = os.getenv("TQTLIB")
                if tqtlib != None:
                    canidatepaths.append(tqtlib)
                qtdir = os.getenv("TQTDIR")
                if qtdir != None:
                    canidatepaths.append(os.path.join(qtdir,get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/tqt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,"lib/qt3/"+get_libdir_name()))
                canidatepaths.append(os.path.join(install.prefix,get_libdir_name()))
                canidatepaths.append("/opt/tqt3/"+get_libdir_name())
                canidatepaths.append("/opt/qt/"+get_libdir_name())
                canidatepaths.append("/opt/qt/lib/"+get_libdir_name())
                canidatepaths.append("/opt/qt3/lib/"+get_libdir_name())
                self.qt_lib_dir = FindFileInPaths('libtqt*',canidatepaths)
            if self.qt_lib_dir is None:
                raise SystemExit, "Failed to find Qt library files"
            self.announce("Using %s for Qt library files" % self.qt_lib_dir)

            # Python dir
            if self.python_dir is None:
                self.python_dir = os.path.split(sysconfig.get_config_var("LIBP"))[0]
            self.announce("Using %s for the python directory" % self.python_dir)

            # Python include dir.
            if self.python_inc_dir is None:
                # Find the Python include directory.
                self.python_inc_dir = sysconfig.get_config_var("INCLUDEPY")
            self.announce("Using %s for Python header files" % self.python_inc_dir)

            # PyQt dir
            if self.pyqt_dir is None:
                self.pyqt_dir = FindFileInPaths("python_tqt", sys.path)
            if self.pyqt_dir is None:
                self.pyqt_dir = os.path.join(sysconfig.get_python_lib(), 'python_tqt')
            if (FindFileInPaths("libtqtcmodule*",[self.pyqt_dir]) is None) and (FindFileInPaths("qt*",[self.pyqt_dir]) is None):
                raise SystemExit, "Failed to find the PyQt directory: %s" % self.pyqt_dir
            self.announce("Using %s for PyQt modules" % self.pyqt_dir)

            # PyTDE dir
            if self.pytde_dir is None:
                self.pytde_dir = sysconfig.get_python_lib()
            if (FindFileInPaths("libtdecorecmodule*",[self.pytde_dir]) is None) and (FindFileInPaths("tdecore*",[self.pytde_dir]) is None):
                raise SystemExit, "Failed to find the PyTDE directory: %s" % self.pytde_dir
            self.announce("Using %s for PyTDE modules" % self.pytde_dir)

            # Sip dir
            if self.sip_dir is None:
                self.sip_dir = os.path.dirname(FindFileInPaths("sip_tqt*", sys.path))
            if self.sip_dir is None:
                self.sip_dir = sysconfig.get_python_lib()
            if (FindFileInPaths("libsip_tqt*", [self.sip_dir]) is None) and (FindFileInPaths("sip_tqt*", [self.sip_dir]) is None):
                raise SystemExit, "Failed to find libsip files in directory: %s" % self.sip_dir
            self.announce("Using %s for libsip files" % self.sip_dir)

            # Find the C library (libgcc, libgcc_s or some other variation).
            if self.clib is None:
                canidatepaths = ["/usr/"+get_libdir_name(), "/usr/local/"+get_libdir_name() ]
                self.clib = FindFileInPaths("libgcc*.so",canidatepaths)
                if self.clib!=None:
                    self.clib = glob.glob(os.path.join(self.clib,'libgcc*.so'))[0]
                else:
                    self.clib = FindFileInPaths("libgcc*.a",canidatepaths)
                    if self.clib!=None:
                        self.clib = glob.glob(os.path.join(self.clib,'libgcc*.a'))[0]
            if self.clib is None:
                raise SystemExit, "tdedistutils.py (2): Failed to find a suitable libgcc library"
            self.announce("Using %s for clib" % self.clib)

            # Make a list of places to look for python .so modules
            self.python_sub_dirs = sysconfig.get_config_var("LIBSUBDIRS").split()
            base = sysconfig.get_config_var("LIBP")
            self.python_sub_dirs = [ os.path.join(base,item) for item in self.python_sub_dirs ]
            self.python_sub_dirs.append(base)

    def get_command_name(self):
        return 'build_tdeioslave'

    def run(self):
        if self.no_tdeioslave:
            self.announce("Skipping TDEIO Slaves")
            return

        if not os.path.isdir(self.build_dir):
            os.mkdir(self.build_dir)

        for moduletuple in self.distribution.tdeioslaves:
            self.announce("Building TDEIO Slave from protocol file %s." % moduletuple[0])

            protocolfilename = moduletuple[0]

            # Read the protocol file
            libraryname = None
            try:
                fhandle = open(protocolfilename,'r')
                for line in fhandle.readlines():
                    parts = line.strip().split('=')
                    try:
                        if parts[0]=="exec":
                            libraryname = parts[1]
                    except IndexError:
                        pass
                fhandle.close()
            except IOError:
                raise SystemExit, "Failed to find tdeioslave protocol file: %s" % moduletuple[0]

            # Sanity check.
            if libraryname is None:
                raise SystemExit, "Failed to find library name (Was there a exec entry in the protocol file?)"

            modulename = os.path.basename(moduletuple[1])
            if modulename.endswith('.py'):
                modulename = modulename[:-3]

            stub_cpp_name = libraryname+'.cpp'
            stub_so_name = libraryname+'.so'
            stub_la_name = libraryname+'.la'
            python_version = '%i.%i' % (sys.version_info[0],sys.version_info[1])

            # Build the 'stub' code.
            cppcode = self.cpptemplate % {"moduledir": self.data_dir,
                                            "modulename": modulename,
                                            "python_version": python_version}

            # Put it on disk.
            cppfile = os.path.join(os.path.dirname(moduletuple[0]),stub_cpp_name)
            try:
                fhandle = open(cppfile,'w')
                fhandle.write(cppcode)
                fhandle.close()
            except IOError:
                raise SystemExit, "Could not write the C++ stub: %s" % cppfile

            # Compile the stub library.
            cmdlist = ['libtool']

            # Couldn't get it to pass without this ...
            cmdlist.append("--mode=compile")
            cmdlist.append("--tag=CXX")

            # Find the compiler flags and options
            # CXX is empty on some Systems, let's do it 'the hard way'.
            # FIXME :: get CXX from make.conf for Gentoo.
            if len(sysconfig.get_config_var("CXX").split()) >= 2:
                cmdlist.extend(sysconfig.get_config_var("CXX").split())
            else:
                cmdlist.extend(['g++', '-pthread'])

            #cmdlist.extend(sysconfig.get_config_var("CXX").split())

            # cc_flags
            cmdlist.append("-c")
            cmdlist.append("-g")

            # The 4 is randomly chosen!
            # FIXME :: get CFLAGS from make.conf for Gentoo.
            if len(sysconfig.get_config_var("CFLAGS").split()) >=4:
                cmdlist.extend(sysconfig.get_config_var("CFLAGS").split())
            else:
                # On Gentoo systems, CFLAGS are not in the environment.
                raw = os.popen('emerge info 2> /dev/null|grep CFLAGS')
                lines = raw.readlines()
                if len(lines):
                    cflags = lines[0].split('"')[1].split()
                    print "Got CFLAGS from emerge info."
                    cmdlist.extend(cflags)
                else:
                    # Still no CFLAGS found, use these ...
                    cmdlist.extend(['-fno-strict-aliasing', '-DNDEBUG', '-g', '-O3', '-Wall', '-Wstrict-prototypes'])

            #sysconfig.get_config_var("CFLAGS").split()
            # includes
            cmdlist.append("-I" + sysconfig.get_config_var("INCLUDEDIR"))
            cmdlist.append("-I" + sysconfig.get_config_var("INCLUDEDIR"))
            cmdlist.append("-I" + sysconfig.get_config_var("INCLUDEPY"))
            cmdlist.append("-I" + self.python_inc_dir)
            cmdlist.append("-I" + self.kde_inc_dir)
            cmdlist.append("-I" + self.kde_inc_dir + "/tde")
            cmdlist.append("-I" + self.qt_inc_dir)
            cmdlist.append("-I/usr/include/tqt")
            cmdlist.append("-I.")
            # input
            cmdlist.append(cppfile)
            # output
            outputfile = os.path.join(self.build_dir,libraryname+'.lo')
            cmdlist.append("-o")
            cmdlist.append(outputfile)
            spawn(cmdlist) # Execute!!!
            print

            # Link the resulting object file to create a shared library.
            cmdlist = ['libtool']
            cmdlist.append("--mode=link")
            cmdlist.append("--tag=LD")

            # Grab the linker command name
            cmdlist.append(sysconfig.get_config_var("LDSHARED").split()[0])
            # link_flags
            cmdlist.append("-module")
            cmdlist.append("-avoid-version")
            cmdlist.append("-shared")
            cmdlist.append("-export-dynamic")
            # object
            cmdlist.append(outputfile)
            cmdlist.append("-rpath"); cmdlist.append(self.kde_tdeioslave_lib_dir)
            cmdlist.append("-o"); cmdlist.append(os.path.join(self.build_dir,stub_la_name))
            # Link libs
            linklist = []
            linklist.append("-lpython%s" % python_version)
            linklist.extend(sysconfig.get_config_var("LIBS").split())

            # FIXME I doubt half of these libraries need to be here.
            linklist.append(self.sip_dir+"/sip_tqt.so")
            # PyQt libs
            linklist.append(self.pyqt_dir+"/qt.so")
            # PyTDE libs
            linklist.append(self.pytde_dir+"/tdecore.so")

#            linklist.append("-L"+self.sip_dir); linklist.append("-lsip_tqt")
#            # PyQt libs
#            linklist.append("-L"+self.pyqt_dir); linklist.append("-lqtcmodule")
#            # PyTDE libs
#            linklist.append("-L"+self.pytde_dir); linklist.append("-ltdecorecmodule"); linklist.append("-ltdeuicmodule")

            linklist.append("-L"+self.kde_lib_dir); linklist.append("-L/opt/trinity/lib"); linklist.append("-ltdecore"); linklist.append("-lpythonize")
            linklist.append("-L"+self.qt_lib_dir); linklist.append("-lqt-mt")
            linklist.append("-lm")
            linklist.append("-lc")
            linklist.append(self.clib)

            linklist.append("-R"); linklist.append(self.python_dir)
            linklist.append("-R"); linklist.append(self.qt_lib_dir)
            linklist.append("-R"); linklist.append(self.sip_dir)
            linklist.append("-R"); linklist.append(self.pyqt_dir)
            linklist.append("-R"); linklist.append(self.pytde_dir)
            linklist.append("-R"); linklist.append(self.kde_lib_dir)

            cmdlist.extend(linklist)
            spawn(cmdlist) # Execute!!
            print

    cpptemplate = r"""
/*
 * Launch Control Centre modules written in Python using an embedded Python
 * interpreter.
 * Based on David Boddie's PyTDE-components.
 */

#include <stdio.h>
#include <Python.h>
#include <kinstance.h>
#define MODULE_DIR "%(moduledir)s"
#define MODULE_NAME "%(modulename)s"
#define FACTORY "SlaveFactory"

const char modname[] = MODULE_NAME;
#define MAIN_METHOD "dispatchLoop"

FILE *d = NULL;

PyObject* call_function(PyObject *callable, PyObject *args) {
    PyObject *result, *pArgs;

    if (callable == NULL) {
        printf(MODULE_NAME " tdeioslave error: callable == NULL in call_function\n");
        return NULL;
    }

    if (PyCallable_Check(callable)) {
        if(args == NULL) {
            pArgs = PyTuple_New(0);
        } else {
            pArgs = args;
        }
        result = PyObject_CallObject(callable, pArgs);

        /* If the arguments were created is this function then decrease
           their reference count. */
        if(args == NULL) {
            Py_XDECREF(pArgs);
            /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
        }

        if(result == NULL) {
            PyErr_Print();
            PyErr_Clear();
        }
    }

    return result;
}

extern "C" {
    int kdemain( int argc, char **argv) {
        PyObject *pModule, *pName, *pDict;
        TDEInstance slave(MODULE_NAME);

        Py_SetProgramName(argv[0]);
        Py_Initialize();
        //PyEval_InitThreads();
        PySys_SetArgv(1, argv);

        PyRun_SimpleString("import sys\n");
        PyRun_SimpleString("sys.path.append('"MODULE_DIR"')\n");

        pName = PyString_FromString(modname);
        pModule = PyImport_Import(pName);

        Py_XDECREF(pName);

        if(pModule == NULL) {
            printf(MODULE_NAME " tdeioslave error: pModule == NULL\n");
            return 1;
        } else {
            PyObject *pClass, *pMethod, *pArgs, *pArg1, *pArg2, *pInstance;
            int i;

            pDict = PyModule_GetDict(pModule);
            /* pDict is a borrowed reference */

            pClass = PyDict_GetItemString(pDict, FACTORY);

            if(pClass == NULL) {
                printf(MODULE_NAME " tdeioslave error: pClass == NULL\n");
                return 1;
            } else {
                pArgs = PyTuple_New(2);

                pArg1 = PyString_FromString(argv[2]);
                pArg2 = PyString_FromString(argv[3]);

                PyTuple_SetItem(pArgs, 0, pArg1);
                PyTuple_SetItem(pArgs, 1, pArg2);

                call_function(pClass, pArgs);

                /* Some time later... */
                Py_XDECREF(pClass);
                Py_XDECREF(pArgs);
            }

            Py_XDECREF(pModule);
        }

        Py_Finalize();
        return 0;
    }
}
"""
###########################################################################
class InstallTdeioslave(Command):
    description = "Install Tdeioslave files"

    user_options = [
        ('install-dir=', 'd', "base directory for installing tdeioslave module files"),
        ('install-cmd=', None, "Command to use to install the files"),
        ('install-protocol-dir=',None,"directory for tdeioslave protocol files"),
        ('build-dir=','b', "build directory (where to install from)"),
        ('root=', None, "install everything relative to this alternate root directory"),
        ('force', 'f', "force installation (overwrite existing files)"),
        ('skip-build', None, "skip the build steps"),
        ]
    boolean_options = ['force', 'skip-build']

    def initialize_options(self):
        self.build_dir = None
        self.install_dir = None
        self.install_cmd = None
        self.install_protocol_dir = None
        self.outfiles = []
        self.root = None
        self.force = 0
        self.warn_dir = 1
        self.skip_build = None

    def finalize_options(self):
        own_install_dir = self.install_dir is not None
        own_install_protocol_dir = self.install_protocol_dir is not None

        self.set_undefined_options('install',
                                    ('build_base', 'build_dir'),
                                    ('install_tdeioslave', 'install_dir'),
                                    ('root', 'root'),
                                    ('force', 'force'),
                                    ('skip_build', 'skip_build'),
                                    ('install_cmd', 'install_cmd'),
                                    ('install_protocol','install_protocol_dir')
                                    )

        if own_install_dir and self.root is not None:
            self.install_dir = change_root(self.root,self.installdir)

        if own_install_protocol_dir and self.root is not None:
            self.install_protocol_dir = change_root(self.root,self.install_protocol_dir)

    def get_command_name(self):
        return 'install_tdeioslave'

    def run(self):
        if not self.skip_build:
            self.run_command('build_tdeioslave')

        self.announce("Installing Tdeioslave files...")

        for moduletuple in self.distribution.tdeioslaves:
            self.announce("Building Tdeioslave module from protocol file %s." % moduletuple[0])

            protocolfilename = moduletuple[0]

            # Read the protocol file
            libraryname = None
            try:
                fhandle = open(protocolfilename,'r')
                for line in fhandle.readlines():
                    parts = line.strip().split('=')
                    try:
                        if parts[0]=="exec":
                            libraryname = parts[1]
                    except IndexError:
                        pass
                fhandle.close()
            except IOError:
                raise SystemExit, "Failed to find tdeioslave protocol file: %s" % moduletuple[0]

            if libraryname is None:
                raise SystemExit, "Failed to find library name (Was there a exec entry in the protocol file?)"

            self.outfiles.extend(self.mkpath(self.install_protocol_dir))
            protocolfile_dest = os.path.join(self.install_protocol_dir,os.path.basename(protocolfilename))
            self.copy_file(protocolfilename, protocolfile_dest)

            stub_la_name = libraryname+'.la'

            self.outfiles.extend(self.mkpath(self.install_dir))

            # Install the library.
            cmdlist = ['libtool']
            cmdlist.append("--mode=install")
            cmdlist.append(self.install_cmd)
            cmdlist.append("-c")
            cmdlist.append(os.path.join(self.build_dir,stub_la_name))
            cmdlist.append(os.path.join(self.install_dir,stub_la_name))
            spawn(cmdlist) # Execute!!
            print

            self.outfiles = [os.path.join(self.install_dir,os.path.basename(file)) for file in glob.glob(os.path.join(self.build_dir,'.libs',libraryname+'*'))]
            self.outfiles.append(protocolfile_dest)

        self.announce("Done installing Tdeioslave files.")

    def get_outputs(self):
        return self.outfiles or []

    def mkpath(self, name, mode=0777):
        return dir_util.mkpath(name, mode, dry_run=self.dry_run)

###########################################################################
class CheckPyQt(Command):
    description = "Checks for the presence of a working PyQt installation"

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        self.min_qt_version = self.distribution.min_qt_version

    def run(self):
        if self.min_qt_version!=None:
            qtver,kdever = get_qt_kde_versions()
            if compare_versions(self.min_qt_version,qtver)==1:
                raise SystemExit, "Your Qt version is too old. Version %s or higher is required, found %s." % (self.min_qt_version,qtver)
            self.announce("Found Qt version %s." % qtver)
        try:
            self.announce("Checking for a working PyQt...")
            from python_tqt import qt
            self.announce("  ...PyQt is working")
        except:
            raise SystemExit, "Couldn't import Qt! Please make sure that PyQt is installed and working."

    def get_outputs(self): return []

###########################################################################
class CheckPyTDE(Command):
    description = "Checks for the presence of a working PyTDE installation"

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        self.min_kde_version = self.distribution.min_kde_version

    def run(self):
        if self.min_kde_version!=None:
            qtver,kdever = get_qt_kde_versions()
            if compare_versions(self.min_kde_version,kdever)==1:
                raise SystemExit, "Your KDE version is too old. Version %s or higher is required, found %s." % (self.min_kde_version,kdever)
            self.announce("Found KDE version %s." % kdever)
        self.announce("Checking for a working PyTDE...")

        # Try to import modules one by one.
        for k_module in ('dcop', 'tdecore', 'tdeui', 'tdeio', 'tdefile', 'tdeparts', 'tdehtml', 'tdespell'):
            self.announce(k_module)
            try:
                exec('import ' + k_module)
            except:
                raise SystemExit, "Error: Couldn't find module '" + k_module + "'. \n" + \
                    "Couldn't import KDE! Please make sure that PyTDE is installed and working.\n" + \
                    "PyTDE is available here: http://www.trinitydesktop.org"
        self.announce("  ...PyTDE is working")

    def get_outputs(self): return []

###########################################################################
def FindFileInPaths2(globpattern,canidatepaths):
    if canidatepaths is None or len(canidatepaths)==0:
        return (None,None)

    # Look for the globpattern on the path.
    for path in canidatepaths:
        if path!=None:
            files = glob.glob(os.path.join(path, globpattern))
            if len(files)!=0:
                return (path,os.path.basename(files[0]))

    # Continue searching with a breadth first search.
    dirs = []
    for path in canidatepaths:
        # Examine any directories on this path.
        dirlist = glob.glob(os.path.join(path, "*"))
        for item in dirlist:
            if os.path.isdir(item):
                # Examine each subdirectory.
                dirs.append(item)
    # Examine all subdirectories.
    return FindFileInPaths2(globpattern, dirs)

###########################################################################
def FindFileInPaths(globpattern,canidatepaths):
    x,y = FindFileInPaths2(globpattern,canidatepaths)
    return x

###########################################################################
# FIXME replace this with spawn.find_executable().
def FindExeOnPath(exe_name,high_prio_dirs=None,low_prio_dirs=None):
    candiate_paths = []

    if high_prio_dirs is not None:
        candiate_paths.extend(high_prio_dirs)

    path_var = os.getenv("PATH")
    candiate_paths.extend(path_var.split(':'))

    if low_prio_dirs is not None:
        candiate_paths.extend(low_prio_dirs)

    for dir in candiate_paths:
        if dir is not None:
            candiate = os.path.join(dir,exe_name)
            if os.path.isfile(candiate):
                if os.access(candiate,os.X_OK):
                    return candiate
    return None

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

def ask_kde_config(question):
    # Look for the tde-config program
    kdeconfig = find_executable("tde-config", os.environ['PATH'] + os.pathsep + \
        os.pathsep.join(['/bin','/usr/bin','/opt/trinity/bin','/opt/kde/bin','/usr/local/bin']))
    if kdeconfig!=None:
        # Ask the tde-config program for the
        fhandle = os.popen(kdeconfig+' ' + question,'r')
        result = fhandle.read()
        fhandle.close()
        return result
    else:
        return None

###########################################################################
# Convert for example, "3.1.1a" => [3,1,1,'a']
#
def split_version_name(name):
    result = []
    accu = ''
    type = 0
    for c in name:
        if type==0:
            if c.isdigit():
                type = 1
            else:
                type = 2
            accu += c
        elif c=='.':
            if type==1:
                result.append(int(accu))
            else:
                result.append(accu)
            accu = ''
            type = 0
        elif type==1:
            # Digits
            if c.isdigit():
                accu += c
            else:
                result.append(int(accu))
                type = 2
                accu = c
        else:
            if c.isdigit():
                result.append(accu)
                type = 1
                accu = c
            else:
                accu += c
    if accu!='':
        result.append(accu)
    return result

###########################################################################
#
# Returns:
# -1 if a < b
# 0 if a and b are equal
# 1 if a > b
def compare_versions(a,b):
    aparts = split_version_name(a)
    bparts = split_version_name(b)
    if len(aparts)>len(bparts):
        compmax = len(aparts)
    else:
        compmax = len(bparts)
    i = 0
    for i in range(compmax):
        abit = 0
        if i<len(aparts):
            abit = aparts[i]
        bit = 0
        if i<len(bparts):
            bbit = bparts[i]
        if isinstance(abit,str) and not isinstance(bbit,str):
            return 1
        elif not isinstance(abit,str) and isinstance(bbit,str):
            return -1
        else:
            if abit>bbit:
                return 1
            elif abit<bbit:
                return -1
    return 0

###########################################################################
def get_qt_kde_versions():
    versioninfo = ask_kde_config('--version')
    qtver = None
    kdever = None
    if versioninfo!=None:
        for line in versioninfo.splitlines():
            if line.startswith("Qt: "):
                qtver = line[4:]
            elif line.startswith("TDE: "):
                kdever = line[5:]
    return qtver,kdever

###########################################################################
def compile_tqtdesigner(ui_files,
                  force=0,
                  prefix=None, base_dir=None,
                  verbose=1, dry_run=0):
    """Compile a collection of QT Designer UI files to .py

    If 'dry_run' is true, doesn't actually do anything that would
    affect the filesystem.
    """
    generated_files = []
    for file in ui_files:
        if not file.endswith(".ui"):
            continue

        # Terminology from the py_compile module:
        #   cfile - byte-compiled file
        #   dfile - purported source filename (same as 'file' by default)
        if base_dir:
            file = os.path.join(base_dir ,file)

        pyfile = file[:-3] + '.py'
        uifile = file

        pyfile_base = os.path.basename(pyfile)
        if force or newer(uifile, pyfile):
            log.info("compiling Qt-Designer UI %s to %s", file, pyfile_base)
            if not dry_run:
                qtuicompiler.CompileUI(uifile, pyfile)
            generated_files.append(pyfile)
        else:
            log.debug("skipping Qt-Designer compilation of %s to %s",
                      file, pyfile_base)
    return generated_files

###########################################################################
def get_libdir_name():
    if os.uname()[4] in ['x86_64','mips64','ppc64','sparc64','s390x','aarch64','ppc64le']:
        return 'lib64'
    else:
        return 'lib'