This file is indexed.

/usr/share/perl5/PilotMgr.pm is in pilot-manager 1.107.0pre108-5.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
#!/usr/bin/perl
# ------------------------------------------------------------
# Copyright (c) 1997 Sun Microsystems, Inc.
# All rights reserved.
# 
# Permission is hereby granted, without written agreement and without
# license or royalty fees, to use, copy, modify, and distribute this
# software and its documentation for any purpose, provided that the
# above copyright notice and the following two paragraphs appear in
# all copies of this software.
# 
# IN NO EVENT SHALL SUN MICROSYSTEMS, INC. BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF SUN
# MICROSYSTEMS, INC. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 
# SUN MICROSYSTEMS, INC. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THE SOFTWARE PROVIDED
# HEREUNDER IS ON AN "AS IS" BASIS, AND SUN MICROSYSTEMS, INC. HAS NO
# OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
# MODIFICATIONS.
# ------------------------------------------------------------
#
# PilotManager is a synchronization suite for the 3Com(USRobotics) Pilot.
# It allows the user to synchronize Pilot databases with applications
# on your Unix desktop.
# 
# PilotManager offers the ability to plug in in custom designed
# conduits that will synchronize data between the Pilot and your
# desktop.  Each conduit will be called in turn for a specific database.
#
# Be sure to check out the PilotManager web page!
#          http://www.moshpit.org/pilotmgr
#
# Bharat Mediratta, 4/97
# Bharat@Menalto.Com
# Alan Harder, 1/98
# Alan.Harder@Sun.Com
#
# To subscribe to the PilotManager aliases, send email to:
#
#     pilotmgr-announce-request@pilotmgr.ebay.sun.com (Announcements)
#     pilotmgr-request@pilotmgr.ebay.sun.com          (Discussion)
#
# with the word 'subscribe' in the body of the email.
# You can subscribe from within PilotManager using the
# Feedback menu.  You should submit bug reports this way
# also.
#
# Patch for -daemon flag in version 1.107 provided (separately) by
# Aaron Kaplan <kaplan@cs.rochester.edu>/Gossamer <gossamer@tertius.net.au>
# and Robert King <rob@fmr.com>.
# Patch for restoring previous username/id to reset pilot in v1.107
# provided by Bodo Bellut <bodo@garfield.ping.de>.
#
package PilotMgr;

my $VERSION = "1.107";		 # PilotManager Version
my ($BASEDIR);			 # Location of PilotManager directory
my ($RCDIR);			 # PilotManager working directory
my ($userInfo);			 # Synchronization info from Pilot
my ($RCFILE);			 # PilotManager RC file
my ($LOGFILE);			 # PilotManager log file
my ($LOGFILE_THRESHOLD) = 100000;# How big the log can get
use vars qw($PREFS);		 # List of variables to be saved to prefs
my ($DEBUG) = 0;		 # Debugging mode on/off
my ($CANCEL);			 # Should we cancel this hotsync?
my ($MODE);			 # Sync Mode (normal,cmdline,specific conduits)

my $AUTHOR = 'pilotmgr-author@pilotmgr.ebay.sun.com';
my $ALIAS = 'pilotmgr@pilotmgr.ebay.sun.com';
my $ALIAS_MAINT = 'owner-pilotmgr@pilotmgr.ebay.sun.com';
my $REQUEST = 'pilotmgr-request@pilotmgr.ebay.sun.com';
my $ANNC_ALIAS = 'pilotmgr-announce@pilotmgr.ebay.sun.com';
my $ANNC_REQUEST = 'pilotmgr-announce-request@pilotmgr.ebay.sun.com';
my $URL = 'http://www.moshpit.org/pilotmgr';

# This begin block tracks down the actual location of the
# PilotManager code and puts it into @INC

# block removed for Debian version:
# we don't need this since we're installing PilotMgr.pm in the normal
# Perl load paths.  We will be putting the various Sync modules in a
# PilotMgr directory though.

use lib '/usr/share/perl5/PilotMgr';
$BASEDIR = '/usr/share/perl5/PilotMgr';

use PDA::Pilot;
use Data::Dumper;

use strict;
use Time::Local;
use TkUtils;
use sigtrap;
use Carp;

###
# Check command line parameters
#  Getopt seems to have a problem with 'use strict' so for
#  now take the easy way out.
###
while ($_ = shift)
{
    if ($_ eq '-d')
    {
	$DEBUG = 1;
    }
    elsif (/^-da?emon$/i)
    {
	# fork and sync forever in background (blocks)
	$MODE = 'DAEMON';
    }
    elsif (/^-sync$/i)
    {
	# do sync now, don't bring up gui
	$MODE = 'CMDLINE';
    }
    elsif (/^-syncwith$/i)
    {
	# sync with specified conduit(s) only
	$MODE = [shift];
	push(@$MODE, shift) while (@ARGV && $ARGV[0] !~ /^-/);
    }
    elsif (/^-install$/i)
    {
	# use Installer conduit to install specified dbs
	$MODE = ['Installer'];
	while (@ARGV && $ARGV[0] !~ /^-/)
	{
	    $_ = shift;
	    if (system "cp $_ $ENV{HOME}/.pilotmgr/Installer")
	    {
		print "Error copying $_ to $ENV{HOME}/.pilotmgr/Installer\n";
	    } else {
		s|^.*/([^/]+)$|$1|;
		print "File $_ ready for install\n";
	    }
	}
    }
    elsif (/^-rcdir$/i)
    {
	$RCDIR = shift;
    }
    else
    {
	print<<"EOH";
Usage: $0 [-rcdir <dir>]
	[-sync | -daemon | -syncwith <conduits..> | -install <dbs..>]
 -sync = Start sync from command line, don't bring up gui.
 -daemon = Daemon mode, sync forever in background (preferences are locked).
 -syncwith <conduit>* = Start sync from command line with specified conduit(s).
			(Ignores currently "active" conduits from preferences)
 -install <prc/pdb>* = Use Installer conduit to install the specified files.
 -rcdir <dir> = Access resource dir <dir> instead of default ~/.pilotmgr
No parameters brings up PilotManager in normal GUI mode.
EOH
	exit;
    }
}

##############################################################################
#
# GUI code
#
##############################################################################

my ($gWm);			# Main window
my ($gColorDialog);		# Color configuration dialog
my ($gPropsDialog);		# Properties Dialog
my ($gAboutDialog);		# About PilotManager Dialog
my ($gDocDialog);		# PilotManager Document Reader Dialog
my ($gDocText);			# Contents of DocDialog text window
my ($gDocTitle);		# Title of DocDialog text window
my ($gMainFrame);		# Regular sync output frame
my ($gSyncOutput);		# Text area for sync output info
my ($gHotSyncButton);		# Button widget that starts ball rolling
my ($gNewConduits);		# Window for choosing new conduits to load
my ($gNewConduitList);		# Listbox widget containing new conduits
my ($gPortMenu);		# Menu to select port from
my ($gRateMenu);		# Menu to select rate from
my ($gFeedbackMenu);		# Feedback menu
my ($gReloadMenu);		# Reload conduit menu (in debug mode)
my ($gConfigButton);		# Config button on Prefs sheet
my ($gMoveAButton);		# "<< Move" button on Prefs sheet
my ($gMoveIButton);		# "Move >>" button on Prefs sheet
my ($gMoveUButton);		# "Move Up" button on Prefs sheet
my ($gMoveDButton);		# "Move Down" button on Prefs sheet
my ($gActiveConduitList);	# Listbox widget containing active conduits
my ($gInactiveConduitList);	# Listbox widget containing inactive conduits
my ($gClearOutput);		# Button to clear output widget
my ($gStatusWindow);		# immediate status window
my ($gStatus);			# immediate status data record
my ($DefaultColors);		# Default colors for widgets
my ($gCancel);			# Cancel sync button
my ($gOtherPortDialog);		# Text entry dialog for other serial ports
my ($gOtherPort);		# Result from above dialog
my ($gOtherPortDone);		# Modal trigger from above dialog

sub createGUI
{
    my (@frame);	# array of frames and subframes
    my ($menu);
    my ($label);
    my ($button);
    my ($text);
    my ($image);

    my (@FILEMENU) =
	(
	 "Properties...", [],
	 "Installer", [
		"Configure...", [],
		"Run...", [] ],
	 "-", [],
	 "Load New Conduits...", [],
	 "-", [],
	 "Quit", [],
	 );

    my (@RELOADMENU) = ();

    my (@HELPMENU) =
	(
	 "About PilotManager...", [],
	 "-", [],
	 "Writing your own Conduit...", [],
	 "Copyright...", [],
	 );

    my (@FEEDBACKMENU) =
	("File a bug", [],
	 "Send email to PilotManager alias...", [],
	 "Send email to PilotManager author...", [],
	 "-", [],
	 "PilotManager Announcements alias", [
		"About alias", [],
		"Subscribe to alias...", [],
		"Unsubscribe from alias...", []],
	 "PilotManager Discussion alias", [
		"About alias", [],
		"Subscribe to alias...", [],
		"Unsubscribe from alias...", []],
	 "Send email to alias maintainer...", []);

    my ($key);
    foreach $key (sort (keys %{$PREFS->{"InactiveConduits"}},
			keys %{$PREFS->{"ActiveConduits"}}))
    {
	push(@{$FEEDBACKMENU[1]}, "File bug against $key...", []);
	push(@RELOADMENU, $key, []);
    }
    push(@{$FEEDBACKMENU[1]}, "-", [], "File bug against PilotManager...", []);
    push(@RELOADMENU, "PilotSync", []);

    #########################################
    # Main Window
    #########################################


    $gWm = MainWindow->new;
    $gWm->title("PilotManager, v$VERSION");
    $gWm->bind("<Destroy>", sub { if ($_[0] eq $gWm) { &quit; } });
    $image = $gWm->Photo('pilotmgr', 
			 -file => "$BASEDIR/lib/images/pilotmgr.gif");

    $frame[0] = $gWm->Frame(-relief => "raised",
			    -borderwidth => 2);


    $menu = &Menu($frame[0], "File", \&menuChoice, @FILEMENU);
    $menu->configure(-relief => "flat");
    $menu->pack(-side => "left");

    $gFeedbackMenu = &Menu($frame[0], "Feedback", \&menuChoice, @FEEDBACKMENU);
    $gFeedbackMenu->configure(-relief => "flat");
    $gFeedbackMenu->pack(-side => "left");

    if ($DEBUG)
    {
	$gReloadMenu = &Menu($frame[0], "Reload", \&menuChoice, @RELOADMENU);
	$gReloadMenu->configure(-relief => "flat");
	$gReloadMenu->pack(-side => "left");
    }

    $menu = &Menu($frame[0], "Help", \&menuChoice, @HELPMENU);
    $menu->configure(-relief => "flat");
    $menu->pack(-side => "right");

    $frame[0]->pack(-side => "top",
		    -fill => "x");

    $gMainFrame = $gWm->Frame;

    $image = $gWm->Photo('hotsync', 
			 -file => "$BASEDIR/lib/images/hotsync.gif");

    if (!exists($PREFS->{"seenWelcome"}) || $PREFS->{"seenWelcome"} == 0)
    {
	$label = TkUtils::Label($gMainFrame, "^^^ Choose File / Properties");
	$label->pack(-anchor => "w");
    }

    $gHotSyncButton = TkUtils::Button($gMainFrame, "HotSync", 
				      sub{ &buttonChoice("HotSync") });
    $gHotSyncButton->configure(-image => 'hotsync');
    $gHotSyncButton->configure(-relief => 'flat');

    $gHotSyncButton->configure(-foreground => 'red4');
    $gHotSyncButton->pack(-anchor => "c");

    if (!exists($PREFS->{"seenWelcome"}) || $PREFS->{"seenWelcome"} == 0)
    {
	$label = TkUtils::Label($gMainFrame, "Then click ^^^ this button");
	$label->pack(-anchor => "c");
    }

    ($gSyncOutput, $label) = TkUtils::Text($gMainFrame, 
					   "Synchronization Status");
			    
    $gSyncOutput->configure(-wrap => "word");
    $gSyncOutput->parent->pack(-fill => "both",
			       -expand => "true");
    $gSyncOutput->pack(-fill => "both",
		       -expand => "true");

    $frame[0] = $gMainFrame->Frame;
    $gClearOutput = TkUtils::Button($frame[0], "Clear Status Window",
				    sub{ &buttonChoice("Clear Status Window")
					 });
    $gClearOutput->pack(-side => 'left');

    $gCancel = TkUtils::Button($frame[0], "Cancel Sync",
			       sub{ &buttonChoice("Cancel Sync")
					 });
    $gCancel->configure(-state => "disabled");

    $gCancel->pack(-side => 'left');
    
    $frame[0]->pack(-side => 'bottom');

    $gMainFrame->pack(-expand => "true",
		      -fill => "both");

    if ($PREFS->{"mainGeometry"})
    {
	$gWm->geometry($PREFS->{"mainGeometry"});
    }

    &setColors($gWm);

    # Set the icon at the end.  If we set it sooner, the pilotmanager
    # window tends to appear before we're ready (don't know why!)
    #
    $gWm->Icon(-image => 'pilotmgr');
    $gWm->iconname($VERSION);
}

sub updateMenus
{
    my ($conduit, $fmenu, $rmenu);

    # Get menu handles
    return unless (defined $gFeedbackMenu);
    $fmenu = $gFeedbackMenu->cget("-menu")->entrycget(1, "-menu");
    $rmenu = $gReloadMenu->cget("-menu") if ($DEBUG);

    # Delete old items
    #  Index 0 is tearoff, last 2 are separator and PilotMgr choice
    $fmenu->delete(1, $fmenu->index("last") - 2);
    $rmenu->delete(1, "end") if ($DEBUG);

    # Repopulate menus
    foreach $conduit (sort(keys %{$PREFS->{"InactiveConduits"}},
			   keys %{$PREFS->{"ActiveConduits"}}))
    {
	$fmenu->insert($fmenu->index("last") - 1, "command",
	    -label => "File bug against $conduit...",
	    -command =>
		eval qq{sub{&menuChoice(
		    "Feedback / File a bug / File bug against $conduit...")}});

	if ($DEBUG)
	{
	    $rmenu->add("command", -label => $conduit,
		-command => eval qq{sub{&menuChoice("Reload / $conduit")}});
	}
    }
    $rmenu->add("command", -label => "PilotSync",
	-command => sub{&menuChoice("Reload / PilotSync")}) if ($DEBUG);
}

sub createColorDialog
{
    my (@frames);
    my (%menu, %entry);
    my (@opts);
    my ($key);
    my ($obj);

    $gColorDialog = $gWm->Toplevel(-title => "Configure Colors");
    $gColorDialog->withdraw;
    $gColorDialog->transient($gWm);

    $obj = TkUtils::Label($gColorDialog, 
			  "Select a color for each object\n" .
			  "If the field is blank, the default will be used.\n".
			  "Your changes will be saved when you dismiss " .
			  "the dialog.\nHit apply to have your changes " .
			  "reflected immediately.");
    $obj->pack(-side => 'top',
	       -anchor => 'center');

    # Determine list of settable attributes
    #
    foreach $key (sort keys %{$PREFS->{"colors"}->{"Default"}})
    {
	push(@opts, $key, []);
    }

    # Create a choice for each object.
    #
    $frames[0] = $gColorDialog->Frame(-relief => 'ridge', -bd => '2');
    $frames[1] = $frames[0]->Frame;
    $frames[2] = $frames[0]->Frame;
    $frames[3] = $frames[0]->Frame;
    my (%seen);
    foreach $key ("Default", sort keys %{$PREFS->{"colors"}})
    {
	next if $seen{$key}++;

	$obj = TkUtils::Label($frames[1], $key);
	$obj->pack(-side => 'top',
		   -anchor => 'e',
		   -expand => 'true',
		   -fill => 'both');

	$obj->configure(-foreground => 'blue')
	    if ($key eq "Default");

	$entry{$key} = TkUtils::Entry($frames[3],
				      \$PREFS->{"colors"}->{$key}->{$opts[0]});
	$entry{$key}->pack(-side => 'top',
			   -expand => 'true',
			   -fill => 'both');

	$menu{$key} = TkUtils::Menu($frames[2], 
				    $opts[0],
				    sub{ my ($val) = $_[0]; $val =~ s|.*/ ||;
					 $menu{$key}->configure(-text => $val);
					 $entry{$key}->configure(-textvariable => \$PREFS->{"colors"}->{$key}->{$val});
				     },
				    @opts);

	$menu{$key}->pack(-side => 'top',
			  -expand => 'true',
			  -fill => 'both');
    }
    $frames[3]->pack(-side => 'right',
		     -fill => 'both',
		     -expand => 'true');
    $frames[2]->pack(-side => 'right',
		     -fill => 'both',
		     -expand => 'true');
    $frames[1]->pack(-side => 'right',
		     -fill => 'both',
		     -expand => 'true');

    $frames[0]->pack(-side => 'top');

    $frames[0] = $gColorDialog->Frame;

    $obj = TkUtils::Button($frames[0], "Apply", sub{ &setColors($gWm) });
    $obj->pack(-side => 'left',
	       -anchor => 'center');

    $obj = TkUtils::Button($frames[0], "Dismiss", 
			   sub{ &setColors($gWm); $gColorDialog->withdraw });
    $obj->pack(-side => 'left',
	       -anchor => 'center');

    $frames[0]->pack(-side => 'bottom');
    
    &setColors($gColorDialog);
}

sub createAboutDialog
{
    my (@frame);
    my ($label);
    my ($button);
    my (@saveLabels);

    $gAboutDialog = $gWm->Toplevel(-title => "About PilotManager");
    $gAboutDialog->withdraw;
    $gAboutDialog->transient($gWm);
    $frame[0] = $gAboutDialog->Frame;

    $label = TkUtils::Label($frame[0], "PilotManager $VERSION");
    $label->pack(-side => 'top',
		 -anchor => 'center');
    push(@saveLabels, $label);

    $label = TkUtils::Label($frame[0], 
			    "PilotManager is a Unix synchronization " .
			    "suite for the 3Com PalmPilot.\n For more " .
			    "details, please refer to:");
    $label->pack(-side => 'top',
		 -anchor => 'center');

    $label = TkUtils::Label($frame[0], $URL);
    $label->pack(-side => 'top',
		 -anchor => 'center');
    push(@saveLabels, $label);

    $label = TkUtils::Label($frame[0], 
			    "Please file any bugs that you find via\nthe " .
			    "Feedback menu.  Thank-you.");
    $label->pack(-side => 'top',
		 -anchor => 'center');

    $label = TkUtils::Label($frame[0], 
			    "Copyright (C) 1997 Bharat " .
			    "Mediratta\nSubject to the terms of the Sun " .
			    "Microsystems License\nDevelopment taken over " .
			    "11/97 by Alan Harder");
    $label->pack(-side => 'top',
		 -anchor => 'center');


    $button = TkUtils::Button($frame[0], "Dismiss",
			      sub{ $gAboutDialog->withdraw});
    $button->pack;

    $frame[0]->pack;

    &setColors($gAboutDialog);

    foreach $label (@saveLabels)
    {
	$label->configure('foreground' => 'red4');
    }

    $gAboutDialog->withdraw;
}

sub createPropsDialog
{
    my (@frame);
    my ($label);
    my ($button);
    my ($image);

    my (@TTYMENU) =
	("/dev/ttya", [],
	 "/dev/ttyb", [],
	 "/dev/cua/a", [],
	 "/dev/cua/b", [],
	 "/dev/cua0", [],
	 "/dev/cua1", [],
	 "/dev/cua2", [],
	 "/dev/cua3", [],
	 "/dev/pilot", [],
	 "Other...", []);

    my (@RATEMENU) =
	("9600", [],
	 "19200", [],
	 "38400", [],
	 "57600", [],
	 "76800", [],
	 "115200", []);

    $gPropsDialog = $gWm->Toplevel(-title => "PilotManager Properties");
    $gPropsDialog->withdraw;
    $gPropsDialog->transient($gWm);

    $frame[0] = $gPropsDialog->Frame;
    $frame[1] = $frame[0]->Frame;

    $frame[2] = $frame[1]->Frame(-relief => 'ridge', -bd => 2);
    $label = TkUtils::Label($frame[2], "Communication Settings");
    $label->pack(-side => 'top',
		 -anchor => 'center');
    $label->configure(-foreground => "blue");

    $frame[3] = $frame[2]->Frame;
    $frame[4] = $frame[3]->Frame;
    $label = TkUtils::Label($frame[4], "Pilot Port");
    $label->pack(-side => "top");
    $label = TkUtils::Label($frame[4], "Comm speed ");
    $label->pack(-side => "top");
    $frame[4]->pack(-side => "left");

    $frame[4] = $frame[3]->Frame;
    $PREFS->{"gPort"} ||= $TTYMENU[0];
    $gPortMenu = &Menu($frame[4], 
		       $PREFS->{"gPort"} || $TTYMENU[0],
		       sub{
			   if ($_[0] =~ /Other/) { &getOtherPort; } else {
			   ($PREFS->{"gPort"} = $_[0]) =~ s|.*/ ||;
			   $gPortMenu->configure(-text => $PREFS->{"gPort"})
			   }},
		       @TTYMENU);
    $gPortMenu->pack(-side => "top");
    $PREFS->{"gRate"} ||= "9600";
    $gRateMenu = &Menu($frame[4], 
		       $PREFS->{"gRate"} || $RATEMENU[0], 
		       sub{
			   ($PREFS->{"gRate"} = $_[0]) =~ s|.*/ ||;
			   $gRateMenu->configure(-text => $PREFS->{"gRate"})
			   },
		       @RATEMENU);
    $gRateMenu->pack(-side => "top",
		     -expand => "true",
		     -fill => "x");
    $frame[4]->pack(-side => "left");
    $frame[3]->pack;
    $frame[2]->pack(-side => "left",
		    -expand => 'true',
		    -fill => 'both');

    $frame[2] = $frame[1]->Frame(-relief => 'ridge', -bd => 2);
    $label = TkUtils::Label($frame[2], "Miscellaneous");
    $label->configure(-foreground => "blue");
    $label->pack(-anchor => 'c');

    $frame[3] = $frame[2]->Frame;

    $PREFS->{"gDateStamp"} = 1
	unless (exists($PREFS->{"gDateStamp"}) && 
		defined($PREFS->{"gDateStamp"}));

    $button = TkUtils::Checkbutton($frame[3], 
				   "Datestamp hotsync log",
				   \$PREFS->{"gDateStamp"});

    $button->pack(-side => 'top',
		  -expand => 'false');

    $PREFS->{"gShowConduitStatus"} = 1
	unless (exists($PREFS->{"gShowConduitStatus"}) &&
		defined($PREFS->{"gShowConduitStatus"}) );

    $button = TkUtils::Checkbutton($frame[3], 
				   "Show conduit status window",
				   \$PREFS->{"gShowConduitStatus"});

    $button->pack(-side => 'top',
		  -expand => 'false');


    $frame[4] = $frame[3]->Frame;
    $button = TkUtils::Checkbutton($frame[4], 
				   "Use color scheme",
				   \$PREFS->{"gUseColors"});
    $button->bind("<ButtonPress>", 
		  sub{ 
		      if ($PREFS->{"gUseColors"})
		      {
			  &setColors($gWm);
		      }
		      else
		      {
			  &unsetColors($gWm);
		      }
		  });

    $button->pack(-side => 'left',
		  -expand => 'false');
    
    $button = TkUtils::Button($frame[4],
			      "Customize Colors",
			      sub{ &showColorDialog });
    $button->pack(-side => 'left',
		  -expand => 'false');

    $frame[4]->pack(-side => 'top',
		    -expand => 'false');

    $frame[3]->pack;

    $frame[2]->pack(-side => 'left',
		    -expand => 'true',
		    -fill => 'both');
    $frame[1]->pack(-side => 'top',
		    -expand => 'false',
		    -fill => 'x');

    $frame[1] = $frame[0]->Frame(-relief => 'ridge',
				 -bd => '2');
	$frame[1]->pack( -expand => 'true',
				 -fill => 'x');
    $frame[2] = $frame[1]->Frame;
    ($gActiveConduitList, $label) = 
	TkUtils::List($frame[2], "Active Conduits (in order)", "vertical");
    $gActiveConduitList->configure(-height => 5);
    $label->configure(-foreground => "darkgreen");
    $gActiveConduitList->pack(-fill => "both",
			      -expand => "true");
    $gActiveConduitList->bind("<Double-Button-1>", 
			      sub{&buttonChoice("Configure")});
    $gActiveConduitList->bind("<ButtonPress>", \&selectConduit);
    $gActiveConduitList->bind("<ButtonRelease>", \&selectConduit);
    $gActiveConduitList->bind("<KeyPress-Down>", \&selectConduit);
    $gActiveConduitList->bind("<KeyPress-Up>", \&selectConduit);

    $gMoveUButton= TkUtils::Button($frame[2], "Up", 
				   sub{&buttonChoice("Up")});
    $gMoveUButton->configure(-state => "disabled");
    $gMoveUButton->pack(-padx => 0,
			-side => "left",
			-anchor => "c",
			-expand => "true");

    $gMoveDButton= TkUtils::Button($frame[2], "Down", 
				   sub{&buttonChoice("Down")});
    $gMoveDButton->configure(-state => "disabled");
    $gMoveDButton->pack(-side => "left",
			-anchor => "c",
			-expand => "true");
    $gConfigButton= TkUtils::Button($frame[2], "Configure", 
				     sub{&buttonChoice("Configure")});
    $gConfigButton->configure(-state => "disabled");
    $gConfigButton->pack(-side => "left", 
			 -anchor => "c",
			 -expand => "true");


    $gMoveIButton = TkUtils::Button($frame[2], "Move >>", 
				    sub{&buttonChoice("Move >>") });
    $gMoveIButton->configure(-state => "disabled");
    $gMoveIButton->pack(-side => "left",
			-anchor => "c",
			-expand => "true");

    $frame[2]->pack(-side => 'left',
		    -expand => 'true',
		    -fill => 'both');

    $frame[2] = $frame[1]->Frame;
    ($gInactiveConduitList, $label) = 
	TkUtils::List($frame[2], "Inactive Conduits", "vertical");
    $gInactiveConduitList->configure(-height => 5);
    $gInactiveConduitList->bind("<Double-Button-1>", 
				sub{&buttonChoice("<< Move")});
    $gInactiveConduitList->bind("<ButtonPress>", \&selectConduit);
    $gInactiveConduitList->bind("<ButtonRelease>", \&selectConduit);
    $gInactiveConduitList->bind("<KeyPress-Down>", \&selectConduit);
    $gInactiveConduitList->bind("<KeyPress-Up>", \&selectConduit);
    $label->configure(-foreground => "red");
    $gInactiveConduitList->pack(-fill => "both",
				-expand => "true");


    $gMoveAButton = TkUtils::Button($frame[2], "<< Move", 
				    sub{ &buttonChoice("<< Move") });
    $gMoveAButton->configure(-state => "disabled");
    $gMoveAButton->pack(-side => "left", 
			-anchor => "c",
			-expand => "true");
    $frame[2]->pack(-side => 'left',
		    -expand => 'true',
		    -fill => 'both');
    $frame[1]->pack(-side => 'top',
		    -expand => 'true',
		    -fill => 'both');

    $frame[0]->configure(-relief => "raised");
    $frame[0]->pack(-fill => "both",
		 -expand => "true");

    $button = TkUtils::Button($frame[0], "Dismiss", 
			     sub{ &savePrefs; $gPropsDialog->withdraw});
    $button->pack;

    if ($PREFS->{"propsGeometry"})
    {
	$gPropsDialog->geometry($PREFS->{"propsGeometry"});
    }

    $gPropsDialog->bind("<Destroy>",
			sub{ if ($_[0] eq $gPropsDialog) { &savePrefs; } } );


    &setColors($gPropsDialog);

    &updateConduitLists;
}

sub createOtherPortDialog
{
    my ($frame, $obj);

    $gOtherPortDialog = $gWm->Toplevel(-title => 'Serial Port Device');
    $gOtherPortDialog->withdraw;
    $gOtherPortDialog->transient($gWm);

    $frame = $gOtherPortDialog->Frame(-relief => 'ridge', -bd => 2);

    $obj = $frame->Entry(-textvariable => \$gOtherPort, -width => 15);
    $obj->pack(-side => 'top');

    $obj = $frame->Button(-text => 'Ok',
			  -command => sub { $gOtherPortDone = 1; });
    $obj->pack(-side => 'left');

    $obj = $frame->Button(-text => 'Cancel',
			  -command => sub { $gOtherPortDone = 2; });
    $obj->pack;

    $frame->pack;

    &setColors($gOtherPortDialog);
}

sub showAbout
{
    &createAboutDialog
	unless (defined($gAboutDialog) && $gAboutDialog->Exists);

    $gAboutDialog->Popup(-popanchor => 'c',
			 -popover => $gWm,
			 -overanchor => 'c');
}

sub showColorDialog
{
    &createColorDialog
	unless (defined($gColorDialog) && $gColorDialog->Exists);

    $gColorDialog->Popup(-popanchor => 'c',
			 -popover => $gWm,
			 -overanchor => 'c');
}

sub showDoc
{
    my ($doc, $title) = @_;
    my ($ret);

    unless (defined($gDocDialog) && $gDocDialog->Exists)
    {
	my (@frame);
	my ($button);
	$gDocDialog = $gWm->Toplevel(-title => "PilotManager Documentation");
	$gDocDialog->withdraw;
	$gDocDialog->transient($gWm);
	$frame[0] = $gDocDialog->Frame;

	($gDocText, $gDocTitle) = TkUtils::Text($frame[0], $title);
	$gDocText->configure(-height => 20,
			     -state => "disabled");
	$gDocText->pack(-expand => "true",
			-fill => "both");
			     

	$button = TkUtils::Button($frame[0], "Dismiss",
				  sub{ $gDocDialog->withdraw});
	$button->pack;

	$frame[0]->pack(-expand => 'true',
			-fill => 'both');

	&setColors($gDocDialog);
    }

    $gDocText->configure(-state => "normal");
    $gDocText->delete("0.0", "end");

    if(open(FD, "<$BASEDIR/$doc"))
    {
	$gDocTitle->configure(-text => $title);
	while (<FD>)
	{
	    $gDocText->insert("end", $_);
	}
	close(FD);
	$ret = 1;
    }
    else
    {
	$gDocTitle->configure(-text => "Error!");
	$gDocText->insert("end", "Error loading $BASEDIR/$doc!\n"); 
	# $gDocText->insert("end", "Please file a bug using the Feedback menu");
	$ret = 0;
    }

    $gDocText->configure(-state => "disabled");
    $gDocDialog->Popup(-popanchor => 'c',
		       -popover => $gWm,
		       -overanchor => 'c');

    return $ret;
}

sub showProperties
{
    &createPropsDialog
	unless (defined($gPropsDialog) && $gPropsDialog->Exists);

    $gPropsDialog->Popup(-popanchor => 'c',
			 -popover => $gWm,
			 -overanchor => 'c');
}

sub configureInstaller
{
    if (defined &Installer::conduitConfigure)
    {
	Installer::conduitConfigure("Installer", $gWm);
    }
    else
    {
	&tellUser("Installer conduit not found!");
    }
}

sub runInstaller
{
    unless (defined &Installer::conduitSync)
    {
	&tellUser("Installer conduit not found!");
	return;
    }

    my ($saveOrder) = ($PREFS->{"ActiveOrder"});

    $PREFS->{"ActiveOrder"} = ["Installer"];

    $gHotSyncButton->configure(-state => "disabled");
    $gCancel->configure(-state => 'normal');

    eval
    {
	&hotSync;
    };
    msg("Error: $@") if ($@);

    $gHotSyncButton->configure(-state => "normal");
    $gCancel->configure(-state => 'disabled');
    $gStatusWindow->withdraw
	if (defined $gStatusWindow and $gStatusWindow->Exists);

    $PREFS->{"ActiveOrder"} = $saveOrder;
}

sub getOtherPort
{
    &createOtherPortDialog
	unless(defined($gOtherPortDialog) && $gOtherPortDialog->Exists);

    $gOtherPort = '';
    $gOtherPortDone = 0;
    $gOtherPortDialog->Popup(-popanchor => 'c', -overanchor => 'c',
			     -popover => $gPropsDialog);

    $gOtherPortDialog->grab;
    $gOtherPortDialog->waitVariable(\$gOtherPortDone);
    $gOtherPortDialog->grabRelease;
    $gOtherPortDialog->withdraw;

    if ($gOtherPortDone == 1)
    {
	$PREFS->{'gPort'} = $gOtherPort;
	$gPortMenu->configure(-text => $PREFS->{'gPort'});
    }
}

sub menuChoice
{
    my ($choice) = @_;

    ($choice eq "File / Quit") and $gWm->destroy;
    ($choice eq "File / Properties...") and &showProperties;
    ($choice eq "File / Installer / Configure...") and &configureInstaller;
    ($choice eq "File / Installer / Run...") and &runInstaller;
    ($choice eq "File / Load New Conduits...") and &loadNewConduits;
    ($choice eq "Help / About PilotManager...") and &showAbout;
    ($choice eq "Help / Copyright...") and 
	&showDoc("COPYRIGHT", "Copyright");
    ($choice eq "Help / Writing your own Conduit...") 
	and &showDoc("docs/Conduit.api", "Writing your own Conduit");
    ($choice eq "Help / About PilotManager...") and &showAbout;
    ($choice =~ m|.*File a bug / .*\s(.*?)\.\.|) and &feedback("bug $1");
    ($choice =~ m|Feedback / Send .* alias maint|) and &feedback("aliasmaint");
    ($choice =~ m|Feedback / Send .*ilotManager alias|) and &feedback("alias");
    ($choice =~ m|Feedback / Send .* author|) and &feedback("author");
    ($choice =~ m|Feedback / .* Announcements alias / About alias|)
	and &showDoc("docs/AnncAlias.txt", "PilotManager Announcements Alias");
    ($choice =~ m|Feedback / .* Discussion alias / About alias|)
	and &showDoc("docs/DiscAlias.txt", "PilotManager Discussion Alias");
    ($choice =~ m|Feedback / PilotManager (.*) alias / Subscribe|)
	and &feedback("subscribe-$1");
    ($choice =~ m|Feedback / PilotManager (.*) alias / Unsubscribe|)
	and &feedback("unsubscribe-$1");

    if ($DEBUG)
    {
	if ($choice =~ m|Reload / (.*)|)
	{
	    my ($status, %sym) = ({});

	    # Unload
	    delete $INC{"$1.pm"};
	    *sym = "$1::";
	    undef %sym;

	    # Special for PilotSync (not a conduit)
	    if ($1 eq 'PilotSync')
	    {
		eval "use $1";
		msg($@ ? "Error reloading PilotSync: $@"
		       : "PilotSync module reloaded.");
		return;
	    }

	    # Reload
	    &loadConduits( [ $1 ], $status );

	    # Tell user what happened
	    if ($status->{$1})
	    {
		# Remove conduit from GUI things if reload failed
		&updateConduitLists;
		&updateMenus;

		msg("Conduit '$1' not reloaded due to errors.");
	    } else {
		msg("Conduit '$1' has been reloaded.");
	    }
	}
    }
}

sub feedback
{
    my ($type) = @_;

    ($type eq "alias") && 
	&showMail('to' => $ALIAS,
		 'editable' => 'true');

    ($type eq "author") && 
	&showMail('to' => $AUTHOR,
		 'subject' => "PilotManager v$VERSION Feedback",
		 'editable' => 'true');

    ($type eq "aliasmaint") &&
	&showMail('to' => $ALIAS_MAINT,
		  'editable' => 'true');

    ($type =~ /^(subscribe)-(.*)$/ ||
     $type =~ /^(unsubscribe)-(.*)$/) && 
	 &showMail('to' => ($2 eq "Announcements" ? $ANNC_REQUEST : $REQUEST),
		  'subject' => "Administrative request",
		  'body' => "$1\n",
		  'editable' => 'false');

    if ($type eq "bug PilotManager")
    {
	&showMail('to' => $AUTHOR,
		  'subject' => "PilotManager v$VERSION bug report",
		  'editable' => 'true');
    }
    elsif ($type =~ /bug (.*)/)
    {
	my ($conduit);
	if (exists($PREFS->{"ActiveConduits"}{$1}))
	{
	    $conduit = $PREFS->{"ActiveConduits"}{$1};
	}
	else
	{
	    $conduit = $PREFS->{"InactiveConduits"}{$1};
	}

	&showMail('to' => $conduit->{"email"},
		  'subject' => "PilotManager: $1 v$conduit->{version} " .
		               "bug report",
		  'cc' => $AUTHOR,
		  'editable' => 'true');
    }
}

sub showMail
{
    my (%data) = @_;
    my (@frame);
    my ($key);
    my ($win);
    my ($to, $subj, $cc, $text);
    my ($label, $entry, $button);

    $win = $gWm->Toplevel(-title => "Send Feedback...");
    $win->withdraw;
    $win->transient($gWm);
    $frame[0] = $win->Frame;
    $frame[1] = $frame[0]->Frame;
    $frame[2] = $frame[1]->Frame;
    TkUtils::Label($frame[2], "To:");
    TkUtils::Label($frame[2], "Subject:");
    TkUtils::Label($frame[2], "Cc:");
    $frame[2]->pack(-side => 'left');

    $frame[2] = $frame[1]->Frame;
    $entry = TkUtils::Entry($frame[2], \$to);
    $entry->configure(-state => 'disabled')
	if (exists($data{"editable"}) && $data{"editable"} eq 'false');

    $entry = TkUtils::Entry($frame[2], \$subj);
    $entry->configure(-state => 'disabled')
	if (exists($data{"editable"}) && $data{"editable"} eq 'false');

    $entry = TkUtils::Entry($frame[2], \$cc);
    $entry->configure(-state => 'disabled')
	if (exists($data{"editable"}) && $data{"editable"} eq 'false');
    $frame[2]->pack(-side => 'left',
		    -expand => 'true',
		    -fill => 'x');
    $frame[1]->pack(-expand => 'false',
		    -fill => 'x');

    ($text) = TkUtils::Text($frame[0], "");
    $data{"body"} and $text->insert("end", $data{"body"});
    $text->configure(-wrap => 'word');
    $text->parent->pack(-expand => 'true',
			-fill => 'both');
    $text->configure(-state => 'disabled')
	if (exists($data{"editable"}) && $data{"editable"} eq 'false');

    $data{"to"} and $to = $data{"to"};
    $data{"subject"} and $subj = $data{"subject"};
    $data{"cc"} and $cc = $data{"cc"};

    $frame[1] = $frame[0]->Frame;
    $button = TkUtils::Button($frame[1], "Send Email", 
			      sub{ $win->withdraw; 
				   &sendEmail($to, 
					      $subj, 
					      $cc,
					      $text->get("1.0", "end"))
				   });
    $button->pack(-side => 'left');
    $button = TkUtils::Button($frame[1], "Cancel", sub{ $win->withdraw });
    $button->pack(-side => 'left');
    $frame[1]->pack;
    $frame[0]->pack(-expand => 'true',
		    -fill => 'both');
    
    &setColors($win);
    $win->Popup;
}

sub sendEmail
{
    my ($to, $subj, $cc, $body) = @_;
    my ($txt);

    if (open(FD, "|/usr/lib/sendmail -t") or
	open(FD, "|/usr/sbin/sendmail -t"))
    {
	print FD "To: $to\n";
	print FD "Subject: $subj\n"
	    if ($subj);
	print FD "Cc: $cc\n"
	    if ($cc);
	print FD "X-Mailer: PilotManager,v$VERSION\n";
	print FD "\n";
	print FD $body;

	if ($subj =~ /(bug|feedback)/i)
	{
	    print FD "-" x 79, "\n";
	    chomp($txt = Config::myconfig());
	    print FD "$txt  More info:\n";
	    chomp($txt = `uname -a`);
	    print FD "    uname='$txt'\n" if ($txt);
	    if (-r '/usr/dt/lib/libcsa.so')
	    {
		($txt = `/usr/ccs/bin/mcs -p /usr/dt/lib/libcsa.so`) =~ s/\n//g;
		$txt =~ s|^/usr/dt/lib/libcsa.so:||;
		print FD "    libcsa='$txt'\n" if ($txt);
	    }
	    print FD "    perllib='$ENV{'PERLLIB'}'\n"
		if (defined $ENV{'PERLLIB'});
	    print FD "    myPMgr='$0', version=$VERSION\n";
	}

	print FD "\n.\n";
	close(FD);
    }
}

sub buttonChoice
{
    my ($choice) = @_;
    my ($id);

    if ($choice eq "Cancel Sync")
    {
	&cancel;
    }
    elsif ($choice eq "HotSync")
    {
	&savePrefs;
	$gHotSyncButton->configure(-state => "disabled");
	$gCancel->configure(-state => 'normal');

	eval
	{
	    &hotSync;
	};
	msg("Error: $@") if ($@);

	$gHotSyncButton->configure(-state => "normal");
	$gCancel->configure(-state => 'disabled');
	$gStatusWindow->withdraw
	    if (defined($gStatusWindow) && $gStatusWindow->Exists);
    }
    elsif ($choice eq "Clear Status Window")
    {
	$gSyncOutput->configure(-state => "normal");
	$gSyncOutput->delete("0.0", "end");
	$gSyncOutput->configure(-state => "disabled");
    }
    elsif ($choice eq "Up")
    {
	my ($sel);
	$sel = $gActiveConduitList->curselection;
	return if ($sel == 0);
	if (defined($sel))
	{
	    my ($line) = splice(@{$PREFS->{"ActiveOrder"}}, $sel, 1);
	    splice(@{$PREFS->{"ActiveOrder"}}, $sel-1, 0, $line);
	    &updateConduitLists;
	    $gActiveConduitList->selectionSet($sel-1);
	    $gActiveConduitList->see($sel-1);
	    &selectConduit;
	}
    }
    elsif ($choice eq "Down")
    {
	my ($sel);
	$sel = $gActiveConduitList->curselection;
	if (defined($sel))
	{
	    my ($line) = splice(@{$PREFS->{"ActiveOrder"}}, $sel, 1);
	    splice(@{$PREFS->{"ActiveOrder"}}, $sel+1, 0, $line);
	    &updateConduitLists;
	    $gActiveConduitList->selectionSet($sel+1);
	    $gActiveConduitList->see($sel+1);
	    &selectConduit;
	}
    }
    elsif ($choice eq "Move >>")
    {
	my ($sel);
	my ($conduit);
	my ($line);

	$sel = $gActiveConduitList->curselection;
	if (defined($sel))
	{
	    $line = $gActiveConduitList->get($sel);
	    ($conduit = $line) =~ s/[,\s].*//;

	    $PREFS->{"InactiveConduits"}{$conduit} = 
		$PREFS->{"ActiveConduits"}{$conduit};
	    delete $PREFS->{"ActiveConduits"}{$conduit};
	    @{$PREFS->{"ActiveOrder"}} = grep(!/$conduit/,
					      @{$PREFS->{"ActiveOrder"}});
	    &updateConduitLists;
	    $gActiveConduitList->selectionSet($sel);
	    $gActiveConduitList->see($sel);
	    &selectConduit;
	}
    }
    elsif ($choice eq "<< Move")
    {
	my ($sel);
	my ($conduit);
	my ($line);

	$sel = $gInactiveConduitList->curselection;
	if (defined($sel))
	{
	    $line = $gInactiveConduitList->get($sel);
	    ($conduit = $line) =~ s/[,\s].*//;

	    $PREFS->{"ActiveConduits"}{$conduit} = 
		$PREFS->{"InactiveConduits"}{$conduit};
	    delete $PREFS->{"InactiveConduits"}{$conduit};
	    push(@{$PREFS->{"ActiveOrder"}}, $conduit);
	    &updateConduitLists;
	    $gInactiveConduitList->selectionSet($sel);
	    $gInactiveConduitList->see($sel);
	    &selectConduit;
	}
    }
    elsif ($choice eq "Configure")
    {
	my ($line);
	my ($conduit);
	my ($sel);

	$sel = $gActiveConduitList->curselection;
	if (defined($sel))
	{
	    $line = $gActiveConduitList->get($sel);
	    ($conduit = $line) =~ s/[,\s].*//;
	    $conduit->conduitConfigure($gPropsDialog);
	}
    }
}

sub guiMessage
{
    my ($buf) = @_;

    $gSyncOutput->configure(-state => "normal");
    $gSyncOutput->insert("end", "$buf\n");
    $gSyncOutput->see("end");
    $gSyncOutput->configure(-state => "disabled");

    &update;
}

sub update
{
    $gWm->update unless (defined $MODE);
}

sub selectConduit
{
    my ($sel);

    $sel = $gActiveConduitList->curselection;
    if (defined($sel))
    {
	$gConfigButton->configure(-state => "normal");
	$gMoveIButton->configure(-state => "normal");
	$gMoveUButton->configure(-state => "normal");
	$gMoveUButton->configure(-state => "disabled")
	    if ($sel == 0);

	$gMoveDButton->configure(-state => "normal");
	$gMoveDButton->configure(-state => "disabled")
	    if ($sel == @{$PREFS->{"ActiveOrder"}} - 1);
    }
    else
    {
	$gConfigButton->configure(-state => "disabled");
	$gMoveIButton->configure(-state => "disabled");
	$gMoveUButton->configure(-state => "disabled");
	$gMoveDButton->configure(-state => "disabled");
    }

    $sel = $gInactiveConduitList->curselection;
    if (defined($sel))
    {
	$gMoveAButton->configure(-state => "normal");
    }
    else
    {
	$gMoveAButton->configure(-state => "disabled");
    }
}

sub updateConduitLists
{
    my ($conduit, $name);

    return unless (defined $gPropsDialog and $gPropsDialog->Exists);

    $gActiveConduitList->delete(0, "end");
    $gInactiveConduitList->delete(0, "end");
    foreach $conduit (@{$PREFS->{"ActiveOrder"}})
    {
	$name = &getFullName($conduit, $PREFS->{"ActiveConduits"});
	$gActiveConduitList->insert("end", $name);
    }

    foreach $conduit (sort keys %{$PREFS->{"InactiveConduits"}})
    {
	$name = &getFullName($conduit, $PREFS->{"InactiveConduits"});
	$gInactiveConduitList->insert("end", $name);
    }
}

sub unsetColors
{
    my ($widget) = @_;
    my ($attr);
    my ($name);

    ($name = $widget) =~ s/.*::(.*)=.*/$1/;

    foreach $attr (keys %{$PREFS->{"colors"}->{"Default"}})
    {
	eval
	{
	    $DefaultColors->{$name}->{$attr} = ($widget->configure($attr))[3]
		unless (exists($DefaultColors->{$name}->{$attr}));

	    if (!$DefaultColors->{$name}->{$attr})
	    {
		$DefaultColors->{$name}->{$attr} = 
		    ($gWm->configure($attr))[4];
	    }

	    $widget->configure($attr => $DefaultColors->{$name}->{$attr});
	};
    }

    my ($child);
    foreach $child ($widget->children)
    {
	&unsetColors($child);
    }
}

sub setColors
{
    my ($widget, $override) = @_;
    my ($name);
    my ($i);
    my ($attr);
    my (%seen) = ();

    return unless ($PREFS->{"gUseColors"});
    return unless (exists $PREFS->{"colors"});

    ($name = $widget) =~ s/.*::(.*)=.*/$1/;

    my ($COLOR) = $PREFS->{"colors"};

    if (exists($COLOR->{$name}))
    {
	foreach $attr (keys %{$COLOR->{"Default"}})
	{
	    # This is too slow.  And, it doesn't work the second
	    # time around...
	    #
	    if (0)
	    {
		unless ($override)
		{
		    my (@cfg);
		    eval
		    {
			@cfg = $widget->configure($attr);
		    };
		    next if ($@);

		    if (defined($cfg[3]) && defined($cfg[4]) &&
			$cfg[3] ne $cfg[4])
		    {
			next;
		    }
		}
	    }

	    # Otherwise, set it.
	    #
	    eval
	    {
		if (exists($COLOR->{$name}) && 
		    exists($COLOR->{$name}->{$attr}) &&
		    defined($COLOR->{$name}->{$attr}) &&
		    $COLOR->{$name}->{$attr} =~ /\S/)
		{
		    $widget->configure($attr => $COLOR->{$name}->{$attr});
		}
		else
		{
		    $widget->configure($attr => $COLOR->{"Default"}->{$attr})
			if exists($COLOR->{"Default"}->{$attr});
		}
	    };
	}

	# For entry widgets, set the blinking cursor to be the same
 	# color as the foreground text - code snippet from Adam Stein
 	$widget->configure(-insertbackground => $widget->cget('-foreground'))
 		if ($widget->class eq 'Entry' || $widget->class eq 'Text');
    }

    my ($child);
    foreach $child ($widget->children)
    {
	&setColors($child, $override);
    }
}

##############################################################################
#
# Glue routines
#
##############################################################################

sub getFullName
{
    my ($name, $conduits) = @_;

    if (exists($conduits->{$name}{"version"}))
    {
	my ($version) = $conduits->{$name}{"version"};
	return "$name, v$version";
    }

    return "";
}

sub quit
{
    my ($conduit);
    foreach $conduit (keys %{$PREFS->{"ActiveConduits"}},
		      keys %{$PREFS->{"InactiveConduits"}})
    {
	$conduit->conduitQuit();
    }

    &savePrefs;
    exit;
}

sub loadPrefs
{
    my ($upgraded);

    if (-f $RCFILE)
    {
	do "$RCFILE";
    }

    $PREFS->{'gPort'} = '/dev/ttya'
	unless (exists $PREFS->{'gPort'});
    $PREFS->{'gRate'} = '9600'
	unless (exists $PREFS->{'gRate'});
    $PREFS->{'gUseColors'} = 1
	unless (exists $PREFS->{'gUseColors'});

    if (!exists $PREFS->{"colors"})
    {
	$PREFS->{"colors"} = 
	{
		'Default' =>
		{ 
		    'foreground' => 'red4',
		    'background' => '#e5d897',
		    'activeforeground' => '#D3D3D3', 
		    'activebackground' => 'wheat2',
		    'disabledforeground' => 'gray',
		    'disabledbackground' => 'darkgray',#'gray',
		    'highlightcolor' => 'black',
		    'highlightbackground' => '#e5d897',
		},
		
		'Scrollbar' => 
		{
		},

		'Frame' =>
		{
		},
		
		'Text' =>
		{
		    'foreground' => '#D3D3D3', # == lightgray (on my machine)
		    'background' => '#00008B', # == darkblue (on my machine) 
		},

		'Label' =>
		{
		    'foreground' => 'darkgreen',
		},

		'Button' =>
		{
		    'activeforeground' => 'red4',
		},

		'Listbox' =>
		{
		    'foreground' => '#D3D3D3', # == lightgray (on my machine)
		    'background' => '#00008B', # == darkblue (on my machine) 
		},

		'Checkbutton' =>
		{
		    'activeforeground' => 'red4',
		},

		'Radiobutton' =>
		{
		    'activeforeground' => 'red4',
		},

		'Menu' =>
		{
		    'activeforeground' => 'red4',
		},

		'Menubutton' =>
		{
		    'activeforeground' => 'red4',
		},

		'Entry' =>
		{
		    'foreground' => '#D3D3D3', # == lightgray (on my machine)
		    'background' => '#00008B',	# == darkblue (on my machine) 
		},
		
		'Scale' =>
		{
		    'activeforeground' => 'red4',
		},

		'Toplevel' =>
		{
		},
	};
    }

    if (!exists $PREFS->{"version"} or !defined $PREFS->{"version"})
    {
	$upgraded = 1;
    }
    elsif ($PREFS->{"version"} ne $VERSION)
    {
	$upgraded = 1;

	# Do a series of filters to bring prefs up to speed.
	#
	#my ($major, $minor) = split(/-/, $PREFS->{"version"}, 2);
    }

    if ($upgraded)
    {
	# Remove the size restraints on our geometry
	# because we've gone to a new version and the size
	# may be different.
	#
	$PREFS->{"propsGeometry"} =~ s/.*?\+/+/;
	$PREFS->{"mainGeometry"} =~ s/.*?\+/+/;
    }

    # Sanity check on our sizes
    #
    &checkMin(\$PREFS->{"mainGeometry"}, 580, 370);
    &checkMin(\$PREFS->{"propsGeometry"}, 430, 320);
}

sub checkMin
{
    my ($var, $x, $y) = @_;
    my (@opts);

    @opts = split(/[\+x]/, $$var);

    return if (@opts != 4);

    $opts[0] = $x if ($opts[0] < $x);
    $opts[1] = $y if ($opts[1] < $y);

    $$var = "$opts[0]x$opts[1]+$opts[2]+$opts[3]";
}

sub init
{
    my ($conduit, $info);

    srand(time() ^ ($$ + ($$ << 15)));

    if ($DEBUG)
    {
	$RCDIR = "$ENV{HOME}/.pilotmgr-debug" unless (defined $RCDIR);
	print "Debug: Using $RCDIR\n";
    }
    else
    {
	$RCDIR = "$ENV{HOME}/.pilotmgr" unless (defined $RCDIR);
    }

    eval 'use lib "$RCDIR"';	# put user modules at top of search list.

    $RCFILE = "$RCDIR/preferences";
    $LOGFILE = "$RCDIR/hotsync.log";

    $PREFS->{"ActiveConduits"} = {};
    $PREFS->{"InactiveConduits"} = {};

    &loadPrefs;

    # Locate all conduits.  Any ones that are not defined in
    # our conduit tables are put into the inactive list.
    #
    # A conduit is defined as a script that has the following
    # two lines in it:
    #   sub conduitInit
    #   sub conduitSync
    my ($file, $conduitName);
    my (@list); 

    foreach $file (<$BASEDIR/*.pm>, <$RCDIR/*.pm>)
    {
	push(@list, $conduitName) if ($conduitName = &isConduit($file));
    }

    # Change dir to our resource dir.  All conduits expect
    # to be in this dir when started.  Also required for loading conduits
    # placed in this dir ($RCDIR is not in @INC, but "." is).
    #
    mkdir($RCDIR, 0755)
	unless (-d $RCDIR);
    chdir($RCDIR);

    &loadConduits(\@list);

    my ($key);
    foreach $key (keys %{$PREFS->{"ActiveConduits"}})
    {
	if (!grep($_ eq $key, @list))
	{
	    print "Conduit '$key' cannot be found...\n";
	    delete $PREFS->{"ActiveConduits"}->{$key};
	    @{$PREFS->{"ActiveOrder"}} = 
		grep($_ ne $key, @{$PREFS->{"ActiveOrder"}});
	}
	elsif (!grep($_ eq $key, @{$PREFS->{"ActiveOrder"}}))
	{
	    # an active conduit got lost somehow from order list
	    push(@{$PREFS->{"ActiveOrder"}}, $key);
	}
    }

    foreach $key (keys %{$PREFS->{"InactiveConduits"}})
    {
	unless (grep($_ eq $key, @list))
	{
	    print "Conduit '$key' cannot be found...\n";
	    delete $PREFS->{"InactiveConduits"}->{$key};
	    @{$PREFS->{"ActiveOrder"}} = 
		grep($_ ne $key, @{$PREFS->{"ActiveOrder"}});
	}
    }

    if (!exists($PREFS->{"pcid"}) || !defined($PREFS->{"pcid"}) ||
	$PREFS->{"pcid"} == 0)
    {
	$PREFS->{"pcid"} = rand(2147483648) + 1;
    }

    if (!exists($PREFS->{"ActiveOrder"}) || !defined($PREFS->{"ActiveOrder"}))
    {
	@{$PREFS->{"ActiveOrder"}} = keys %{$PREFS->{"ActiveConduits"}};
    }
}

sub isConduit
{
    my ($file) = @_;

    if (open(FD, "<$file"))
    {
	my (@lines) = grep(/^(package|sub conduit(Init|Sync))/, <FD>);
	close(FD);
	if (@lines == 3)
	{
	    $lines[0] =~ /^package\s+(\S+);/;
	    return $1;
	}
    }
    return undef;
}

sub loadConduits
{
    my ($list, $status) = @_;
    my ($pkgname);

    foreach $pkgname (@$list)
    {
	eval "use $pkgname";
	if ($@)
	{
	    $status->{$pkgname} = 1 if (defined $status);

	    print "v" x 30, " ERROR ", "v" x 30, "\n";
	    print "Unable to load conduit '$pkgname'\n";
	    print "$pkgname has been removed from the conduit lists\n";
	    print "Details of the error:\n";
	    print "$@\n";
	    print "^" x 30, " ERROR ", "^" x 30,
		  "\nTo skip loading $pkgname in future execute this command:",
		  "\n% mv $pkgname.pm $pkgname.pm-\n";

	    # Remove it from the system
	    my (%sym);
	    delete $INC{"$pkgname.pm"};
	    *sym = "${pkgname}::";
	    undef %sym;

	    # Remove it from the conduit lists
	    #
	    if (exists $PREFS->{"ActiveConduits"}->{$pkgname})
	    {
		delete $PREFS->{"ActiveConduits"}->{$pkgname};
	    }

	    if (exists $PREFS->{"InactiveConduits"}->{$pkgname})
	    {
		delete $PREFS->{"InactiveConduits"}->{$pkgname};
	    }

	    @{$PREFS->{"ActiveOrder"}} = 
		grep($_ ne $pkgname, @{$PREFS->{"ActiveOrder"}});
	}
	else
	{
	    $status->{$pkgname} = 0 if (defined $status);

	    $pkgname->conduitInit();

	    # If the conduit isn't on either Active or Inactive lists,
	    # put it on the inactive list.
	    #
	    if (exists $PREFS->{"ActiveConduits"}->{$pkgname})
	    {
		$PREFS->{"ActiveConduits"}->{$pkgname} =
		    $pkgname->conduitInfo();
	    }
	    else
	    {
		unless (exists $PREFS->{"InactiveConduits"}->{$pkgname})
		{
		    print "New conduit '$pkgname' added to the inactive " .
			"conduit list\n";
		}
		
		$PREFS->{"InactiveConduits"}->{$pkgname} =
		    $pkgname->conduitInfo();
	    }

	    my $wdir = "$RCDIR/$pkgname";
	    unless (-d $wdir)
	    {
		# Can't use msg() here, the window hasn't been created yet!
		#
		mkdir($wdir, 0755) or
		    print STDERR "Unable to create $wdir\n";
	    }
	}
    }
}

sub loadNewConduits
{
    # Create GUI if needed
    &createNewConduitsGui
	unless (defined $gNewConduits and $gNewConduits->Exists);

    # Update conduit list.  Only show the GUI if we have anything on the list.
    if (&updateNewConduitsGui)
    {
	$gNewConduits->Popup(-popanchor => 'c', -popover => $gWm,
			     -overanchor => 'c');
	$gNewConduits->grab;
    } else {
	$gNewConduits->withdraw;
	&tellUser("No new conduits to load");
    }
}

sub _loadNewConduits
{
    my ($load) = @_;

    if ($load)
    {
	my ($list, $status, $conduit) = ([], {});

	# Get selected conduits
	foreach ($gNewConduitList->curselection)
	{
	    $conduit = $gNewConduitList->get($_);
	    push(@$list, $conduit);
	}

	# Load selected conduits
	&loadConduits($list, $status);

	# Update GUI things
	&updateConduitLists;
	&updateMenus;

	# Tell user what happened
	foreach (@$list)
	{
	    msg("Conduit '$_' ",
		$status->{$_} ? 'not loaded due to errors.'
			      : 'has been loaded.');
	}
    }

    # Make conduit list window go away
    $gNewConduits->grabRelease;
    $gNewConduits->withdraw;
}

sub createNewConduitsGui
{
    my ($frame, $obj, $vscroll);

    # Create GUI list
    $gNewConduits = $gWm->Toplevel(-title => 'New Conduits List');
    $gNewConduits->withdraw;
    $gNewConduits->transient($gWm);

    $frame = $gNewConduits->Frame(-relief => 'ridge', -bd => 2);

    $vscroll = $frame->Scrollbar(-orient => 'vert');
    $vscroll->pack(-side => 'right', -fill => 'y');

    $gNewConduitList = $frame->Listbox(-yscrollcommand => [$vscroll => 'set'],
				       -selectmode => 'multiple');
    $vscroll->configure(-command => [$gNewConduitList => 'yview']);
    $gNewConduitList->pack(-side => 'top');

    $frame->pack(-side => 'top');
    $frame = $gNewConduits->Frame(-bd => 2);

    $obj = $frame->Button(-text => 'Load',
			  -command => sub { &_loadNewConduits(1); });
    $obj->pack(-side => 'left');

    $obj = $frame->Button(-text => 'Cancel',
			  -command => sub { &_loadNewConduits(0); });
    $obj->pack;

    $frame->pack;
    &setColors($gNewConduits);
}

sub updateNewConduitsGui
{
    my ($conduitName, $file, @allConduits, @newConduits);

    # Assemble a list of all the known conduits to make it easier
    # to lookup this information
    @allConduits = sort(keys %{$PREFS->{"InactiveConduits"}},
			keys %{$PREFS->{"ActiveConduits"}});

    # Search directory for new conduits
    foreach $file (<$BASEDIR/*.pm>, <$RCDIR/*.pm>)
    {
	push(@newConduits, $conduitName)
	    if ($conduitName = &isConduit($file) and
		!grep(/$conduitName/, @allConduits));
    }

    # Remove old list and create new one
    $gNewConduitList->delete(0, "end");
    $gNewConduitList->insert("end", sort @newConduits);

    return scalar(@newConduits);
}

sub savePrefs
{
    my ($var);

    $Data::Dumper::Purity = 1;
    $Data::Dumper::Deepcopy = 1;
    $Data::Dumper::Indent = 1;

    $PREFS->{"mainGeometry"} = $gWm->geometry unless (defined $MODE);
    $PREFS->{"version"} = $VERSION;
    if (defined($gPropsDialog) && $gPropsDialog->Exists)
    {
	$PREFS->{"propsGeometry"} = $gPropsDialog->geometry;
    }

    if (open(FD, ">$RCFILE"))
    {
	if (defined &Data::Dumper::Dumpxs)
	{
	    print FD Data::Dumper->Dumpxs([$PREFS], ['PREFS']);
	}
	else
	{
	    print FD Data::Dumper->Dump([$PREFS], ['PREFS']);
	}

	print FD "1;\n";
	close(FD);
    }
    else
    {
	print "Unable to save preferences to $RCFILE!\n";
    }
    
}

##############################################################################
#
# Sync routines
#
##############################################################################

sub hotSync
{
    my ($conduit, $key, $retries);
    my ($socket, $dlp);

    &cycleLogs;

    if ($PREFS->{'gPort'} =~ m|^/| &&
	!(-r $PREFS->{'gPort'} && -w $PREFS->{'gPort'}))
    {
	msg("Error: Don't have read/write permissions on $PREFS->{gPort}!\n" .
	    "(On Solaris owner/group/perms should be root/sys/666)");
	return;
    }

    msg("Please press the Hotsync button on your Pilot cradle");

    $CANCEL = 0;

    # Start trying to connect.
    #
    eval
    {
	$ENV{"PILOTRATE"} = $PREFS->{"gRate"};
	$socket = PDA::Pilot::openPort($PREFS->{"gPort"});
    };
    if ($@)
    {
	msg("Error: $@\n");
	return;
    }

    # Try to accept 3 times, each time with a timeout of 10 seconds.
    #
    $retries = 3;
    while (1)
    {
	$retries--;

	$gWm->update unless (defined $MODE);

	my ($err);
	
	eval
	{
	    $SIG{'ALRM'} = sub{ croak("alarm") };
	    alarm(10) unless ($MODE eq 'DAEMON');

	    $dlp = PDA::Pilot::accept($socket);
	};

	alarm(0);

	$gWm->update unless (defined $MODE);

	if ($dlp)
	{
	    msg("Connected.");
	    last;
	}
	else
	{
	    if ($CANCEL)
	    {
		msg("Hotsync cancelled");
		$dlp->log("Hotsync cancelled")
		    if ($dlp);
		$CANCEL = 0;
		PDA::Pilot::close($socket);
		return;
	    }

	    if ($retries == 0)
	    {
		msg("Unable to connect to the Pilot.  Sync aborted.");
		PDA::Pilot::close($socket);
		return;
	    }

	    #
	    # Otherwise, keep trying.
	}
    }

    # If this fails, the user most likely cancelled on the 
    # Pilot side.
    #
    &fullStatus("Pilot Manager", "Retrieving User Information", 0);
    eval
    {
	$userInfo = $dlp->getUserInfo();
    };
    if ($@)
    {
	msg("Synchronization cancelled on Pilot\n");
	eval
	{
	    $dlp->close();
	    PDA::Pilot::close($socket);
	};
	return;
    }

    $SIG{'PIPE'} = 'IGNORE';
    $dlp->log("Hotsync with PilotManager\n" .
		     "Details reported in PilotManager log\n\n");

    # Check the user information to see if the Pilot has been
    # reset or if it's the wrong Pilot for our setup.
    #
    if ($userInfo->{"userID"} == 0 && $userInfo->{"lastSyncPC"} == 0)
    {
	# A hard reset has happened.
	#
	&watchdog($dlp, 1);
	&tellUser("This Pilot has been reset or has never been synced.  ".
		  "Most conduits will sync properly, however you will ".
		  "need to restore your databases from your backups using ".
		  "the Installer conduit.");

	if (exists $PREFS->{"userinfo"})
	{
	    # Ask user whether to restore a previous username/id values
	    my $ans = 
		&askUser("PilotManager was previously synced with\n\n\t".
			 "'$PREFS->{userinfo}->{name}'".
			 "\n\tUnique ID: $PREFS->{userinfo}->{userID}\n\n".
			 "Do you wish to restore these settings to this ".
			 "pilot or enter a new name?",
			 "New Name", "Restore");

	    if ($ans eq "Restore")
	    {
		$userInfo->{"name"} = $PREFS->{"userinfo"}->{"name"};
		$userInfo->{"userID"} = $PREFS->{"userinfo"}->{"userID"};
	    }
	}

	&watchdog($dlp, 0);

	# Trigger all conduits to do a full sync.
	#
	$userInfo->{"successfulSyncDate"} = 0;
    }

    # If the username is not defined, request it from 
    # the user.
    if ($userInfo->{"name"} eq "")
    {
	$userInfo->{"name"} = &getUserName;
	$userInfo->{"userID"} = rand(2147483648) + 1;
    }

    if (exists($PREFS->{"userinfo"}))
    {
	# Check to make sure this is the right user
	#
	if ($PREFS->{"userinfo"}->{"userID"} ne $userInfo->{"userID"})
	{
	    &watchdog($dlp, 1);
	    my ($ans) = 
		&askUser("Your Pilot belongs to\n\n\t'$userInfo->{name}'".
			 "\n\tUnique ID: $userInfo->{userID}".
			 "\n\nbut PilotManager is expecting\n\n\t".
			 "'$PREFS->{userinfo}->{name}'".
			 "\n\tUnique ID: $PREFS->{userinfo}->{userID}\n\n".
			 "If this is an ok match, click 'Proceed' and ".
			 "PilotManager will be configured to match the ".
			 "Pilot.  However, be ".
			 "warned that if you sync somebody else\'s Pilot ".
			 "with your PilotManager configuration very bad ".
			 "things will happen!", "Proceed", "Cancel");
	    &watchdog($dlp, 0);

	    if ($ans ne "Proceed")
	    {
		$gStatusWindow->withdraw
		    if (defined($gStatusWindow) && $gStatusWindow->Exists);
		msg("Hotsync cancelled");
		$dlp->log("Hotsync cancelled");
		eval
		{
		    $dlp->close();
		    PDA::Pilot::close($socket);
		};
		return;
	    }
	}
    }

    # Need to do a full sync if they last sync'd on a 
    # different machine.
    #
    if ($userInfo->{"lastSyncPC"} != $PREFS->{"pcid"})
    {
	$userInfo->{"lastSyncPC"} = $PREFS->{"pcid"};

	# Trigger all conduits to do a full sync.
	#
	$userInfo->{"successfulSyncDate"} = 0;
    }

    # Configure PilotManager to use whatever the Pilot provides
    #
    $PREFS->{"userinfo"} = $userInfo;

    # Set the "official" time of this sync.
    #
    $userInfo->{"thisSyncDate"} = time;

    $PREFS->{"databases"} = &loadDBList($dlp);

    # Call each conduit in turn
    #
    foreach $conduit (@{$PREFS->{"ActiveOrder"}})
    {
	last if ($CANCEL);

	fullStatus($conduit, "", 0);

	# Damage control in case a conduit was irresponsible
	#
	chdir($RCDIR);
	$dlp->tickle;

	eval
	{
	    msg("Synchronizing using the $conduit conduit");
	    $conduit->conduitSync($dlp, $userInfo);
	};
	if ($@)
	{
	    last if ($CANCEL);
	    msg("$conduit did not complete cleanly.\nError $@\n".
		"Trying to continue.");
	}

	$dlp->watchdog(0);
    }
    $gStatusWindow->withdraw
	if (defined($gStatusWindow) && $gStatusWindow->Exists);

    if ($CANCEL)
    {
	msg("Synchronization cancelled.\n");
	$CANCEL = 0;
    }
    else
    {
	# Whatever 'lastSyncDate' is set to when you close the 
	# connection is what 'successfulSyncDate' is set to when
	# you reopen.  Provided that the close goes cleanly.
	#
	$userInfo->{"lastSyncDate"} = $userInfo->{"thisSyncDate"};

	msg("Synchronization complete");
    }

    eval
    {
	$dlp->setUserInfo($userInfo);
    };
    if ($@)
    {
	print $@;
	msg("Error writing user info (this is bad, but not fatal)");
    }

    $dlp->close();
    PDA::Pilot::close($socket);
}

sub getDatabaseList
{
    if (exists($PREFS->{"databases"}) &&
	defined($PREFS->{"databases"}))
    {
	return @{$PREFS->{"databases"}};
    }
    else
    {
	return ();
    }
}

sub getUserName
{
    my ($win, @frames, $obj, $name, $done);

    if (defined $MODE)
    {
	# not in gui mode
	for ($name=''; !length $name;)
	{
	    print "Your Pilot is unlabelled.\nPlease enter your name: ";
	    chomp($name = <STDIN>);
	}
	return $name;
    }

    $win = $gWm->Toplevel(-title => "Identify your Pilot");
    $win->withdraw;
    $frames[0] = $win->Frame;

    $obj = TkUtils::Label($frames[0], 
			  "Your Pilot is unlabelled.\n".
			  "Please enter your name");
    $obj->pack;

    $obj = TkUtils::Entry($frames[0], \$name);
    $obj->bind("<Return>", sub{ $win->grabRelease;
				$win->destroy });
    $obj->pack;

    $obj = TkUtils::Button($frames[0], "Ok", sub{ $win->grabRelease;
						  $win->destroy });
    $obj->pack;

    $frames[0]->pack;

    &setColors($win);

    $win->Popup;
    $win->grab;
    $win->update;
    $win->waitWindow;

    return $name;
}

sub status
{
    return unless ($PREFS->{"gShowConduitStatus"});

    if (!defined($gStatusWindow) || !$gStatusWindow->Exists())
    {
	my (@frames, $obj);

	$gStatusWindow = $gWm->Toplevel(-title => "Conduit Status");
	$gStatusWindow->withdraw;
	$gStatusWindow->transient($gWm);

	$frames[0] = $gStatusWindow->Frame(-relief => 'ridge', -bd => '2');

	$gStatus->{"conduit"}->{"widget"} = TkUtils::Label($frames[0], "");
	$gStatus->{"conduit"}->{"widget"}->pack(-side => 'top',
						-anchor => 'center');

	$gStatus->{"message"}->{"widget"} = TkUtils::Label($frames[0], "");
	$gStatus->{"message"}->{"widget"}->pack(-side => 'top',
						-anchor => 'center');
	
	$gStatus->{"percent"}->{"widget"} =
	    $frames[0]->Canvas(-height => 20,
			       -width => 202);

	$gStatus->{"percent"}->{"widget"}->
	    create("rectangle",
		   0, 0, 202, 20,
		   -fill => 'black',
		   -tags => 'border');

	$gStatus->{"percent"}->{"widget"}->
	    create("rectangle",
		   0, 0, 0, 20,
		   -fill => 'gray',
		   -tags => 'rect');

	$gStatus->{"percent"}->{"widget"}->pack(-side => 'top',
						-padx => 4,
						-anchor => 'center');

	$frames[0]->pack(-side => 'top',
			 -expand => 'true',
			 -fill => 'both');
				     
	$obj = TkUtils::Button($gStatusWindow, "Dismiss", 
			       sub{ $gStatusWindow->withdraw; });
	
	&setColors($gStatusWindow);
	$gStatusWindow->geometry("250x100");
    }

    $gStatus->{"message"}->{"value"} = $_[0];
    my ($perc) = $_[1];

    $perc = 100 if ($perc > 100);
    $perc = 0 if ($perc < 0);

    $gStatus->{"percent"}->{"value"} = $perc;

    $gStatus->{"percent"}->{"widget"}->
	coords("rect", 0, 0,
	       int(202 * $gStatus->{"percent"}->{"value"} / 100), 20);

    $gStatus->{"conduit"}->{"widget"}->
	configure(-text => $gStatus->{"conduit"}->{"value"});

    $gStatus->{"message"}->{"widget"}->
	configure(-text => $gStatus->{"message"}->{"value"});

				
    if (!$gStatusWindow->IsMapped)
    {
	$gStatusWindow->Popup;
    }

    $gStatusWindow->update;
}

sub fullStatus
{
    $gStatus->{"conduit"}->{"value"} = shift;
    &status;			# Pass the stack along
}


sub cancel
{
    # We're getting this in the event thread -- that means
    # that a sync is going on in hotsync().  
    #
    # Tell the conduit to cancel and hope for the best.
    # Meanwhile, set the global CANCEL flag so that the
    # hotsync stops.
    #
    $CANCEL = 1;

    eval
    {
	$gStatus->{"conduit"}->{"value"}->conduitCancel();
    };

    $gStatus->{"conduit"}->{"value"} = "Cancelling, please wait";
    $gStatusWindow->update
	if (defined($gStatusWindow) && $gStatusWindow->Exists);
    $gCancel->configure(-state => "disabled");
}

sub msg
{
    my ($buf) = (join('', @_));
    my ($pad);
    my ($time);

    chomp($buf);

    if (defined($PREFS->{"gDateStamp"}) || $PREFS->{"gDateStamp"})
    {
	$time = &prettyTime(time);
	$time .= "   ";
    }
    else
    {
	$time = "";
    }

    $pad = " " x length($time);
    $buf =~ s/\n/\n$pad/g;

    $buf = "$time$buf";

    if (defined $MODE)
    {
	# Command line sync
	#
	print "$buf\n";
    }
    else
    {
	# Normal gui sync
	#
	&guiMessage($buf);
    }

    if (open(FD, ">>$LOGFILE"))
    {
	print FD "$buf\n";
	close(FD);
    }
}

sub askUser
{
    my ($question, @answers) = @_;
    my ($dialog, $chk);

    unless (defined $MODE)
    {
	$dialog = $gWm->Dialog(
			   -title  => "Riddle me this...",
			   -text   => $question,
			   -bitmap => 'question',
			   -default_button => $answers[0],
			   -buttons => [@answers]
			   );
	$dialog->configure(-wraplength => '4i');
	$dialog->transient($gWm);
	&setColors($dialog);
	return $dialog->Show;
    }
    else
    {
	print "----------\n$question\n";
	while (1)
	{
	    print '[', join('/', @answers), ']: ';
	    chomp($dialog = <STDIN>);
	    foreach $chk (@answers)
	    {
		if ($dialog =~ /^$chk$/i)
		{
		    print "----------\n";
		    return $chk;
		}
	    }
	}
    }
}

sub tellUser
{
    my ($msg) = @_;
    my ($dialog);

    unless (defined $MODE)
    {
	$dialog = $gWm->Dialog(
			   -title  => "Pay attention!",
			   -text   => $msg,
			   -bitmap => 'info',
			   -default_button => "Ok",
			   -buttons => ["Ok"]
			   );
	$dialog->configure(-wraplength => '4i');
	$dialog->transient($gWm);
	&setColors($dialog);
	return $dialog->Show;
    }
    else
    {
	print "----------\n$msg\n----------\n";
	return "Ok";
    }
}

# Stolen from ctime.pl by Waldemar Kebsch (kebsch.pad@nixpbe.UUCP)
# and renamed to 'prettyTime'
#
sub prettyTime
{
    my ($time) = @_;
    my(@DoW) = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
    my(@MoY) = ('Jan','Feb','Mar','Apr','May','Jun',
		'Jul','Aug','Sep','Oct','Nov','Dec');

    my($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);

    # Determine what time zone is in effect.
    # Use GMT if TZ is defined as null, local time if TZ undefined.
    # There's no portable way to find the system default timezone.

    my($TZ) = defined($ENV{'TZ'}) ? ( $ENV{'TZ'} ? $ENV{'TZ'} : 'GMT' ) : '';
    ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
        ($TZ eq 'GMT') ? gmtime($time) : localtime($time);

    # Hack to deal with 'PST8PDT' format of TZ
    # Note that this can't deal with all the esoteric forms, but it
    # does recognize the most common: [:]STDoff[DST[off][,rule]]

    if($TZ=~/^([^:\d+\-,]{3,})([+-]?\d{1,2}(:\d{1,2}){0,2})([^\d+\-,]{3,})?/){
        $TZ = $isdst ? $4 : $1;
    }
    $TZ .= ' ' unless $TZ eq '';

    $mon++;
    return sprintf("%02d/%02d/%04d %2d:%02d:%02d",
		   $mon, $mday, $year + 1900, $hour, $min, $sec);
}

sub loadDBList
{
    my ($dlp) = @_;
    my ($result, $i) = ([], 0);
    my ($count, $count_max, $rec);

    fullStatus("Pilot Manager", "Refreshing Database List", 0);
    $count = 0;
    if (exists($PREFS->{"databases"}) && defined($PREFS->{"databases"}))
    {
	$count_max = @{$PREFS->{"databases"}};
    }
    else
    {
	$count_max = 0;
    }

    eval
    {
	do
	{
	    status("Refreshing Database List", 
		   int(100 * $count++ / $count_max)) if ($count_max);
	    $rec = $dlp->getDBInfo($i,1,0);
	    push(@$result, $rec) if (exists $rec->{"name"} and $rec->{"name"});
	    $i = $rec->{"index"}+1;
	}
	while ($rec->{"more"});
    };

    fullStatus("Pilot Manager", "Refreshing Database List", 100);

    return $result;
}

sub watchdog
{
    my ($dlp, $which) = @_;

    if ($which)
    {
	$dlp->watchdog(20);
    }
    else
    {
	$dlp->watchdog(0);
    }

    return;
}

sub cycleLogs
{
    if (-f $LOGFILE && (stat($LOGFILE))[7] > $LOGFILE_THRESHOLD)
    {
	rename($LOGFILE, $LOGFILE . ".old");
    }
}

# Thanks to Charles LaBrec <Charles.Labrec@East.Sun.Com>
# for finding this bug.
#
sub checkTimeBug
{
    my(@tm1) = (0, 0, 0, 1, 0, 97);
    my($time) = timelocal(@tm1);
    my(@tm2) = localtime($time);

    return (@tm1[0..5] != @tm2[0..5]);
}


##############################################################################
#
# Main code
#
##############################################################################

&init;
&createGUI unless (defined $MODE);

if (!exists($PREFS->{"seenWelcome"}) || $PREFS->{"seenWelcome"} == 0)
{
    if (!defined $MODE)
    {
	if (&showDoc("docs/WelcomeMessage", "Welcome New Users!"))
	{
	    $PREFS->{"seenWelcome"} = time;
	}
    }
    else
    {
	if(open(FD, "<$BASEDIR/docs/WelcomeMessage"))
	{
	    print "Welcome New Users!\n\n", <FD>;
	    close(FD);
	    $PREFS->{"seenWelcome"} = time;
	    print "[Press Return to Continue]\n";
	    scalar(<STDIN>);
	}
    }
}

if (&checkTimeBug)
{
    my $noteText =
	"Congratulations!  Your OS has a bug in the time of day ".
	"code.  This bug causes dates to slowly travel backwards in time ".
	"and interferes with PilotManager's performance.  This bug is ".
	"caused by having a bad timezone environment variable setting. ".
	"Your timezone is set to\n\n\t$ENV{TZ}\n\nYou might try setting ".
	"it to a more specific timezone, for example US/Pacific maps ".
	"to:\n\n\tPST8PDT\n\n" .
	"You'll need to set the correct value for your time zone, of ".
	"course.\n\nPilotManager will not function until this is fixed.".
	"\n(This is NOT a bug in PilotManager!)";

    if (!defined $MODE)
    {
	$gHotSyncButton->configure(-state => 'disabled');
	&tellUser($noteText);
    }
    else
    {
	print "$noteText\n";
	exit;
    }
}

if (!defined $MODE)
{
    # Normal GUI mode
    #
    Tk::MainLoop;
}
elsif ($MODE eq 'CMDLINE')
{
    # Start full sync from command line
    #
    my $saveStatus = $PREFS->{"gShowConduitStatus"};

    $PREFS->{"gShowConduitStatus"} = 0;
    &hotSync;
    $PREFS->{"gShowConduitStatus"} = $saveStatus;
    &quit;
}
elsif ($MODE eq 'DAEMON')
{
    # Start full sync from command line and loop forever
    # XXX Should check we aren't already running before we do this
    #
    my ($saveStatus, $pid) = ($PREFS->{"gShowConduitStatus"});
    unless ($pid = fork)
    {
	unless (fork)
	{
	    $PREFS->{"gShowConduitStatus"} = 0;
	    while (1)
	    {
		&hotSync;
	    }
	    $PREFS->{"gShowConduitStatus"} = $saveStatus;
	}
	exit 0;
    }
    waitpid($pid, 0);
}
else
{
    # Start sync with specified conduit(s) from command line
    #
    my ($saveOrder, $saveStatus, $con) = ($PREFS->{"ActiveOrder"},
					  $PREFS->{"gShowConduitStatus"});

    $PREFS->{"gShowConduitStatus"} = 0;
    $PREFS->{"ActiveOrder"} = [];
    foreach $con (@$MODE)
    {
	if (defined $PREFS->{"ActiveConduits"}->{$con} ||
	    defined $PREFS->{"InactiveConduits"}->{$con})
	{
	    push(@{$PREFS->{"ActiveOrder"}}, $con);
	}
	else
	{
	    print "Conduit '$con' not found.\n";
	}
    }
    if (@{$PREFS->{"ActiveOrder"}})
    {
	&hotSync;
	$PREFS->{"ActiveOrder"} = $saveOrder;
	$PREFS->{"gShowConduitStatus"} = $saveStatus;
	&quit;
    }
    else
    {
	print "No valid conduits found.  Sync aborted.\n";
    }
}