summaryrefslogtreecommitdiff
path: root/src/syncevo/Cmdline.cpp
blob: b0e1cda1e59fabd7e335160d7909090492ef74f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
/*
 * Copyright (C) 2008-2009 Patrick Ohly <patrick.ohly@gmx.de>
 * Copyright (C) 2009 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include <syncevo/Cmdline.h>
#include <syncevo/CmdlineSyncClient.h>
#include <syncevo/FilterConfigNode.h>
#include <syncevo/VolatileConfigNode.h>
#include <syncevo/IniConfigNode.h>
#include <syncevo/SyncSource.h>
#include <syncevo/SyncContext.h>
#include <syncevo/util.h>
#include <syncevo/SuspendFlags.h>
#include "test.h"

#include <synthesis/SDK_util.h>

#include <unistd.h>
#include <errno.h>

#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
#include <set>
#include <list>
#include <algorithm>
using namespace std;

#include <boost/shared_ptr.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <boost/range.hpp>
#include <fstream>

#include <syncevo/declarations.h>
using namespace std;
SE_BEGIN_CXX

// synopsis and options char strings
#include "CmdlineHelp.c"

Cmdline::Cmdline(int argc, const char * const * argv) :
    m_argc(argc),
    m_argv(argv),
    m_validSyncProps(SyncConfig::getRegistry()),
    m_validSourceProps(SyncSourceConfig::getRegistry())
{}

Cmdline::Cmdline(const vector<string> &args) :
    m_args(args),
    m_validSyncProps(SyncConfig::getRegistry()),
    m_validSourceProps(SyncSourceConfig::getRegistry())
{
    m_argc = args.size();
    m_argvArray.reset(new const char *[args.size()]);
    for(int i = 0; i < m_argc; i++) {
        m_argvArray[i] = m_args[i].c_str();
    }
    m_argv = m_argvArray.get();
}

Cmdline::Cmdline(const char *arg, ...) :
    m_validSyncProps(SyncConfig::getRegistry()),
    m_validSourceProps(SyncSourceConfig::getRegistry())
{
    va_list argList;
    va_start(argList, arg);
    for (const char *curr = arg;
         curr;
         curr = va_arg(argList, const char *)) {
        m_args.push_back(curr);
    }
    va_end(argList);
    m_argc = m_args.size();
    m_argvArray.reset(new const char *[m_args.size()]);
    for (int i = 0; i < m_argc; i++) {
        m_argvArray[i] = m_args[i].c_str();
    }
    m_argv = m_argvArray.get();
}

bool Cmdline::parse()
{
    vector<string> parsed;
    return parse(parsed);
}

/**
 * Detects "--sync foo", "--sync=foo", "-s foo".
 */
static bool IsKeyword(const std::string arg,
                      const char *longWord,
                      const char *shortWord)
{
    return boost::istarts_with(arg, std::string(longWord) + "=") ||
        boost::iequals(arg, longWord) ||
        boost::iequals(arg, shortWord);
}

bool Cmdline::parse(vector<string> &parsed)
{
    parsed.clear();
    if (m_argc) {
        parsed.push_back(m_argv[0]);
    }
    m_delimiter = "\n\n";

    // All command line options which ask for a specific operation,
    // like --restore, --print-config, ... Used to detect conflicting
    // operations.
    vector<string> operations;

    int opt = 1;
    bool ok;
    while (opt < m_argc) {
        parsed.push_back(m_argv[opt]);
        if (boost::iequals(m_argv[opt], "--")) {
            // separator between options and <config> <source>:
            // swallow it and leave option parsing
            opt++;
            break;
        }
        if (m_argv[opt][0] != '-') {
            if (strchr(m_argv[opt], '=')) {
                // property assignment
                if (!parseProp(UNKNOWN_PROPERTY_TYPE,
                               NULL,
                               m_argv[opt],
                               NULL)) {
                    return false;
                } else {
                    opt++;
                    continue;
                }
            } else {
                break;
            }
        }
        if (IsKeyword(m_argv[opt], "--sync", "-s")) {
            if (!parseAssignment(opt, parsed, SOURCE_PROPERTY_TYPE, "sync", NULL)) {
                return false;
            }

            // disable requirement to add --run explicitly in order to
            // be compatible with traditional command lines
            m_run = true;
        } else if (IsKeyword(m_argv[opt], "--keyring", "-k")) {
            if (!parseAssignment(opt, parsed, SYNC_PROPERTY_TYPE, "keyring", "true")) {
                return false;
            }
        } else if(boost::iequals(m_argv[opt], "--sync-property") ||
                  boost::iequals(m_argv[opt], "-y")) {
                opt++;
                if (!parseProp(SYNC_PROPERTY_TYPE,
                               m_argv[opt - 1], opt == m_argc ? NULL : m_argv[opt])) {
                    return false;
                }
                parsed.push_back(m_argv[opt]);
        } else if(boost::iequals(m_argv[opt], "--source-property") ||
                  boost::iequals(m_argv[opt], "-z")) {
            opt++;
            if (!parseProp(SOURCE_PROPERTY_TYPE,
                           m_argv[opt - 1], opt == m_argc ? NULL : m_argv[opt])) {
                return false;
            }
            parsed.push_back(m_argv[opt]);
        }else if(boost::iequals(m_argv[opt], "--template") ||
                  boost::iequals(m_argv[opt], "-l")) {
            opt++;
            if (opt >= m_argc) {
                usage(false, string("missing parameter for ") + cmdOpt(m_argv[opt - 1]));
                return false;
            }
            parsed.push_back(m_argv[opt]);
            m_template = m_argv[opt];
            m_configure = true;
            string temp = boost::trim_copy (m_template);
            if (temp.find ("?") == 0){
                m_printTemplates = true;
                m_dontrun = true;
                m_template = temp.substr (1);
            }
        } else if(boost::iequals(m_argv[opt], "--print-databases")) {
            operations.push_back(m_argv[opt]);
            m_printDatabases = true;
        } else if(boost::iequals(m_argv[opt], "--create-database")) {
            operations.push_back(m_argv[opt]);
            m_createDatabase = true;
        } else if(boost::iequals(m_argv[opt], "--remove-database")) {
            operations.push_back(m_argv[opt]);
            m_removeDatabase = true;
        } else if(boost::iequals(m_argv[opt], "--print-servers") ||
                  boost::iequals(m_argv[opt], "--print-peers") ||
                  boost::iequals(m_argv[opt], "--print-configs")) {
            operations.push_back(m_argv[opt]);
            m_printServers = true;
        } else if(boost::iequals(m_argv[opt], "--print-config") ||
                  boost::iequals(m_argv[opt], "-p")) {
            operations.push_back(m_argv[opt]);
            m_printConfig = true;
        } else if(boost::iequals(m_argv[opt], "--print-sessions")) {
            operations.push_back(m_argv[opt]);
            m_printSessions = true;
        } else if(boost::iequals(m_argv[opt], "--configure") ||
                  boost::iequals(m_argv[opt], "-c")) {
            operations.push_back(m_argv[opt]);
            m_configure = true;
        } else if(boost::iequals(m_argv[opt], "--remove")) {
            operations.push_back(m_argv[opt]);
            m_remove = true;
        } else if(boost::iequals(m_argv[opt], "--run") ||
                  boost::iequals(m_argv[opt], "-r")) {
            operations.push_back(m_argv[opt]);
            m_run = true;
        } else if(boost::iequals(m_argv[opt], "--restore")) {
            operations.push_back(m_argv[opt]);
            opt++;
            if (opt >= m_argc) {
                usage(false, string("missing parameter for ") + cmdOpt(m_argv[opt - 1]));
                return false;
            }
            m_restore = m_argv[opt];
            if (m_restore.empty()) {
                usage(false, string("missing parameter for ") + cmdOpt(m_argv[opt - 1]));
                return false;
            }
            //if can't convert it successfully, it's an invalid path
            if (!relToAbs(m_restore)) {
                usage(false, string("parameter '") + m_restore + "' for " + cmdOpt(m_argv[opt - 1]) + " must be log directory");
                return false;
            }
            parsed.push_back(m_restore);
        } else if(boost::iequals(m_argv[opt], "--before")) {
            m_before = true;
        } else if(boost::iequals(m_argv[opt], "--after")) {
            m_after = true;
        } else if (boost::iequals(m_argv[opt], "--print-items")) {
            operations.push_back(m_argv[opt]);
            m_printItems = m_accessItems = true;
        } else if ((boost::iequals(m_argv[opt], "--export") && (m_export = true)) ||
                   (boost::iequals(m_argv[opt], "--import") && (m_import = true)) ||
                   (boost::iequals(m_argv[opt], "--update") && (m_update = true))) {
            operations.push_back(m_argv[opt]);
            m_accessItems = true;
            opt++;
            if (opt >= m_argc || !m_argv[opt][0]) {
                usage(false, string("missing parameter for ") + cmdOpt(m_argv[opt - 1]));
                return false;
            }
            m_itemPath = m_argv[opt];
            if (m_itemPath != "-") {
                string dir, file;
                splitPath(m_itemPath, dir, file);
                if (dir.empty()) {
                    dir = ".";
                }
                if (!relToAbs(dir)) {
                    SyncContext::throwError(dir, errno);
                }
                m_itemPath = dir + "/" + file;
            }
            parsed.push_back(m_itemPath);
        } else if (boost::iequals(m_argv[opt], "--delimiter")) {
            opt++;
            if (opt >= m_argc) {
                usage(false, string("missing parameter for ") + cmdOpt(m_argv[opt - 1]));
                return false;
            }
            m_delimiter = m_argv[opt];
            parsed.push_back(m_delimiter);
        } else if (boost::iequals(m_argv[opt], "--delete-items")) {
            operations.push_back(m_argv[opt]);
            m_deleteItems = m_accessItems = true;
        } else if(boost::iequals(m_argv[opt], "--dry-run")) {
            m_dryrun = true;
        } else if(boost::iequals(m_argv[opt], "--migrate")) {
            operations.push_back(m_argv[opt]);
            m_migrate = true;
        } else if(boost::iequals(m_argv[opt], "--status") ||
                  boost::iequals(m_argv[opt], "-t")) {
            operations.push_back(m_argv[opt]);
            m_status = true;
        } else if(boost::iequals(m_argv[opt], "--quiet") ||
                  boost::iequals(m_argv[opt], "-q")) {
            m_quiet = true;
        } else if(boost::iequals(m_argv[opt], "--help") ||
                  boost::iequals(m_argv[opt], "-h")) {
            m_usage = true;
        } else if(boost::iequals(m_argv[opt], "--version")) {
            operations.push_back(m_argv[opt]);
            m_version = true;
        } else if (parseBool(opt, "--daemon", NULL, true, m_useDaemon, ok)) {
            if (!ok) {
                return false;
            }
        } else if(boost::iequals(m_argv[opt], "--monitor")||
                boost::iequals(m_argv[opt], "-m")) {
            operations.push_back(m_argv[opt]);
            m_monitor = true;
        } else if (boost::iequals(m_argv[opt], "--luids")) {
            // all following parameters are luids; can't be combined
            // with setting config and source name
            while (++opt < m_argc) {
                parsed.push_back(m_argv[opt]);
                m_luids.push_back(CmdlineLUID::toLUID(m_argv[opt]));
            }
        } else {
            usage(false, string(m_argv[opt]) + ": unknown parameter");
            return false;
        }
        opt++;
    }

    if (opt < m_argc) {
        m_server = m_argv[opt++];
        while (opt < m_argc) {
            parsed.push_back(m_argv[opt]);
            if (m_sources.empty() ||
                !m_accessItems) {
                m_sources.insert(m_argv[opt++]);
            } else {
                // first additional parameter was source, rest are luids
                m_luids.push_back(CmdlineLUID::toLUID(m_argv[opt++]));
            }
        }
    }

    // check whether we have conflicting operations requested by user
    if (operations.size() > 1) {
        usage(false, boost::join(operations, " ") + ": mutually exclusive operations");
        return false;
    }

    // common sanity checking for item listing/import/export/update
    if (m_accessItems) {
        if ((m_import || m_update) && m_dryrun) {
            usage(false, operations[0] + ": --dry-run not supported");
            return false;
        }
    }

    return true;
}

bool Cmdline::parseBool(int opt, const char *longName, const char *shortName,
                        bool def, Bool &value,
                        bool &ok)
{
    string option = m_argv[opt];
    string param;
    size_t pos = option.find('=');
    if (pos != option.npos) {
        param = option.substr(pos + 1);
        option.resize(pos);
    }
    if ((longName && boost::iequals(option, longName)) ||
        (shortName && boost::iequals(option, shortName))) {
        ok = true;
        if (param.empty()) {
            value = def;
        } else if (boost::iequals(param, "t") ||
                   boost::iequals(param, "1") ||
                   boost::iequals(param, "true") ||
                   boost::iequals(param, "yes")) {
            value = true;
        } else if (boost::iequals(param, "f") ||
              boost::iequals(param, "0") ||
              boost::iequals(param, "false") ||
              boost::iequals(param, "no")) {
            value = false;
        } else {
            usage(false, string("parameter in '") + m_argv[opt] + "' must be 1/t/true/yes or 0/f/false/no");
            ok = false;
        }
        // was our option
        return true;
    } else {
        // keep searching for match
        return false;
    }
}

bool Cmdline::isSync()
{
    // make sure command line arguments really try to run sync
    if (m_usage || m_version ||
        m_printServers || boost::trim_copy(m_server) == "?" ||
        m_printTemplates || m_dontrun ||
        m_argc == 1 || (m_useDaemon.wasSet() && m_argc == 2) ||
        m_printDatabases ||
        m_createDatabase ||
        m_removeDatabase ||
        m_printConfig || m_remove ||
        (m_server == "" && m_argc > 1) ||
        m_configure || m_migrate ||
        m_status || m_printSessions ||
        !m_restore.empty() ||
        m_accessItems ||
        m_dryrun ||
        (!m_run && m_props.hasProperties(FullProps::IGNORE_GLOBAL_PROPS))) {
        return false;
    } else {
        return true;
    }
}

bool Cmdline::isRestore() const
{
    return !m_restore.empty();
}

bool Cmdline::dontRun() const
{
    // this mimics the if() checks in run()
    if (m_usage || m_version ||
        m_printServers || boost::trim_copy(m_server) == "?" ||
        m_printTemplates) {
        return false;
    } else {
        return m_dontrun;
    }
}

void Cmdline::makeObsolete(boost::shared_ptr<SyncConfig> &from)
{
    string oldname = from->getRootPath();
    string newname, suffix;
    for (int counter = 0; true; counter++) {
        ostringstream newsuffix;
        newsuffix << ".old";
        if (counter) {
            newsuffix << "." << counter;
        }
        suffix = newsuffix.str();
        newname = oldname + suffix;
        if (from->hasPeerProperties()) {
            boost::shared_ptr<SyncConfig> renamed(new SyncConfig(from->getPeerName() + suffix));
            if (renamed->exists()) {
                // don't pick a config name which has the same peer name
                // as some other, existing config
                continue;
            }
        }

        // now renaming should succeed, but let's check anyway
        if (!rename(oldname.c_str(),
                    newname.c_str())) {
            break;
        } else if (errno != EEXIST && errno != ENOTEMPTY) {
            SE_THROW(StringPrintf("renaming %s to %s: %s",
                                  oldname.c_str(),
                                  newname.c_str(),
                                  strerror(errno)));
        }
    }

    string newConfigName;
    string oldContext = from->getContextName();
    if (from->hasPeerProperties()) {
        newConfigName = from->getPeerName() + suffix + oldContext;
    } else {
        newConfigName = oldContext + suffix;
    }
    from.reset(new SyncConfig(newConfigName));
}

void Cmdline::copyConfig(const boost::shared_ptr<SyncConfig> &from,
                         const boost::shared_ptr<SyncConfig> &to,
                         const set<string> &selectedSources)
{
    const set<string> *sources = NULL;
    set<string> allSources;
    if (!selectedSources.empty()) {
        // use explicitly selected sources
        sources = &selectedSources;
    } else {
        // need an explicit list of all sources which will be copied,
        // for the createFilters() call below
        BOOST_FOREACH(const std::string &source, from->getSyncSources()) {
            allSources.insert(source);
        }
        sources = &allSources;
    }

    // Apply config changes on-the-fly. Regardless what we do
    // (changing an existing config, migrating, creating from
    // a template), existing shared properties in the desired
    // context must be preserved unless explicitly overwritten.
    // Therefore read those, update with command line properties,
    // then set as filter.
    ConfigProps syncFilter;
    SourceProps sourceFilters;
    m_props.createFilters(to->getContextName(), to->getConfigName(), sources, syncFilter, sourceFilters);
    from->setConfigFilter(true, "", syncFilter);
    BOOST_FOREACH(const SourceProps::value_type &entry, sourceFilters) {
        from->setConfigFilter(false, entry.first, entry.second);
    }

    // Modify behavior of target UI before using it: set keyring
    // property separately.
    InitStateTri keyring = from->getKeyring();
    if (keyring.wasSet()) {
        to->setKeyring(keyring);
    }

    // Write into the requested configuration, creating it if necessary.
    to->prepareConfigForWrite();
    to->copy(*from, sources);
}

void Cmdline::finishCopy(const boost::shared_ptr<SyncConfig> &from,
                         const boost::shared_ptr<SyncContext> &to)
{
    // give a change to do something before flushing configs to files
    to->preFlush(to->getUserInterfaceNonNull());

    // done, now write it
    m_configModified = true;
    to->flush();

    // migrating peer?
    if (m_migrate &&
        from->hasPeerProperties()) {
        
        // also copy .synthesis dir
        string fromDir, toDir;
        fromDir = from->getRootPath() + "/.synthesis";
        toDir = to->getRootPath() + "/.synthesis";
        if (isDir(fromDir)) {
            cp_r(fromDir, toDir);
        }

        // Succeeded so far, remove "ConsumerReady" flag from migrated
        // config to hide that old config from normal UI users. Must
        // do this without going through SyncConfig, because that
        // would bump the version.
        BoolConfigProperty ready("ConsumerReady", "", "0");
        // Also disable auto-syncing in the migrated config.
        StringConfigProperty autosync("autoSync", "", "");
        {
            IniFileConfigNode node(from->getRootPath(), "config.ini", false);
            if (ready.getPropertyValue(node)) {
                ready.setProperty(node, false);
            }
            if (!autosync.getProperty(node).empty()) {
                autosync.setProperty(node, InitStateString("0", true));
            }
            node.flush();
        }

        // same for very old configs
        {
            IniFileConfigNode node(from->getRootPath() + "/spds/syncml", "config.txt", false);
            if (!autosync.getProperty(node).empty()) {
                autosync.setProperty(node, InitStateString("0", true));
            }
            node.flush();
        }

        // Set ConsumerReady for migrated SyncEvolution < 1.2
        // configs, because in older releases all existing
        // configurations where shown. SyncEvolution 1.2 is more
        // strict and assumes that ConsumerReady must be set
        // explicitly. The sync-ui always has set the flag for
        // configs created or modified with it, but the command
        // line did not. Matches similar code in
        // syncevo-dbus-server.          
        if (from->getConfigVersion(CONFIG_LEVEL_PEER, CONFIG_CUR_VERSION) == 0 /* SyncEvolution < 1.2 */) {
            to->setConsumerReady(true);
            to->flush();
        }
    }
}

void Cmdline::migratePeer(const std::string &fromPeer, const std::string &toPeer)
{
    boost::shared_ptr<SyncConfig> from(new SyncConfig(fromPeer));
    makeObsolete(from);
    // hack: move to different target config for createSyncClient()
    m_server = toPeer;
    boost::shared_ptr<SyncContext> to(createSyncClient());

    // Special case for Memotoo: explicitly set preferred sync format
    // to vCard 3.0 as part of the SyncEvolution 1.1.x -> 1.2 migration,
    // because it works better. Template was also updated in 1.2, but
    // that alone wouldn't improve existing configs.
    if (from->getConfigVersion(CONFIG_LEVEL_PEER, CONFIG_CUR_VERSION) == 0) {
        vector<string> urls = from->getSyncURL();
        if (urls.size() == 1 &&
            urls[0] == "http://sync.memotoo.com/syncML") {
            boost::shared_ptr<SyncContext> to(createSyncClient());
            m_props[to->getContextName()].m_sourceProps["addressbook"].insert(make_pair("syncFormat", "text/vcard"));
        }
    }

    copyConfig(from, to, set<string>());
    finishCopy(from, to);
}

/**
 * Finds first instance of delimiter string in other string. In
 * addition, it treats "\n\n" in a special way: that delimiter also
 * matches "\n\r\n".
 */
class FindDelimiter {
    const string m_delimiter;
public:
    FindDelimiter(const string &delimiter) :
        m_delimiter(delimiter)
    {}
    boost::iterator_range<string::iterator> operator()(string::iterator begin,
                                                       string::iterator end)
    {
        if (m_delimiter == "\n\n") {
            // match both "\n\n" and "\n\r\n"
            while (end - begin >= 2) {
                if (*begin == '\n') {
                    if (*(begin + 1) == '\n') {
                        return boost::iterator_range<string::iterator>(begin, begin + 2);
                    } else if (end - begin >= 3 &&
                               *(begin + 1) == '\r' &&
                               *(begin + 2) == '\n') {
                        return boost::iterator_range<string::iterator>(begin, begin + 3);
                    }
                }
                ++begin;
            }
            return boost::iterator_range<string::iterator>(end, end);
        } else {
            boost::sub_range<string> range(begin, end);
            return boost::find_first(range, m_delimiter);
        }
    }
};

void Cmdline::checkSyncPasswords(SyncContext &context)
{
    ConfigPropertyRegistry& registry = SyncConfig::getRegistry();
    BOOST_FOREACH(const ConfigProperty *prop, registry) {
        prop->checkPassword(context.getUserInterfaceNonNull(),
                            context.getConfigName(),
                            *context.getProperties());
    }
}

void Cmdline::checkSourcePasswords(SyncContext &context,
                                   const std::string &sourceName,
                                   SyncSourceNodes &nodes)
{
    ConfigPropertyRegistry &registry = SyncSourceConfig::getRegistry();
    BOOST_FOREACH(const ConfigProperty *prop, registry) {
        prop->checkPassword(context.getUserInterfaceNonNull(),
                            context.getConfigName(),
                            *context.getProperties(),
                            sourceName,
                            nodes.getProperties());
    }
}

bool Cmdline::run() {
    // --dry-run is only supported by some operations.
    // Be very strict about it and make sure it is off in all
    // potentially harmful operations, otherwise users might
    // expect it to have an effect when it doesn't.

    // TODO: check filter properties for invalid config and source
    // names

    if (m_usage) {
        usage(true);
    } else if (m_version) {
        SE_LOG_SHOW(NULL, "SyncEvolution %s%s\n%s%s",
                    VERSION,
                    SyncContext::isStableRelease() ? "" : " (pre-release)",
                    EDSAbiWrapperInfo(),
                    SyncSource::backendsInfo().c_str());
    } else if (m_printServers || boost::trim_copy(m_server) == "?") {
        dumpConfigs("Configured servers:",
                    SyncConfig::getConfigs());
    } else if (m_printTemplates) {
        SyncConfig::DeviceList devices;
        if (m_template.empty()){
            devices.push_back (SyncConfig::DeviceDescription("", "", SyncConfig::MATCH_FOR_CLIENT_MODE));
            dumpConfigTemplates("Available configuration templates (servers):",
                    SyncConfig::getPeerTemplates(devices), false);
        } else {
            //limiting at templates for syncml clients only.
            devices.push_back (SyncConfig::DeviceDescription("", m_template, SyncConfig::MATCH_FOR_SERVER_MODE));
            dumpConfigTemplates("Available configuration templates (clients):",
                    SyncConfig::matchPeerTemplates(devices), true);
        }
    } else if (m_dontrun) {
        // user asked for information
    } else if (m_printDatabases || m_createDatabase || m_removeDatabase) {
        // manipulate databases
        const SourceRegistry &registry(SyncSource::getSourceRegistry());
        boost::shared_ptr<SyncSourceNodes> nodes;
        std::string header;
        boost::shared_ptr<SyncContext> context;
        FilterConfigNode::ConfigFilter sourceFilter;
        std::string sourceName;
        FilterConfigNode::ConfigFilter::const_iterator backend;

        void (Cmdline::*operation)(SyncSource *, const std::string &) =
            m_printDatabases ? &Cmdline::listDatabases :
            m_createDatabase ? &Cmdline::createDatabase :
            &Cmdline::removeDatabase;

        if (!m_server.empty()) {
            // list for specific backend chosen via config
            if (m_sources.size() != 1) {
                SE_THROW(StringPrintf("must specify exactly one source after the config name '%s'",
                                      m_server.c_str()));
            }
            sourceName = *m_sources.begin();
            sourceFilter = m_props.createSourceFilter(m_server, sourceName);
            backend = sourceFilter.find("backend");
            context.reset(createSyncClient());
            if (!context->exists()) {
                SE_THROW(StringPrintf("config '%s' does not exist", m_server.c_str()));
            }
            nodes.reset(new SyncSourceNodes(context->getSyncSourceNodesNoTracking(sourceName)));
            header = StringPrintf("%s/%s", m_server.c_str(), sourceName.c_str());
            if (!nodes->dataConfigExists()) {
                SE_THROW(StringPrintf("%s does not exist",
                                      header.c_str()));
            }
        } else {
            sourceFilter = m_props.createSourceFilter(m_server, "");
            backend = sourceFilter.find("backend");
            context.reset(createSyncClient());
            boost::shared_ptr<FilterConfigNode> sharedNode(new VolatileConfigNode());
            boost::shared_ptr<FilterConfigNode> configNode(new VolatileConfigNode());
            boost::shared_ptr<FilterConfigNode> hiddenNode(new VolatileConfigNode());
            boost::shared_ptr<FilterConfigNode> trackingNode(new VolatileConfigNode());
            boost::shared_ptr<FilterConfigNode> serverNode(new VolatileConfigNode());
            nodes.reset(new SyncSourceNodes(true, sharedNode, configNode, hiddenNode, trackingNode, serverNode, ""));
            header = backend != sourceFilter.end() ?
                backend->second :
                "???";
        }
        nodes->getProperties()->setFilter(sourceFilter);
        FilterConfigNode::ConfigFilter syncFilter = m_props.createSyncFilter(m_server);
        context->setConfigFilter(true, "", syncFilter);

        SyncSourceParams params("list", *nodes, context);
        if (!m_server.empty() || backend != sourceFilter.end()) {
            // list for specific backend
            params.m_name = sourceName;
            auto_ptr<SyncSource> source(SyncSource::createSource(params, false, NULL));
            if (source.get() != NULL) {
                if (!m_server.empty() && nodes) {
                    // ensure that we have passwords for this config
                    checkSyncPasswords(*context);
                    checkSourcePasswords(*context, sourceName, *nodes);
                }
                (this->*operation)(source.get(), header);
            } else {
                SE_LOG_SHOW(NULL, "%s:\n   cannot access databases", header.c_str());
            }
        } else {
            // list for all backends
            BOOST_FOREACH(const RegisterSyncSource *source, registry) {
                BOOST_FOREACH(const Values::value_type &alias, source->m_typeValues) {
                    if (!alias.empty() && source->m_enabled) {
                        SourceType type(*alias.begin());
                        nodes->getProperties()->setProperty("backend", type.m_backend);
                        std::string header = boost::join(alias, " = ");
                        try {
                            // The name is used in error messages. We
                            // don't have a source name, so let's fall
                            // back to the backend instead.
                            params.m_name = type.m_backend;
                            auto_ptr<SyncSource> source(SyncSource::createSource(params, false));
                            (this->*operation)(source.get(), header);
                        } catch (...) {
                            SE_LOG_ERROR(NULL, "%s:\naccessing databases failed", header.c_str());
                            Exception::handle();
                        }
                    }
                }
            }
        }
    } else if (m_printConfig) {
        boost::shared_ptr<SyncConfig> config;
        ConfigProps syncFilter;
        SourceProps sourceFilters;

        if (m_template.empty()) {
            if (m_server.empty()) {
                usage(false, "--print-config requires either a --template or a server name.");
                return false;
            }
            config.reset(new SyncConfig(m_server));
            if (!config->exists()) {
                SE_LOG_ERROR(NULL, "Server '%s' has not been configured yet.", m_server.c_str());
                return false;
            }

            // No need to include a context or additional sources,
            // because reading the m_server config already includes
            // the right information.
            m_props.createFilters("", m_server, NULL, syncFilter, sourceFilters);
        } else {
            string peer, context;
            SyncConfig::splitConfigString(SyncConfig::normalizeConfigString(m_template,
                                                                            SyncConfig::NormalizeFlags(SyncConfig::NORMALIZE_SHORTHAND|SyncConfig::NORMALIZE_IS_NEW)),
                                          peer, context);
            config = SyncConfig::createPeerTemplate(peer);
            if (!config.get()) {
                SE_LOG_ERROR(NULL, "No configuration template for '%s' available.", m_template.c_str());
                return false;
            }

            // When instantiating a template, include the properties
            // of the target context as filter to preserve shared
            // properties, the final name inside that context as
            // peer config name, and the sources defined in the template.
            list<string> sourcelist = config->getSyncSources();
            set<string> sourceset(sourcelist.begin(), sourcelist.end());
            m_props.createFilters(std::string("@") + context, "",
                                  &sourceset,
                                  syncFilter, sourceFilters);
        }

        // determine whether we dump a peer or a context
        int flags = DUMP_PROPS_NORMAL;
        string peer, context;
        SyncConfig::splitConfigString(config->getConfigName(), peer, context);
        if (peer.empty()) {
            flags |= HIDE_PER_PEER;
            checkForPeerProps();
        } 

        if (m_sources.empty() ||
            m_sources.find("main") != m_sources.end()) {
            boost::shared_ptr<FilterConfigNode> syncProps(config->getProperties());
            syncProps->setFilter(syncFilter);
            dumpProperties(*syncProps, config->getRegistry(), flags);
        }

        list<string> sources = config->getSyncSources();
        sources.sort();
        BOOST_FOREACH(const string &name, sources) {
            if (m_sources.empty() ||
                m_sources.find(name) != m_sources.end()) {
                SE_LOG_SHOW(NULL, "[%s]", name.c_str());
                SyncSourceNodes nodes = config->getSyncSourceNodes(name);
                boost::shared_ptr<FilterConfigNode> sourceProps = nodes.getProperties();
                sourceProps->setFilter(sourceFilters.createSourceFilter(name));
                dumpProperties(*sourceProps, SyncSourceConfig::getRegistry(),
                               flags | ((name != *(--sources.end())) ? HIDE_LEGEND : DUMP_PROPS_NORMAL));
            }
        }
    } else if (m_configure || m_migrate) {
        if (!needConfigName()) {
            return false;
        }
        if (m_dryrun) {
            SyncContext::throwError("--dry-run not supported for configuration changes");
        }

        // name of renamed config ("foo.old") after migration
        string newname;

        // True if the target configuration is a context like @default
        // or @foobar. Relevant in several places in the following
        // code.
        bool configureContext = false;

        bool fromScratch = false;
        string peer, context;
        SyncConfig::splitConfigString(SyncConfig::normalizeConfigString(m_server), peer, context);
        if (peer.empty()) {
            configureContext = true;
            checkForPeerProps();
        }

        // Make m_server a fully-qualified name. Useful in error
        // messages and essential for migrating "foo" where "foo"
        // happens to map to "foo@bar".  Otherwise "foo" will be
        // mapped incorrectly to "foo@default" after renaming
        // "foo@bar" to "foo.old@bar".
        //
        // The inverse problem can occur for "foo@default": after
        // renaming, "foo" without "@default" would be mapped to
        // "foo@somewhere-else" if such a config exists.
        m_server = peer + "@" + context;

        // Both config changes and migration are implemented as copying from
        // another config (template resp. old one). Migration also moves
        // the old config. The target configuration is determined by m_server,
        // but the exact semantic of it depends on the operation.
        boost::shared_ptr<SyncConfig> from;
        boost::shared_ptr<SyncContext> to;
        string origPeer;
        if (m_migrate) {
            if (!m_sources.empty()) {
                SE_LOG_ERROR(NULL, "cannot migrate individual sources");
                return false;
            }

            string oldContext = context;
            from.reset(new SyncConfig(m_server));
            if (!from->exists()) {
                // for migration into a different context, search for config without context
                oldContext = "";
                from.reset(new SyncConfig(peer));
                if (!from->exists()) {
                    SE_LOG_ERROR(NULL, "Server '%s' has not been configured yet.", m_server.c_str());
                    return false;
                }
            }

            // Check if we are migrating an individual peer inside
            // a context which itself is too old. In that case,
            // the whole context and everything inside it needs to
            // be migrated.
            if (!configureContext) {
                bool obsoleteContext = false;
                if (from->getLayout() < SyncConfig::SHARED_LAYOUT) {
                    // check whether @default context exists and is too old;
                    // in that case migrate it first
                    SyncConfig target("@default");
                    if (target.exists() &&
                        target.getConfigVersion(CONFIG_LEVEL_CONTEXT, CONFIG_CUR_VERSION) <
                        CONFIG_CONTEXT_MIN_VERSION) {
                        // migrate all peers inside @default *and* the one outside
                        origPeer = m_server;
                        m_server = "@default";
                        obsoleteContext = true;
                    }
                } else {
                    // config already is inside a context; need to check that context
                    if (from->getConfigVersion(CONFIG_LEVEL_CONTEXT, CONFIG_CUR_VERSION) <
                        CONFIG_CONTEXT_MIN_VERSION) {
                        m_server = string("@") + context;
                        obsoleteContext = true;
                    }
                }
                if (obsoleteContext) {
                    // hack: move to different config and back later
                    from.reset(new SyncConfig(m_server));
                    peer = "";
                    configureContext = true;
                }
            }

            // rename on disk and point "from" to it
            makeObsolete(from);

            // modify the config referenced by the (possibly modified) m_server
            to.reset(createSyncClient());
        } else {
            from.reset(new SyncConfig(m_server));
            // m_server known, modify it
            to.reset(createSyncClient());

            if (!from->exists()) {
                // creating from scratch, look for template
                fromScratch = true;
                string configTemplate;
                if (m_template.empty()) {
                    if (configureContext) {
                        // configuring a context, template doesn't matter =>
                        // use default "SyncEvolution" template
                        configTemplate =
                            peer = "SyncEvolution";
                        from = SyncConfig::createPeerTemplate(peer);
                    } else if (peer == "target-config") {
                        // Configuring the source context for local sync
                        // => determine template based on context name.
                        configTemplate = context;
                        from = SyncConfig::createPeerTemplate(context);
                    } else {
                        // template is the peer name
                        configTemplate = m_server;
                        from = SyncConfig::createPeerTemplate(peer);
                    }
                } else {
                    // Template is specified explicitly. It must not contain a context,
                    // because the context comes from the config name.
                    configTemplate = m_template;
                    if (SyncConfig::splitConfigString(SyncConfig::normalizeConfigString(configTemplate,
                                                                                        SyncConfig::NormalizeFlags(SyncConfig::NORMALIZE_SHORTHAND|SyncConfig::NORMALIZE_IS_NEW)),
                                                      peer, context)) {
                        SE_LOG_ERROR(NULL, "Template %s must not specify a context.", configTemplate.c_str());
                        return false;
                    }
                    string tmp;
                    SyncConfig::splitConfigString(SyncConfig::normalizeConfigString(m_server), tmp, context);
                    from = SyncConfig::createPeerTemplate(peer);
                }
                list<string> missing;
                if (!from.get()) {
                    // check if all obligatory sync properties are specified; needed
                    // for both the "is complete" check and the error message below
                    ConfigProps syncProps = m_props.createSyncFilter(to->getContextName());
                    bool complete = true;
                    BOOST_FOREACH(const ConfigProperty *prop, SyncConfig::getRegistry()) {
                        if (prop->isObligatory() &&
                            syncProps.find(prop->getMainName()) == syncProps.end()) {
                            missing.push_back(prop->getMainName());
                            complete = false;
                        }
                    }

                    // if everything was specified and no invalid template name was given, allow user
                    // to proceed with "none" template; if a template was specified, we skip
                    // this and go directly to the code below which prints an error message
                    if (complete &&
                        m_template.empty()) {
                        from = SyncConfig::createPeerTemplate("none");
                    }
                }
                if (!from.get()) {
                    SE_LOG_ERROR(NULL, "No configuration template for '%s' available.", configTemplate.c_str());
                    if (m_template.empty()) {
                        SE_LOG_INFO(NULL,
                                    "Use '--template none' and/or specify relevant properties on the command line to create a configuration without a template. Need values for: %s",
                                    boost::join(missing, ", ").c_str());
                    } else if (missing.empty()) {
                        SE_LOG_INFO(NULL, "All relevant properties seem to be set, omit the --template parameter to proceed.");
                    }
                    SE_LOG_INFO(NULL, "\n");
                    SyncConfig::DeviceList devices;
                    devices.push_back(SyncConfig::DeviceDescription("", "", SyncConfig::MATCH_ALL));
                    dumpConfigTemplates("Available configuration templates (clients and servers):",
                                        SyncConfig::getPeerTemplates(devices),
                                        false,
                                        Logger::INFO);
                    return false;
                }
            }
        }

        // Which sources are configured is determined as follows:
        // - all sources in the template by default (empty set), except when
        // - sources are listed explicitly, and either
        // - updating an existing config or
        // - configuring a context.
        //
        // This implies that when configuring a peer from scratch, all
        // sources in the template will be created, with command line
        // source properties applied to all of them. This might not be
        // what we want, but because this is how we have done it
        // traditionally, I keep this behavior for now.
        //
        // When migrating, m_sources is empty and thus the whole set of
        // sources will be migrated. Checking it here for clarity's sake.
        set<string> sources;
        if (!m_migrate &&
            !m_sources.empty() &&
            (!fromScratch || configureContext)) {
            sources = m_sources;
        }

        // Also copy (aka create) sources listed on the command line if
        // creating from scratch and
        // - "--template none" enables the "do what I want" mode or
        // - source properties apply to it.
        // Creating from scratch with other sources is a possible typo
        // and will trigger an error below.
        if (fromScratch) {
            BOOST_FOREACH(const string &source, m_sources) {
                if (m_template == "none" ||
                    !m_props.createSourceFilter(to->getContextName(), source).empty()) {
                    sources.insert(source);
                }
            }
        }

        // Special case for migration away from "type": older
        // SyncEvolution could cope with "type" only set correctly for
        // peers. Real-world case: Memotoo config, context had "type =
        // calendar" set for address book.
        //
        // Setting "backend" based on an incorrect "type" from the
        // context would lead to a broken, unusable config. Solution:
        // take "backend" and "databaseFormat" from a peer config when
        // migrating a context.
        //
        // Note that peers are assumed to be consistent. Not attempt is
        // made to detect a config which has inconsistent peer configs.
        if (m_migrate && configureContext &&
            from->getConfigVersion(CONFIG_LEVEL_CONTEXT, CONFIG_CUR_VERSION) == 0) {
            list<string> peers = from->getPeers();
            peers.sort(); // make code below deterministic

            BOOST_FOREACH(const std::string source, from->getSyncSources()) {
                BOOST_FOREACH(const string &peer, peers) {
                    IniFileConfigNode node(from->getRootPath() + "/peers/" + peer + "/sources/" + source,
                                           "config.ini",
                                           true);
                    string sync = node.readProperty("sync");
                    if (sync.empty() ||
                        boost::iequals(sync, "none") ||
                        boost::iequals(sync, "disabled")) {
                        // ignore this peer, it doesn't use the source
                        continue;
                    }

                    SourceType type(node.readProperty("type"));
                    if (!type.m_backend.empty()) {
                        // found some "type": use "backend" and
                        // "dataFormat" in filter, unless the user
                        // already set a value there
                        ConfigProps syncFilter;
                        SourceProps sourceFilters;
                        set<string> set;
                        set.insert(source);
                        m_props.createFilters(to->getContextName(), "",
                                              &set, syncFilter, sourceFilters);
                        const ConfigProps &sourceFilter = sourceFilters[source];
                        if (sourceFilter.find("backend") == sourceFilter.end()) {
                            m_props[to->getContextName()].m_sourceProps[source]["backend"] = type.m_backend;
                        }
                        if (!type.m_localFormat.empty() &&
                            sourceFilter.find("databaseFormat") == sourceFilter.end()) {
                            m_props[to->getContextName()].m_sourceProps[source]["databaseFormat"] = type.m_localFormat;
                        }
                        // use it without bothering to keep looking
                        // (no consistenty check!)
                        break;
                    }
                }
            }
        }

        // TODO: update complete --configure output to be more informative.
        // This is a first step, but shouldn't be done in isolation.
        // SE_LOG_INFO(NULL, "%s configuration %s",
        //             fromScratch ? "creating" : "updating",
        //             to->getConfigName().c_str());

        // copy and filter into the target config: createSyncClient()
        // creates a SyncContext for m_server, with propert
        // implementation of the password handling methods in derived
        // classes (D-Bus server, real command line)
        copyConfig(from, to, sources);

        // Sources are active now according to the server default.
        // Disable all sources not selected by user (if any selected)
        // and those which have no database.
        if (fromScratch) {
            list<string> configuredSources = to->getSyncSources();
            set<string> sources = m_sources;
            SuspendFlags &s = SuspendFlags::getSuspendFlags();

            BOOST_FOREACH(const string &source, configuredSources) {
                boost::shared_ptr<PersistentSyncSourceConfig> sourceConfig(to->getSyncSourceConfig(source));
                string disable = "";
                set<string>::iterator entry = sources.find(source);
                bool selected = entry != sources.end();

                if (!m_sources.empty() &&
                    !selected) {
                    disable = "not selected";
                } else {
                    if (entry != sources.end()) {
                        // The command line parameter matched a valid source.
                        // All entries left afterwards must have been typos.
                        sources.erase(entry);
                    }

                    // check whether the sync source works; this can
                    // take some time, so allow the user to abort
                    SE_LOG_INFO(NULL, "%s: looking for databases...",
                                source.c_str());
                    SyncSourceParams params(source, to->getSyncSourceNodes(source), to);
                    auto_ptr<SyncSource> syncSource(SyncSource::createSource(params, false, to.get()));
                    if (syncSource.get() == NULL) {
                        disable = "no backend available";
                    } else {
                        try {
                            SyncSource::Databases databases = syncSource->getDatabases();
                            if (databases.empty()) {
                                disable = "no database to synchronize";
                            }
                        } catch (...) {
                            std::string explanation;
                            Exception::handle(explanation, HANDLE_EXCEPTION_NO_ERROR);
                            disable = "backend failed: " + explanation;
                        }
                    }
                    s.checkForNormal();
                    SE_LOG_INFO(NULL, "%s: %s\n",
                                source.c_str(),
                                disable.empty() ? "okay" : disable.c_str());
                }

                // Do sanity checking of source (can it be enabled?),
                // but only set the sync mode if configuring a peer.
                // A context-only config doesn't have the "sync"
                // property.
                string syncMode;
                if (!disable.empty()) {
                    // abort if the user explicitly asked for the sync source
                    // and it cannot be enabled, otherwise disable it silently
                    if (selected) {
                        SyncContext::throwError(source + ": " + disable);
                    }
                    syncMode = "disabled";
                } else if (selected) {
                    // user absolutely wants it: enable even if off by default
                    ConfigProps filter = m_props.createSourceFilter(m_server, source);
                    ConfigProps::const_iterator sync = filter.find("sync");
                    syncMode = sync == filter.end() ? "two-way" : sync->second;
                }
                if (!syncMode.empty() &&
                    !configureContext) {
                    sourceConfig->setSync(syncMode);
                }
            }

            if (!sources.empty()) {
                SyncContext::throwError(string("no such source(s): ") + boost::join(sources, " "));
            }
        }

        // flush, move .synthesis dir, set ConsumerReady, ...
        finishCopy(from, to);

        // Now also migrate all peers inside context?
        if (configureContext && m_migrate) {
            BOOST_FOREACH(const string &peer, from->getPeers()) {
                migratePeer(peer + from->getContextName(), peer + to->getContextName());
            }
            if (!origPeer.empty()) {
                migratePeer(origPeer, origPeer + to->getContextName());
            }
        }
    } else if (m_remove) {
        if (!needConfigName()) {
            return false;
        }
        if (m_dryrun) {
            SyncContext::throwError("--dry-run not supported for removing configurations");
        }

        // extra sanity check
        if (!m_sources.empty() ||
            m_props.hasProperties(FullProps::IGNORE_GLOBAL_PROPS)) {
            usage(false, "too many parameters for --remove");
            return false;
        } else {
            boost::shared_ptr<SyncConfig> config;
            config.reset(new SyncConfig(m_server));
            if (!config->exists()) {
                SyncContext::throwError(string("no such configuration: ") + m_server);
            }
            config->remove();
            m_configModified = true;
            return true;
        }
    } else if (m_accessItems) {
        // need access to specific source
        boost::shared_ptr<SyncContext> context;
        context.reset(createSyncClient());

        // operating on exactly one source (can be optional)
        string sourceName;
        bool haveSourceName = !m_sources.empty();
        if (haveSourceName) {
            sourceName = *m_sources.begin();
        }

        // apply filters
        context->setConfigFilter(true, "", m_props.createSyncFilter(m_server));
        context->setConfigFilter(false, "", m_props.createSourceFilter(m_server, sourceName));

        SyncSourceNodes sourceNodes = context->getSyncSourceNodesNoTracking(sourceName);
        SyncSourceParams params(sourceName, sourceNodes, context);
        cxxptr<SyncSource> source;

        try {
            source.set(SyncSource::createSource(params, true));
        } catch (const StatusException &ex) {
            // Creating the source failed. Detect some common reasons for this
            // and log those instead. None of these situations are fatal by themselves,
            // but in combination they are a problem.
            if (ex.syncMLStatus() == SyncMLStatus(sysync::LOCERR_CFGPARSE)) {
                std::list<std::string> explanation;

                explanation.push_back(ex.what());
                if (!m_server.empty() && !context->exists()) {
                    explanation.push_back(StringPrintf("configuration '%s' does not exist", m_server.c_str()));
                }
                if (haveSourceName && !sourceNodes.exists()) {
                    explanation.push_back(StringPrintf("source '%s' does not exist", sourceName.c_str()));
                } else if (!haveSourceName) {
                    explanation.push_back("no source selected");
                }
                SyncSourceConfig sourceConfig(sourceName, sourceNodes);
                if (!sourceConfig.getBackend().wasSet()) {
                    explanation.push_back("backend property not set");
                }
                SyncContext::throwError(SyncMLStatus(sysync::LOCERR_CFGPARSE),
                                        boost::join(explanation, "\n"));
            } else {
                throw;
            }
        }

        sysync::TSyError err;
#define CHECK_ERROR(_op) if (err) { SE_THROW_EXCEPTION_STATUS(StatusException, string(source->getName()) + ": " + (_op), SyncMLStatus(err)); }

        checkSyncPasswords(*context);
        checkSourcePasswords(*context, source->getName(), sourceNodes);
        source->open();
        const SyncSource::Operations &ops = source->getOperations();
        if (m_printItems) {
            SyncSourceLogging *logging = dynamic_cast<SyncSourceLogging *>(source.get());
            if (!ops.m_startDataRead ||
                !ops.m_readNextItem) {
                source->throwError("reading items not supported");
            }

            err = ops.m_startDataRead(*source, "", "");
            CHECK_ERROR("reading items");
            list<string> luids;
            readLUIDs(source, luids);
            BOOST_FOREACH(string &luid, luids) {
                string description;
                if (logging) {
                    description = logging->getDescription(luid);
                }
                SE_LOG_SHOW(NULL, "%s%s%s",
                            CmdlineLUID::fromLUID(luid).c_str(),
                            description.empty() ? "" : ": ",
                            description.c_str());
            }
        } else if (m_deleteItems) {
            if (!ops.m_deleteItem) {
                source->throwError("deleting items not supported");
            }
            list<string> luids;
            bool deleteAll = std::find(m_luids.begin(), m_luids.end(), "*") != m_luids.end();
            err = ops.m_startDataRead(*source, "", "");
            CHECK_ERROR("reading items");
            if (deleteAll) {
                readLUIDs(source, luids);
            } else {
                luids = m_luids;
            }
            if (ops.m_endDataRead) {
                err = ops.m_endDataRead(*source);
                CHECK_ERROR("stop reading items");
            }
            if (ops.m_startDataWrite) {
                err = ops.m_startDataWrite(*source);
                CHECK_ERROR("writing items");
            }
            BOOST_FOREACH(const string &luid, luids) {
                sysync::ItemIDType id;
                id.item = (char *)luid.c_str();
                err = ops.m_deleteItem(*source, &id);
                CHECK_ERROR("deleting item");
            }
            char *token;
            err = ops.m_endDataWrite(*source, true, &token);
            if (token) {
                free(token);
            }
            CHECK_ERROR("stop writing items");
        } else {
            SyncSourceRaw *raw = dynamic_cast<SyncSourceRaw *>(source.get());
            if (!raw) {
                source->throwError("reading/writing items directly not supported");
            }
            if (m_import || m_update) {
                err = ops.m_startDataRead(*source, "", "");
                CHECK_ERROR("reading items");
                if (ops.m_endDataRead) {
                    err = ops.m_endDataRead(*source);
                    CHECK_ERROR("stop reading items");
                }
                if (ops.m_startDataWrite) {
                    err = ops.m_startDataWrite(*source);
                    CHECK_ERROR("writing items");
                }

                cxxptr<ifstream> inFile;
                if (m_itemPath =="-" ||
                    !isDir(m_itemPath)) {
                    string content;
                    string luid;
                    if (m_itemPath == "-") {
                        context->getUserInterfaceNonNull().readStdin(content);
                    } else if (!ReadFile(m_itemPath, content)) {
                        SyncContext::throwError(m_itemPath, errno);
                    }
                    if (m_delimiter == "none") {
                        if (m_update) {
                            if (m_luids.size() != 1) {
                                SyncContext::throwError("need exactly one LUID parameter");
                            } else {
                                luid = *m_luids.begin();
                            }
                        }
                        SE_LOG_SHOW(NULL, "#0: %s",
                                    insertItem(raw, luid, content).getEncoded().c_str());
                    } else {
                        typedef boost::split_iterator<string::iterator> string_split_iterator;
                        int count = 0;
                        FindDelimiter finder(m_delimiter);

                        // when updating, check number of luids in advance
                        if (m_update) {
                            unsigned long total = 0;
                            for (string_split_iterator it =
                                     boost::make_split_iterator(content, finder);
                                 it != string_split_iterator();
                                 ++it) {
                                total++;
                            }
                            if (total != m_luids.size()) {
                                SyncContext::throwError(StringPrintf("%lu items != %lu luids, must match => aborting",
                                                                     total, (unsigned long)m_luids.size()));
                            }
                        }
                        list<string>::const_iterator luidit = m_luids.begin();
                        for (string_split_iterator it =
                                 boost::make_split_iterator(content, finder);
                             it != string_split_iterator();
                             ++it) {
                            string luid;
                            if (m_update) {
                                if (luidit == m_luids.end()) {
                                    // was checked above
                                    SyncContext::throwError("internal error, not enough luids");
                                }
                                luid = *luidit;
                                ++luidit;
                            }
                            SE_LOG_SHOW(NULL, "#%d: %s",
                                        count,
                                        insertItem(raw,
                                                   luid,
                                                   string(it->begin(), it->end())).getEncoded().c_str());
                            count++;
                        }
                    }
                } else {
                    ReadDir dir(m_itemPath);
                    int count = 0;
                    BOOST_FOREACH(const string &entry, dir) {
                        string content;
                        string path = m_itemPath + "/" + entry;
                        if (!ReadFile(path, content)) {
                            SyncContext::throwError(path, errno);
                        }
                        SE_LOG_SHOW(NULL, "#%d: %s: %s",
                                    count,
                                    entry.c_str(),
                                    insertItem(raw, "", content).getEncoded().c_str());
                        count++;
                    }
                }
                char *token = NULL;
                err = ops.m_endDataWrite(*source, true, &token);
                if (token) {
                    free(token);
                }
                CHECK_ERROR("stop writing items");
            } else if (m_export) {
                err = ops.m_startDataRead(*source, "", "");
                CHECK_ERROR("reading items");

                ostream *out = NULL;
                cxxptr<ofstream> outFile;
                if (m_itemPath == "-") {
                    // not actually used, falls back to SE_LOG_SHOW()
                    out = &std::cout;
                } else if(!isDir(m_itemPath)) {
                    outFile.set(new ofstream(m_itemPath.c_str()));
                    out = outFile;
                }
                if (m_luids.empty()) {
                    readLUIDs(source, m_luids);
                }
                bool haveItem = false;     // have written one item
                bool haveNewline = false;  // that item had a newline at the end
                BOOST_FOREACH(const string &luid, m_luids) {
                    string item;
                    raw->readItemRaw(luid, item);
                    if (!out) {
                        // write into directory
                        string fullPath = m_itemPath + "/" + luid;
                        ofstream file((m_itemPath + "/" + luid).c_str());
                        file << item;
                        file.close();
                        if (file.bad()) {
                            SyncContext::throwError(fullPath, errno);
                        }
                    } else {
                        std::string delimiter;
                        if (haveItem) {
                            if (m_delimiter.size() > 1 &&
                                haveNewline &&
                                m_delimiter[0] == '\n') {
                                // already wrote initial newline, skip it
                                delimiter = m_delimiter.substr(1);
                            } else {
                                delimiter = m_delimiter;
                            }
                        }
                        if (out == &std::cout) {
                            // special case, use logging infrastructure
                            SE_LOG_SHOW(NULL, "%s%s",
                                        delimiter.c_str(),
                                        item.c_str());
                            // always prints newline
                            haveNewline = true;
                        } else {
                            // write to file
                            *out << delimiter << item;
                            haveNewline = boost::ends_with(item, "\n");
                        }
                        haveItem = true;
                    }
                }
                if (outFile) {
                    outFile->close();
                    if (outFile->bad()) {
                        SyncContext::throwError(m_itemPath, errno);
                    }
                }
            }
        }
        source->close();
    } else {
        if (!needConfigName()) {
            return false;
        }

        std::set<std::string> unmatchedSources;
        boost::shared_ptr<SyncContext> context;
        context.reset(createSyncClient());
        context->setConfigProps(m_props);
        context->setQuiet(m_quiet);
        context->setDryRun(m_dryrun);
        context->setConfigFilter(true, "", m_props.createSyncFilter(m_server));
        if (m_sources.empty()) {
            // Special semantic of 'no source selected': apply
            // filter (if any exists) only to sources which are
            // *active*. Configuration of inactive sources is left
            // unchanged. This way we don't activate sync sources
            // accidentally when the sync mode is modified
            // temporarily.
            BOOST_FOREACH(const std::string &source,
                          context->getSyncSources()) {
                boost::shared_ptr<PersistentSyncSourceConfig> source_config =
                    context->getSyncSourceConfig(source);
                if (!source_config->isDisabled()) {
                    context->setConfigFilter(false, source, m_props.createSourceFilter(m_server, source));
                }
            }
        } else {
            // apply (possibly empty) source filter to selected sources
            BOOST_FOREACH(const std::string &source,
                          m_sources) {
                boost::shared_ptr<PersistentSyncSourceConfig> source_config =
                        context->getSyncSourceConfig(source);
                ConfigProps filter = m_props.createSourceFilter(m_server, source);
                if (!source_config || !source_config->exists()) {
                    // invalid source name in m_sources, remember and
                    // report this below
                    unmatchedSources.insert(source);
                } else if (filter.find("sync") == filter.end()) {
                    // Sync mode is not set, must override the
                    // "sync=disabled" set below with the original
                    // sync mode for the source or (if that is also
                    // "disabled") with "two-way". The latter is part
                    // of the command line semantic that listing a
                    // source activates it.
                    string sync = source_config->getSync();
                    filter["sync"] =
                        sync == "disabled" ? "two-way" : sync;
                    context->setConfigFilter(false, source, filter);
                } else {
                    // sync mode is set, can use m_sourceProps
                    // directly to apply it
                    context->setConfigFilter(false, source, filter);
                }
            }

            // temporarily disable the rest
            FilterConfigNode::ConfigFilter disabled;
            disabled["sync"] = InitStateString("disabled", true);
            context->setConfigFilter(false, "", disabled);
        }

        // check whether there were any sources specified which do not exist
        if (unmatchedSources.size()) {
            context->throwError(string("no such source(s): ") + boost::join(unmatchedSources, " "));
        }

        if (m_status) {
            context->status();
        } else if (m_printSessions) {
            vector<string> dirs;
            context->getSessions(dirs);
            bool first = true;
            BOOST_FOREACH(const string &dir, dirs) {
                if (first) {
                    first = false;
                } else if(!m_quiet) {
                    SE_LOG_SHOW(NULL, "\n");
                }
                SE_LOG_SHOW(NULL, "%s", dir.c_str());
                if (!m_quiet) {
                    SyncReport report;
                    context->readSessionInfo(dir, report);
                    ostringstream out;
                    out << report;
                    SE_LOG_SHOW(NULL, "%s", out.str().c_str());
                }
            }
        } else if (!m_restore.empty()) {
            // sanity checks: either --after or --before must be given, sources must be selected
            if ((!m_after && !m_before) ||
                (m_after && m_before)) {
                usage(false, "--restore <log dir> must be used with either --after (restore database as it was after that sync) or --before (restore data from before sync)");
                return false;
            }
            if (m_sources.empty()) {
                usage(false, "Sources must be selected explicitly for --restore to prevent accidental restore.");
                return false;
            }
            context->restore(m_restore,
                             m_after ?
                             SyncContext::DATABASE_AFTER_SYNC :
                             SyncContext::DATABASE_BEFORE_SYNC);
        } else {
            if (m_dryrun) {
                usage(false, "--dry-run not supported for running a synchronization");
                return false;
            }

            // safety catch: if props are given, then --run
            // is required
            if (!m_run &&
                (m_props.hasProperties(FullProps::IGNORE_GLOBAL_PROPS))) {
                usage(false, "Properties specified, but neither '--configure' nor '--run' - what did you want?");
                return false;
            }

            return (context->sync(&m_report) == STATUS_OK);
        }
    }

    return true;
}

void Cmdline::readLUIDs(SyncSource *source, list<string> &luids)
{
    const SyncSource::Operations &ops = source->getOperations();
    sysync::ItemIDType id;
    sysync::sInt32 status;
    sysync::TSyError err = ops.m_readNextItem(*source, &id, &status, true);
    CHECK_ERROR("next item");
    while (status != sysync::ReadNextItem_EOF) {
        luids.push_back(id.item);
        StrDispose(id.item);
        StrDispose(id.parent);
        err = ops.m_readNextItem(*source, &id, &status, false);
        CHECK_ERROR("next item");
    }
}

CmdlineLUID Cmdline::insertItem(SyncSourceRaw *source, const string &luid, const string &data)
{
    SyncSourceRaw::InsertItemResult res = source->insertItemRaw(luid, data);
    CmdlineLUID cluid;
    cluid.setLUID(res.m_luid);
    return cluid;
}

string Cmdline::cmdOpt(const char *opt, const char *param)
{
    string res = "'";
    if (opt) {
        res += opt;
    }
    // parameter was provided as part of option
    bool included = opt && param &&
        boost::ends_with(std::string(opt),
                         std::string("=") + param);
    if (!included && opt && param) {
        res += " ";
    }
    if (!included && param) {
        res += param;
    }
    res += "'";
    return res;
}

bool Cmdline::parseProp(PropertyType propertyType,
                        const char *opt,
                        const char *param,
                        const char *propname)
{
    std::string args = cmdOpt(opt, param);

    if (!param) {
        usage(false, string("missing parameter for ") + args);
        return false;
    }

    // determine property name and parameter for it
    string propstr;
    string paramstr;
    if (propname) {
        propstr = propname;
        paramstr = param;
    } else if (boost::trim_copy(string(param)) == "?") {
        paramstr = param;
    } else {
        const char *equal = strchr(param, '=');
        if (!equal) {
            usage(false, string("the '=<value>' part is missing in: ") + args);
            return false;
        }
        propstr.assign(param, equal - param);
        paramstr.assign(equal + 1);
    }
    boost::trim(propstr);
    boost::trim_left(paramstr);

    // parse full property string
    PropertySpecifier spec = PropertySpecifier::StringToPropSpec(propstr);

    // determine property type and registry
    const ConfigPropertyRegistry *validProps = NULL;
    switch (propertyType) {
    case SYNC_PROPERTY_TYPE:
        validProps = &m_validSyncProps;
        break;
    case SOURCE_PROPERTY_TYPE:
        validProps = &m_validSourceProps;
        break;
    case UNKNOWN_PROPERTY_TYPE:
        // must guess based on both registries
        if (!propstr.empty()) {
            bool isSyncProp = m_validSyncProps.find(spec.m_property) != NULL;
            bool isSourceProp = m_validSourceProps.find(spec.m_property) != NULL;

            if (isSyncProp) {
                if (isSourceProp) {
                    usage(false, StringPrintf("property '%s' in %s could be both a sync and a source property, use --sync-property or --source-property to disambiguate it", propname, args.c_str()));
                    return false;
                } else {
                    validProps = &m_validSyncProps;
                }
            } else if (isSourceProp ||
                       boost::iequals(spec.m_property, "type")) {
                validProps = &m_validSourceProps;
            } else {
                if (propname) {
                    usage(false, StringPrintf("unrecognized property '%s' in %s", propname, args.c_str()));
                } else {
                    usage(false, StringPrintf("unrecognized property in %s", args.c_str()));
                }
                return false;
            }
        } else {
            usage(false, StringPrintf("a property name must be given in %s", args.c_str()));
            return false;
        }
    }

    if (boost::trim_copy(string(param)) == "?") {
        m_dontrun = true;
        if (propname) {
            return listPropValues(*validProps, spec.m_property, opt ? opt : "");
        } else {
            return listProperties(*validProps, opt ? opt : "");
        }
    } else {
        if (boost::trim_copy(paramstr) == "?") {
            m_dontrun = true;
            return listPropValues(*validProps, spec.m_property, args);
        } else {
            const ConfigProperty *prop = validProps->find(spec.m_property);
            if (!prop && boost::iequals(spec.m_property, "type")) {
                // compatiblity mode for "type": map to the properties which
                // replaced it
                prop = validProps->find("backend");
                if (!prop) {
                    SE_LOG_ERROR(NULL, "backend: no such property");
                    return false;
                }
                SourceType sourceType(paramstr);
                string error;
                if (!prop->checkValue(sourceType.m_backend, error)) {
                    SE_LOG_ERROR(NULL, "%s: %s", args.c_str(), error.c_str());
                    return false;
                }
                ContextProps &props = m_props[spec.m_config];
                props.m_sourceProps[spec.m_source]["backend"] =
                    InitStateString(sourceType.m_backend,
                                    !sourceType.m_backend.empty());
                props.m_sourceProps[spec.m_source]["databaseFormat"] =
                    InitStateString(sourceType.m_localFormat,
                                    !sourceType.m_localFormat.empty());
                props.m_sourceProps[spec.m_source]["syncFormat"] =
                    InitStateString(sourceType.m_format,
                                    !sourceType.m_format.empty());
                props.m_sourceProps[spec.m_source]["forceSyncFormat"] =
                    sourceType.m_forceFormat ?
                    InitStateString("1", true) :
                    InitStateString("0", false);
                return true;
            } else if (!prop) {
                SE_LOG_ERROR(NULL, "%s: no such property", args.c_str());
                return false;
            } else {
                string error;
                if (!prop->checkValue(paramstr, error)) {
                    SE_LOG_ERROR(NULL, "%s: %s", args.c_str(), error.c_str());
                    return false;
                } else {
                    ContextProps &props = m_props[spec.m_config];
                    if (validProps == &m_validSyncProps) {
                        // complain if sync property includes source prefix
                        if (!spec.m_source.empty()) {
                            SE_LOG_ERROR(NULL, "%s: source name '%s' not allowed in sync property",
                                         args.c_str(),
                                         spec.m_source.c_str());
                            return false;
                        }
                        props.m_syncProps[spec.m_property] = paramstr;
                    } else {
                        props.m_sourceProps[spec.m_source][spec.m_property] = paramstr;
                    }
                    return true;                        
                }
            }
        }
    }
}

bool Cmdline::parseAssignment(int &opt, vector<string> &parsed,
                              PropertyType propertyType,
                              const char *propname,
                              const char *def)
{
    string param;
    bool haveParam = false;
    string cmdopt(m_argv[opt]);
    size_t off = cmdopt.find('=');
    if (off != cmdopt.npos) {
        // value embedded in option
        param = cmdopt.substr(off + 1);
        haveParam = true;
    } else if (!def && ++opt < m_argc) {
        // assume next entry is parameter
        param = m_argv[opt];
        parsed.push_back(m_argv[opt]);
        haveParam = true;
    } else if (def) {
        // use default
        param = def;
        haveParam = true;
    }

    return parseProp(propertyType,
                     cmdopt.c_str(),
                     haveParam ? param.c_str() : NULL,
                     propname);
}

bool Cmdline::listPropValues(const ConfigPropertyRegistry &validProps,
                                          const string &propName,
                                          const string &opt)
{
    const ConfigProperty *prop = validProps.find(propName);
    if (!prop && boost::iequals(propName, "type")) {
        SE_LOG_SHOW(NULL,
                    "%s\n"
                    "   <backend>[:<format>[:<version][!]]\n"
                    "   legacy property, replaced by 'backend', 'databaseFormat',\n"
                    "   'syncFormat', 'forceSyncFormat'",
                    opt.c_str());
        return true;
    } else if (!prop) {
        SE_LOG_ERROR(NULL, "%s: no such property", opt.c_str());
        return false;
    } else {
        ostringstream out;
        out << opt << endl;
        string comment = prop->getComment();

        if (comment != "") {
            list<string> commentLines;
            ConfigProperty::splitComment(comment, commentLines);
            BOOST_FOREACH(const string &line, commentLines) {
                out << "   " << line << endl;
            }
        } else {
            out << "   no documentation available" << endl;
        }
        SE_LOG_SHOW(NULL, "%s", out.str().c_str());
        return true;
    }
}

bool Cmdline::listProperties(const ConfigPropertyRegistry &validProps,
                                          const string &opt)
{
    // The first of several related properties has a comment.
    // Remember that comment and print it as late as possible,
    // that way related properties preceed their comment.
    string comment;
    bool needComma = false;
    ostringstream out;
    BOOST_FOREACH(const ConfigProperty *prop, validProps) {
        if (!prop->isHidden()) {
            string newComment = prop->getComment();

            if (newComment != "") {
                if (!comment.empty()) {
                    out << endl;
                    dumpComment(out, "   ", comment);
                    out << endl;
                    needComma = false;
                }
                comment = newComment;
            }
            std::string def = prop->getDefValue();
            if (def.empty()) {
                def = "no default";
            }
            ConfigProperty::Sharing sharing = prop->getSharing();
            if (needComma) {
                out << ", ";
            }
            out << boost::join(prop->getNames(), " = ")
                  << " (" << def << ", "
                  << ConfigProperty::sharing2str(sharing)
                  << (prop->isObligatory() ? ", required" : "")
                  << ")";
            needComma = true;
        }
    }
    out << endl;
    dumpComment(out, "   ", comment);
    SE_LOG_SHOW(NULL, "%s", out.str().c_str());
    return true;
}

static void findPeerProps(FilterConfigNode::ConfigFilter &filter,
                          ConfigPropertyRegistry &registry,
                          set<string> &peerProps)
{
    BOOST_FOREACH(StringPair entry, filter) {
        const ConfigProperty *prop = registry.find(entry.first);
        if (prop &&
            prop->getSharing() == ConfigProperty::NO_SHARING) {
            peerProps.insert(entry.first);
        }
    }
}

void Cmdline::checkForPeerProps()
{
    set<string> peerProps;

    BOOST_FOREACH(FullProps::value_type &entry, m_props) {
        ContextProps &props = entry.second;

        findPeerProps(props.m_syncProps, SyncConfig::getRegistry(), peerProps);
        BOOST_FOREACH(SourceProps::value_type &entry, props.m_sourceProps) {
            findPeerProps(entry.second, SyncSourceConfig::getRegistry(), peerProps);
        }
    }
    if (!peerProps.empty()) {
        string props = boost::join(peerProps, ", ");
        if (props == "forceSyncFormat, syncFormat") {
            // special case: these two properties might have been added by the
            // legacy "sync" property, which applies to both shared and unshared
            // properties => cannot determine that here anymore, so ignore it
        } else {
            SyncContext::throwError(string("per-peer (unshared) properties not allowed: ") +
                                    props);
        }
    }
}

void Cmdline::listDatabases(SyncSource *source, const string &header)
{
    if (!source) {
        // silently skip backends like the "file" backend which do not support
        // listing databases and return NULL unless configured properly
        return;
    }

    ostringstream out;
    out << header << ":\n";

    if (source->isInactive()) {
        out << source->getBackend() << ": not enabled during compilation or not usable in the current environment\n";
    } else {
        SyncSource::Databases databases = source->getDatabases();

        BOOST_FOREACH(const SyncSource::Database &database, databases) {
            out << "   " << database.m_name << " (" << database.m_uri << ")";
            if (database.m_isDefault) {
                out << " <default>";
            }
            out << endl;
        }
    }
    SE_LOG_SHOW(NULL, "%s", out.str().c_str());
    SE_LOG_SHOW(NULL, "\n");
}

void Cmdline::createDatabase(SyncSource *source, const string &header)
{
    if (!source) {
        SE_THROW(StringPrintf("%s:\ncannot access databases", header.c_str()));
        return;
    }

    // Only the name can be set via the command line. URI is chosen by backend.
    InitStateString databaseID = source->getDatabaseID();
    if (!databaseID.wasSet()) {
        SE_THROW("The 'database' property must be set to the name of the new database");
    }
    SyncSource::Database database = source->createDatabase(SyncSource::Database(databaseID, ""));
    SE_LOG_SHOW(NULL, "%s: database '%s' (%s) was created.",
                header.c_str(),
                database.m_name.c_str(),
                database.m_uri.c_str());
}

void Cmdline::removeDatabase(SyncSource *source, const string &header)
{
    if (!source) {
        SE_THROW(StringPrintf("%s:\ncannot access databases", header.c_str()));
        return;
    }

    InitStateString databaseID = source->getDatabaseID();
    if (!databaseID.wasSet()) {
        SE_THROW("The 'database' property was not set. Cowardly refusing to remove the default database. Set it to the empty string and try again if that was the intention.");
    }

    // determine URI
    source->open();
    SyncSource::Database database = source->getDatabase();
    if (database.m_uri.empty()) {
        SE_THROW(StringPrintf("Cannot determine database from 'database' property value '%s'.",
                              databaseID.c_str()));
    }

    source->deleteDatabase(database.m_uri);
    SE_LOG_SHOW(NULL, "%s: database '%s' (%s) was removed.",
                header.c_str(),
                database.m_name.c_str(),
                database.m_uri.c_str());
}

void Cmdline::dumpConfigs(const string &preamble,
                                       const SyncConfig::ConfigList &servers)
{
    ostringstream out;
    out << preamble << endl;
    BOOST_FOREACH(const SyncConfig::ConfigList::value_type &server,servers) {
        out << "   "  << server.first << " = " << server.second <<endl;
    }
    if (!servers.size()) {
        out << "   none" << endl;
    }
    SE_LOG_SHOW(NULL, "%s", out.str().c_str());
}

void Cmdline::dumpConfigTemplates(const string &preamble,
                                  const SyncConfig::TemplateList &templates,
                                  bool printRank,
                                  Logger::Level level)
{
    ostringstream out;
    out << preamble << endl;
    out << "   "  << "template name" << " = " << "template description";
    if (printRank) {
        out << "    " << "matching score in percent (100% = exact match)";
    }
    out << endl;

    BOOST_FOREACH(const SyncConfig::TemplateList::value_type server,templates) {
        out << "   "  << server->m_templateId << " = " << server->m_description;
        if (printRank){
            out << "    " << server->m_rank *20 << "%";
        }
        out << endl;
    }
    if (!templates.size()) {
        out << "   none" << endl;
    }
    SE_LOG(NULL, level, "%s", out.str().c_str());
}

void Cmdline::dumpProperties(const ConfigNode &configuredProps,
                             const ConfigPropertyRegistry &allProps,
                             int flags)
{
    list<string> perPeer, perContext, global;
    ostringstream out;

    BOOST_FOREACH(const ConfigProperty *prop, allProps) {
        if (prop->isHidden() ||
            ((flags & HIDE_PER_PEER) &&
             prop->getSharing() == ConfigProperty::NO_SHARING)) {
            continue;
        }
        if (!m_quiet) {
            string comment = prop->getComment();
            if (!comment.empty()) {
                out << endl;
                dumpComment(out, "# ", comment);
            }
        }
        InitStateString value = prop->getProperty(configuredProps);
        if (!value.wasSet()) {
            out << "# ";
        }
        out << prop->getMainName() << " = " << value.get() << endl;

        list<string> *type = NULL;
        switch (prop->getSharing()) {
        case ConfigProperty::GLOBAL_SHARING:
            type = &global;
            break;
        case ConfigProperty::SOURCE_SET_SHARING:
            type = &perContext;
            break;
        case ConfigProperty::NO_SHARING:
            type = &perPeer;
            break;
        }
        if (type) {
            type->push_back(prop->getMainName());
        }
    }

    if (!m_quiet && !(flags & HIDE_LEGEND)) {
        if (!perPeer.empty() ||
            !perContext.empty() ||
            !global.empty()) {
            out << endl;
        }
        if (!perPeer.empty()) {
            out << "# per-peer (unshared) properties: " << boost::join(perPeer, ", ") << endl;
        }
        if (!perContext.empty()) {
            out << "# shared by peers in same context: " << boost::join(perContext, ", ") << endl;
        }
        if (!global.empty()) {
            out << "# global properties: " << boost::join(global, ", ") << endl;
        }
    }

    SE_LOG_SHOW(NULL, "%s", out.str().c_str());
}

void Cmdline::dumpComment(ostream &stream,
                                       const string &prefix,
                                       const string &comment)
{
    list<string> commentLines;
    ConfigProperty::splitComment(comment, commentLines);
    BOOST_FOREACH(const string &line, commentLines) {
        stream << prefix << line << endl;
    }
}

void Cmdline::usage(bool full, const string &error, const string &param)
{
    SE_LOG_SHOW(NULL, "%s", synopsis);
    if (full) {
        SE_LOG_SHOW(NULL, "\nOptions:\n%s", options);
    }

    if (error != "") {
        SE_LOG_SHOW(NULL, "\n");
        SE_LOG_ERROR(NULL, "%s", error.c_str());
    }
    if (param != "") {
        SE_LOG_INFO(NULL, "use '%s%s?' to get a list of valid parameters",
                    param.c_str(),
                    boost::ends_with(param, "=") ? "" : " ");
    }
}

bool Cmdline::needConfigName()
{
    if (m_server.empty()) {
        usage(false, "No configuration name specified.");
        return false;
    } else {
        return true;
    }
}


SyncContext* Cmdline::createSyncClient() {
    return new SyncContext(m_server, true);
}

#ifdef ENABLE_UNIT_TESTS

/** simple line-by-line diff */
static string diffStrings(const string &lhs, const string &rhs)
{
    ostringstream res;

    typedef boost::split_iterator<string::const_iterator> string_split_iterator;
    string_split_iterator lit =
        boost::make_split_iterator(lhs, boost::first_finder("\n", boost::is_iequal()));
    string_split_iterator rit =
        boost::make_split_iterator(rhs, boost::first_finder("\n", boost::is_iequal()));
    while (lit != string_split_iterator() &&
           rit != string_split_iterator()) {
        if (*lit != *rit) {
            res << "< " << *lit << endl;
            res << "> " << *rit << endl;
        }
        ++lit;
        ++rit;
    }

    while (lit != string_split_iterator()) {
        res << "< " << *lit << endl;
        ++lit;
    }

    while (rit != string_split_iterator()) {
        res << "> " << *rit << endl;
        ++rit;
    }

    return res.str();
}

# define CPPUNIT_ASSERT_EQUAL_DIFF( expected, actual )      \
    do { \
        string expected_ = (expected);                                  \
        string actual_ = (actual);                                      \
        if (expected_ != actual_) {                                     \
            CPPUNIT_NS::Message cpputMsg_(string("expected:\n") +       \
                                          expected_);                   \
            cpputMsg_.addDetail(string("actual:\n") +                   \
                                actual_);                               \
            cpputMsg_.addDetail(string("diff:\n") +                     \
                                diffStrings(expected_, actual_));       \
            CPPUNIT_NS::Asserter::fail( cpputMsg_,                      \
                                        CPPUNIT_SOURCELINE() );         \
        } \
    } while ( false )

// true if <word> =
static bool isPropAssignment(const string &buffer) {
    // ignore these comments (occur in type description)
    if (boost::starts_with(buffer, "KCalExtended = ") ||
        boost::starts_with(buffer, "mkcal = ") ||
        boost::starts_with(buffer, "QtContacts = ")) {
        return false;
    }
                                
    size_t start = 0;
    while (start < buffer.size() &&
           !isspace(buffer[start])) {
        start++;
    }
    if (start + 3 <= buffer.size() &&
        buffer.substr(start, 3) == " = ") {
        return true;
    } else {
        return false;
    }
}

// remove pure comment lines from buffer,
// also empty lines,
// also defaultPeer and keyring (because reference properties do not include global props)
static string filterConfig(const string &buffer)
{
    ostringstream res;

    typedef boost::split_iterator<string::const_iterator> string_split_iterator;
    for (string_split_iterator it =
             boost::make_split_iterator(buffer, boost::first_finder("\n", boost::is_iequal()));
         it != string_split_iterator();
         ++it) {
        string line = boost::copy_range<string>(*it);
        if (!line.empty() &&
            line.find("defaultPeer =") == line.npos &&
            line.find("keyring =") == line.npos &&
            (!boost::starts_with(line, "# ") ||
             isPropAssignment(line.substr(2)))) {
            res << line << endl;
        }
    }

    return res.str();
}

static string removeComments(const string &buffer)
{
    ostringstream res;

    typedef boost::split_iterator<string::const_iterator> string_split_iterator;
    for (string_split_iterator it =
             boost::make_split_iterator(buffer, boost::first_finder("\n", boost::is_iequal()));
         it != string_split_iterator();
         ++it) {
        string line = boost::copy_range<string>(*it);
        if (!line.empty() &&
            !boost::starts_with(line, "#")) {
            res << line << endl;
        }
    }

    return res.str();
}

static string injectValues(const string &buffer)
{
    string res = buffer;

#if 0
    // username/password not set in templates, only in configs created
    // via the command line - not anymore, but if it ever comes back,
    // here's the place for it
    boost::replace_first(res,
                         "# username = ",
                         "username = your SyncML server account name");
    boost::replace_first(res,
                         "# password = ",
                         "password = your SyncML server password");
#endif
    return res;
}

// remove lines indented with spaces
static string filterIndented(const string &buffer)
{
    ostringstream res;
    bool first = true;

    typedef boost::split_iterator<string::const_iterator> string_split_iterator;
    for (string_split_iterator it =
             boost::make_split_iterator(buffer, boost::first_finder("\n", boost::is_iequal()));
         it != string_split_iterator();
         ++it) {
        if (!boost::starts_with(*it, " ")) {
            if (!first) {
                res << endl;
            } else {
                first = false;
            }
            res << *it;
        }
    }

    return res.str();
}

// sort lines by file, preserving order inside each line
static void sortConfig(string &config)
{
    // file name, line number, property
    typedef pair<string, pair<int, string> > line_t;
    vector<line_t> lines;
    typedef boost::split_iterator<string::iterator> string_split_iterator;
    int linenr = 0;
    for (string_split_iterator it =
             boost::make_split_iterator(config, boost::first_finder("\n", boost::is_iequal()));
         it != string_split_iterator();
         ++it, ++linenr) {
        string line(it->begin(), it->end());
        if (line.empty()) {
            continue;
        }

        size_t colon = line.find(':');
        string prefix = line.substr(0, colon);
        lines.push_back(make_pair(prefix, make_pair(linenr, line.substr(colon))));
    }

    // stable sort because of line number
    sort(lines.begin(), lines.end());

    size_t len = config.size();
    config.resize(0);
    config.reserve(len);
    BOOST_FOREACH(const line_t &line, lines) {
        config += line.first;
        config += line.second.second;
        config += "\n";
    }
}

// convert the internal config dump to .ini style (--print-config)
static string internalToIni(const string &config)
{
    ostringstream res;

    string section;
    typedef boost::split_iterator<string::const_iterator> string_split_iterator;
    for (string_split_iterator it =
             boost::make_split_iterator(config, boost::first_finder("\n", boost::is_iequal()));
         it != string_split_iterator();
         ++it) {
        string line(it->begin(), it->end());
        if (line.empty()) {
            continue;
        }

        size_t colon = line.find(':');
        string prefix = line.substr(0, colon);

        // internal values are not part of the --print-config output
        if (boost::contains(prefix, ".internal.ini") ||
            boost::contains(line, "= internal value")) {
            continue;
        }

        // --print-config also doesn't duplicate the "type" property
        // => remove the shared property
        if (boost::contains(line, ":type = ") &&
            boost::starts_with(line, "sources/")) {
            continue;
        }

        // sources/<name>/config.ini or
        // spds/sources/<name>/config.ini
        size_t endslash = prefix.rfind('/');
        if (endslash != line.npos && endslash > 1) {
            size_t slash = prefix.rfind('/', endslash - 1);
            if (slash != line.npos) {
                string newsource = prefix.substr(slash + 1, endslash - slash - 1);
                if (newsource != section &&
                    prefix.find("/sources/") != prefix.npos &&
                    newsource != "syncml") {
                    res << "[" << newsource << "]" << endl;
                    section = newsource;
                }
            }
        }
        string assignment = line.substr(colon + 1);
        // substitude aliases with generic values
        boost::replace_first(assignment, "= syncml:auth-md5", "= md5");
        boost::replace_first(assignment, "= syncml:auth-basix", "= basic");
        res << assignment << endl;
    }

    return res.str();
}

/** result of removeComments(filterRandomUUID(filterConfig())) for Google Calendar template/config */
static const std::string googlecaldav =
               "syncURL = https://www.google.com/calendar/dav/%u/user/?SyncEvolution=Google\n"
               "printChanges = 0\n"
               "dumpData = 0\n"
               "deviceId = fixed-devid\n"
               "IconURI = image://themedimage/icons/services/google-calendar\n"
               "ConsumerReady = 1\n"
               "peerType = WebDAV\n"
               "[calendar]\n"
               "sync = two-way\n"
               "backend = CalDAV\n";

/** result of removeComments(filterRandomUUID(filterConfig())) for Yahoo Calendar + Contacts */
static const std::string yahoo =
               "printChanges = 0\n"
               "dumpData = 0\n"
               "deviceId = fixed-devid\n"
               "IconURI = image://themedimage/icons/services/yahoo\n"
               "ConsumerReady = 1\n"
               "peerType = WebDAV\n"
               "[addressbook]\n"
               "sync = disabled\n"
               "backend = CardDAV\n"
               "[calendar]\n"
               "sync = two-way\n"
               "backend = CalDAV\n";

/**
 * Testing is based on a text representation of a directory
 * hierarchy where each line is of the format
 * <file path>:<line in file>
 *
 * The order of files is alphabetical, of lines in the file as
 * in the file. Lines in the file without line break cannot
 * be represented.
 *
 * The root of the hierarchy is not part of the representation
 * itself.
 */
class CmdlineTest : public CppUnit::TestFixture {
    CPPUNIT_TEST_SUITE(CmdlineTest);
    CPPUNIT_TEST(testFramework);
    CPPUNIT_TEST(testSetupScheduleWorld);
    CPPUNIT_TEST(testFutureConfig);
    CPPUNIT_TEST(testPeerConfigMigration);
    CPPUNIT_TEST(testContextConfigMigration);
    CPPUNIT_TEST(testSetupDefault);
    CPPUNIT_TEST(testSetupRenamed);
    CPPUNIT_TEST(testSetupFunambol);
    CPPUNIT_TEST(testSetupSynthesis);
    CPPUNIT_TEST(testPrintServers);
    CPPUNIT_TEST(testPrintFileTemplates);
    CPPUNIT_TEST(testPrintFileTemplatesConfig);
    CPPUNIT_TEST(testTemplate);
    CPPUNIT_TEST(testMatchTemplate);
    CPPUNIT_TEST(testAddSource);
    CPPUNIT_TEST(testSync);
    CPPUNIT_TEST(testKeyring);
    CPPUNIT_TEST(testWebDAV);
    CPPUNIT_TEST(testConfigure);
    CPPUNIT_TEST(testConfigureSources);
    CPPUNIT_TEST(testOldConfigure);
    CPPUNIT_TEST(testMigrate);
    CPPUNIT_TEST(testMigrateContext);
    CPPUNIT_TEST(testMigrateAutoSync);
    CPPUNIT_TEST_SUITE_END();
    
public:
    CmdlineTest() :
        m_testDir("CmdlineTest")
    {
    }

    void setUp()
    {
        rm_r(m_testDir);
        mkdir_p(m_testDir);
    }

protected:

    /** verify that createFiles/scanFiles themselves work */
    void testFramework() {
        const string root(m_testDir);
        const string content("baz:line\n"
                             "caz/subdir:booh\n"
                             "caz/subdir2/sub:# comment\n"
                             "caz/subdir2/sub:# foo = bar\n"
                             "caz/subdir2/sub:# empty = \n"
                             "caz/subdir2/sub:# another comment\n"
                             "foo:bar1\n"
                             "foo:\n"
                             "foo: \n"
                             "foo:bar2\n");
        const string filtered("baz:line\n"
                              "caz/subdir:booh\n"
                              "caz/subdir2/sub:# foo = bar\n"
                              "caz/subdir2/sub:# empty = \n"
                              "foo:bar1\n"
                              "foo: \n"
                              "foo:bar2\n");
        createFiles(root, content);
        string res = scanFiles(root);
        CPPUNIT_ASSERT_EQUAL_DIFF(filtered, res);
    }

    void removeRandomUUID(string &buffer) {
        string uuidstr = "deviceId = syncevolution-";
        size_t uuid = buffer.find(uuidstr);
        CPPUNIT_ASSERT(uuid != buffer.npos);
        size_t end = buffer.find("\n", uuid + uuidstr.size());
        CPPUNIT_ASSERT(end != buffer.npos);
        buffer.replace(uuid, end - uuid, "deviceId = fixed-devid");
    }

    string filterRandomUUID(const string &buffer) {
        string copy = buffer;
        removeRandomUUID(copy);
        return copy;
    }

    /** create new configurations */
    void testSetupScheduleWorld() { doSetupScheduleWorld(false); }
    void doSetupScheduleWorld(bool shared) {
        string root;
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        root = m_testDir;
        root += "/syncevolution/default";
        string peer;
        if (shared) {
            peer = root + "/peers/scheduleworld";
        } else {
            peer = root;
        }

        {
            rm_r(peer);
            TestCmdline cmdline("--configure",
                                "--sync-property", "proxyHost = proxy",
                                "scheduleworld",
                                "addressbook",
                                NULL);
            cmdline.doit();
            string res = scanFiles(root);
            removeRandomUUID(res);
            string expected = ScheduleWorldConfig();
            sortConfig(expected);
            boost::replace_first(expected,
                                 "# proxyHost = ",
                                 "proxyHost = proxy");
            boost::replace_all(expected,
                               "sync = two-way",
                               "sync = disabled");
            boost::replace_first(expected,
                                 "addressbook/config.ini:sync = disabled",
                                 "addressbook/config.ini:sync = two-way");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
        }

        {
            rm_r(peer);
            TestCmdline cmdline("--configure",
                                "--sync-property", "deviceID = fixed-devid",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            string res = scanFiles(root);
            string expected = ScheduleWorldConfig();
            sortConfig(expected);
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
        }
    }

    void expectTooOld() {
        bool caught = false;
        try {
            SyncConfig config("scheduleworld");
        } catch (const StatusException &ex) {
            caught = true;
            if (ex.syncMLStatus() != STATUS_RELEASE_TOO_OLD) {
                throw;
            } else {
                CPPUNIT_ASSERT_EQUAL(StringPrintf("SyncEvolution %s is too old to read configuration 'scheduleworld', please upgrade SyncEvolution.", VERSION),
                                     string(ex.what()));
            }
        }
        CPPUNIT_ASSERT(caught);
    }

    void testFutureConfig() {
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        doSetupScheduleWorld(false);
        // bump min/cur version to something not supported, then
        // try to read => should fail
        IniFileConfigNode root(m_testDir, "/syncevolution/.internal.ini", false);
        IniFileConfigNode context(m_testDir + "/syncevolution/default", ".internal.ini", false);
        IniFileConfigNode peer(m_testDir + "/syncevolution/default/peers/scheduleworld", ".internal.ini", false);
        root.setProperty("rootMinVersion", StringPrintf("%d", CONFIG_ROOT_MIN_VERSION + 1));
        root.setProperty("rootCurVersion", StringPrintf("%d", CONFIG_ROOT_CUR_VERSION + 1));
        root.flush();
        context.setProperty("contextMinVersion", StringPrintf("%d", CONFIG_CONTEXT_MIN_VERSION + 1));
        context.setProperty("contextCurVersion", StringPrintf("%d", CONFIG_CONTEXT_CUR_VERSION + 1));
        context.flush();
        peer.setProperty("peerMinVersion", StringPrintf("%d", CONFIG_PEER_MIN_VERSION + 1));
        peer.setProperty("peerCurVersion", StringPrintf("%d", CONFIG_PEER_CUR_VERSION + 1));
        peer.flush();

        expectTooOld();

        root.setProperty("rootMinVersion", StringPrintf("%d", CONFIG_ROOT_MIN_VERSION));
        root.flush();
        expectTooOld();

        context.setProperty("contextMinVersion", StringPrintf("%d", CONFIG_CONTEXT_MIN_VERSION));
        context.flush();
        expectTooOld();

        // okay now
        peer.setProperty("peerMinVersion", StringPrintf("%d", CONFIG_PEER_MIN_VERSION));
        peer.flush();
        SyncConfig config("scheduleworld");
    }

    void expectMigration(const std::string &config) {
        bool caught = false;
        try {
            SyncConfig c(config);
            c.prepareConfigForWrite();
        } catch (const StatusException &ex) {
            caught = true;
            if (ex.syncMLStatus() != STATUS_MIGRATION_NEEDED) {
                throw;
            } else {
                CPPUNIT_ASSERT_EQUAL(StringPrintf("Proceeding would modify config '%s' such that the "
                                                  "previous SyncEvolution release will not be able to use it. "
                                                  "Stopping now. Please explicitly acknowledge this step by "
                                                  "running the following command on the command line: "
                                                  "syncevolution --migrate '%s'",
                                                  config.c_str(),
                                                  config.c_str()),
                                     string(ex.what()));
            }
        }
        CPPUNIT_ASSERT(caught);
    }

    void testPeerConfigMigration() {
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        doSetupScheduleWorld(false);
        // decrease min/cur version to something no longer supported,
        // then try to write => should migrate in release mode and fail otherwise
        IniFileConfigNode peer(m_testDir + "/syncevolution/default/peers/scheduleworld", ".internal.ini", false);
        peer.setProperty("peerMinVersion", StringPrintf("%d", CONFIG_PEER_CUR_VERSION - 1));
        peer.setProperty("peerCurVersion", StringPrintf("%d", CONFIG_PEER_CUR_VERSION - 1));
        peer.flush();

        SyncContext::setStableRelease(false);
        expectMigration("scheduleworld");

        SyncContext::setStableRelease(true);
        {
            SyncConfig config("scheduleworld");
            config.prepareConfigForWrite();
        }
        {
            TestCmdline cmdline("--print-servers", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("Configured servers:\n"
                                      "   scheduleworld = CmdlineTest/syncevolution/default/peers/scheduleworld\n"
                                      "   scheduleworld.old = CmdlineTest/syncevolution/default/peers/scheduleworld.old\n",
                                      cmdline.m_out.str());
        }

        // should be okay now
        SyncContext::setStableRelease(false);
        {
            SyncConfig config("scheduleworld");
            config.prepareConfigForWrite();
        }

        // do the same migration with command line
        SyncContext::setStableRelease(false);
        rm_r(m_testDir + "/syncevolution/default/peers/scheduleworld");
        CPPUNIT_ASSERT_EQUAL(0, rename((m_testDir + "/syncevolution/default/peers/scheduleworld.old").c_str(),
                                       (m_testDir + "/syncevolution/default/peers/scheduleworld").c_str()));
        {
            TestCmdline cmdline("--migrate", "scheduleworld", NULL);
            cmdline.doit();
        }
        {
            SyncConfig config("scheduleworld");
            config.prepareConfigForWrite();
        }        
        {
            TestCmdline cmdline("--print-servers", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("Configured servers:\n"
                                      "   scheduleworld = CmdlineTest/syncevolution/default/peers/scheduleworld\n"
                                      "   scheduleworld.old = CmdlineTest/syncevolution/default/peers/scheduleworld.old\n",
                                      cmdline.m_out.str());
        }
    }

    void testContextConfigMigration() {
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        doSetupScheduleWorld(false);
        // decrease min/cur version to something no longer supported,
        // then try to write => should migrate in release mode and fail otherwise
        IniFileConfigNode context(m_testDir + "/syncevolution/default", ".internal.ini", false);
        context.setProperty("contextMinVersion", StringPrintf("%d", CONFIG_CONTEXT_CUR_VERSION - 1));
        context.setProperty("contextCurVersion", StringPrintf("%d", CONFIG_CONTEXT_CUR_VERSION - 1));
        context.flush();

        SyncContext::setStableRelease(false);
        expectMigration("@default");

        SyncContext::setStableRelease(true);
        {
            SyncConfig config("@default");
            config.prepareConfigForWrite();
        }
        {
            TestCmdline cmdline("--print-servers", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("Configured servers:\n"
                                      "   scheduleworld = CmdlineTest/syncevolution/default/peers/scheduleworld\n"
                                      "   scheduleworld.old@default.old = CmdlineTest/syncevolution/default.old/peers/scheduleworld.old\n",
                                      cmdline.m_out.str());
        }

        // should be okay now
        SyncContext::setStableRelease(false);
        {
            SyncConfig config("@default");
            config.prepareConfigForWrite();
        }

        // do the same migration with command line
        SyncContext::setStableRelease(false);
        rm_r(m_testDir + "/syncevolution/default");
        CPPUNIT_ASSERT_EQUAL(0, rename((m_testDir + "/syncevolution/default.old/peers/scheduleworld.old").c_str(),
                                       (m_testDir + "/syncevolution/default.old/peers/scheduleworld").c_str()));
        CPPUNIT_ASSERT_EQUAL(0, rename((m_testDir + "/syncevolution/default.old").c_str(),
                                       (m_testDir + "/syncevolution/default").c_str()));
        {
            TestCmdline cmdline("--migrate", "@default", NULL);
            cmdline.doit();
        }
        {
            SyncConfig config("@default");
            config.prepareConfigForWrite();
        }        
        {
            TestCmdline cmdline("--print-servers", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("Configured servers:\n"
                                      "   scheduleworld = CmdlineTest/syncevolution/default/peers/scheduleworld\n"
                                      "   scheduleworld.old@default.old = CmdlineTest/syncevolution/default.old/peers/scheduleworld.old\n",
                                      cmdline.m_out.str());
        }
    }


    void testSetupDefault() {
        string root;
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        root = m_testDir;
        root += "/syncevolution/default";
        TestCmdline cmdline("--configure",
                            "--template", "default",
                            "--sync-property", "deviceID = fixed-devid",
                            "some-other-server",
                            NULL);
        cmdline.doit();
        string res = scanFiles(root, "some-other-server");
        string expected = DefaultConfig();
        sortConfig(expected);
        boost::replace_all(expected, "/syncevolution/", "/some-other-server/");
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
    }

    void testSetupRenamed() {
        string root;
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        root = m_testDir;
        root += "/syncevolution/default";
        TestCmdline cmdline("--configure",
                            "--template", "scheduleworld",
                            "--sync-property", "deviceID = fixed-devid",
                            "scheduleworld2",
                            NULL);
        cmdline.doit();
        string res = scanFiles(root, "scheduleworld2");
        string expected = ScheduleWorldConfig();
        sortConfig(expected);
        boost::replace_all(expected, "/scheduleworld/", "/scheduleworld2/");
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
    }

    void testSetupFunambol() { doSetupFunambol(false); }
    void doSetupFunambol(bool shared) {
        string root;
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        root = m_testDir;
        root += "/syncevolution/default";
        string peer;
        if (shared) {
            peer = root + "/peers/funambol";
        } else {
            peer = root;
        }

        rm_r(peer);
        const char * const argv_fixed[] = {
                "--configure",
                "--sync-property", "deviceID = fixed-devid",
                // templates are case-insensitive
                "FunamBOL",
                NULL
        }, * const argv_shared[] = {
            "--configure",
            "FunamBOL",
            NULL
        };
        TestCmdline cmdline(shared ? argv_shared : argv_fixed);
        cmdline.doit();
        string res = scanFiles(root, "funambol");
        string expected = FunambolConfig();
        sortConfig(expected);
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
    }

    void testSetupSynthesis() { doSetupSynthesis(false); }
    void doSetupSynthesis(bool shared) {
        string root;
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        root = m_testDir;
        root += "/syncevolution/default";
        string peer;
        if (shared) {
            peer = root + "/peers/synthesis";
        } else {
            peer = root;
        }
        rm_r(peer);
        const char * const argv_fixed[] = {
                "--configure",
                "--sync-property", "deviceID = fixed-devid",
                "synthesis",
                NULL
        }, * const argv_shared[] = {
            "--configure",
            "synthesis",
            NULL
        };
        TestCmdline cmdline(shared ? argv_shared : argv_fixed);
        cmdline.doit();
        string res = scanFiles(root, "synthesis");
        string expected = SynthesisConfig();
        sortConfig(expected);
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
    }

    void testTemplate() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        TestCmdline failure("--template", NULL);

        CPPUNIT_ASSERT(!failure.m_cmdline->parse());
        CPPUNIT_ASSERT_NO_THROW(failure.expectUsageError("[ERROR] missing parameter for '--template'\n"));

        TestCmdline help("--template", "? ", NULL);
        help.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("Available configuration templates (servers):\n"
                                  "   template name = template description\n"
                                  "   eGroupware = http://www.egroupware.org\n"
                                  "   Funambol = http://my.funambol.com\n"
                                  "   Google_Calendar = event sync via CalDAV, use for the 'target-config@google-calendar' config\n"
                                  "   Google_Contacts = contact sync via SyncML, see http://www.google.com/support/mobile/bin/topic.py?topic=22181\n"
                                  "   Goosync = http://www.goosync.com/\n"
                                  "   Memotoo = http://www.memotoo.com\n"
                                  "   Mobical = https://www.everdroid.com\n"
                                  "   Oracle = http://www.oracle.com/technology/products/beehive/index.html\n"
                                  "   Ovi = http://www.ovi.com\n"
                                  "   ScheduleWorld = server no longer in operation\n"
                                  "   SyncEvolution = http://www.syncevolution.org\n"
                                  "   Synthesis = http://www.synthesis.ch\n"
                                  "   WebDAV = contact and event sync using WebDAV, use for the 'target-config@<server>' config\n"
                                  "   Yahoo = contact and event sync using WebDAV, use for the 'target-config@yahoo' config\n",
                                  help.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", help.m_err.str());
    }

    void testMatchTemplate() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "testcases/templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", "/dev/null");

        TestCmdline help1("--template", "?nokia 7210c", NULL);
        help1.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("Available configuration templates (clients):\n"
                "   template name = template description    matching score in percent (100% = exact match)\n"
                "   Nokia_7210c = Template for Nokia S40 series Phone    100%\n"
                "   SyncEvolution_Client = SyncEvolution server side template    40%\n",
                help1.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", help1.m_err.str());
        TestCmdline help2("--template", "?nokia", NULL);
        help2.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("Available configuration templates (clients):\n"
                "   template name = template description    matching score in percent (100% = exact match)\n"
                "   Nokia_7210c = Template for Nokia S40 series Phone    100%\n"
                "   SyncEvolution_Client = SyncEvolution server side template    40%\n",
                help2.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", help2.m_err.str());
        TestCmdline help3("--template", "?7210c", NULL);
        help3.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("Available configuration templates (clients):\n"
                "   template name = template description    matching score in percent (100% = exact match)\n"
                "   Nokia_7210c = Template for Nokia S40 series Phone    60%\n"
                "   SyncEvolution_Client = SyncEvolution server side template    20%\n",
                help3.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", help3.m_err.str());
        TestCmdline help4("--template", "?syncevolution client", NULL);
        help4.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("Available configuration templates (clients):\n"
                "   template name = template description    matching score in percent (100% = exact match)\n"
                "   SyncEvolution_Client = SyncEvolution server side template    100%\n"
                "   Nokia_7210c = Template for Nokia S40 series Phone    40%\n",
                help4.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", help4.m_err.str());
    }

    void testPrintServers() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        doSetupScheduleWorld(false);
        doSetupSynthesis(true);
        doSetupFunambol(true);

        TestCmdline cmdline("--print-servers", NULL);
        cmdline.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("Configured servers:\n"
                                  "   funambol = CmdlineTest/syncevolution/default/peers/funambol\n"
                                  "   scheduleworld = CmdlineTest/syncevolution/default/peers/scheduleworld\n"
                                  "   synthesis = CmdlineTest/syncevolution/default/peers/synthesis\n",
                                  cmdline.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
    }

    void testPrintFileTemplates() {
        // use local copy of templates in build dir (no need to install)
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "./templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        doPrintFileTemplates();
    }

    void testPrintFileTemplatesConfig() {
        // simulate reading templates from user's XDG HOME
        symlink("../templates", (m_testDir + "/syncevolution-templates").c_str());
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "/dev/null");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        doPrintFileTemplates();
    }

    void doPrintFileTemplates() {
        // Compare only the properties which are really set.
        //
        // note that "backend" will be take from the @default context if one
        // exists, so run this before setting up Funambol below
        {
            TestCmdline cmdline("--print-config", "--template", "google calendar", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF(googlecaldav,
                                      removeComments(filterRandomUUID(filterConfig(cmdline.m_out.str()))));
        }

        {
            TestCmdline cmdline("--print-config", "--template", "yahoo", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF(yahoo,
                                      removeComments(filterRandomUUID(filterConfig(cmdline.m_out.str()))));
        }

        testSetupFunambol();

        {
            TestCmdline cmdline("--print-config", "--template", "scheduleworld", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            string actual = cmdline.m_out.str();
            // deviceId must be the one from Funambol
            CPPUNIT_ASSERT(boost::contains(actual, "deviceId = fixed-devid"));
            string filtered = injectValues(filterConfig(actual));
            CPPUNIT_ASSERT_EQUAL_DIFF(filterConfig(internalToIni(ScheduleWorldConfig())),
                                      filtered);
            // there should have been comments
            CPPUNIT_ASSERT(actual.size() > filtered.size());
        }

        {
            TestCmdline cmdline("--print-config", "funambol", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF(filterConfig(internalToIni(FunambolConfig())),
                                      injectValues(filterConfig(cmdline.m_out.str())));
        }
    }

    void testAddSource() {
        string root;
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        testSetupScheduleWorld();

        root = m_testDir;
        root += "/syncevolution/default";

        {
            TestCmdline cmdline("--configure",
                                "--source-property", "uri = dummy",
                                "scheduleworld",
                                "xyz",
                                NULL);
            cmdline.doit();
            string res = scanFiles(root);
            string expected = ScheduleWorldConfig();
            expected += "\n"
                "peers/scheduleworld/sources/xyz/.internal.ini:# adminData = \n"
                "peers/scheduleworld/sources/xyz/.internal.ini:# synthesisID = 0\n"
                "peers/scheduleworld/sources/xyz/config.ini:# sync = disabled\n"
                "peers/scheduleworld/sources/xyz/config.ini:uri = dummy\n"
                "peers/scheduleworld/sources/xyz/config.ini:# syncFormat = \n"
                "peers/scheduleworld/sources/xyz/config.ini:# forceSyncFormat = 0\n"
                "sources/xyz/config.ini:# backend = select backend\n"
                "sources/xyz/config.ini:# database = \n"
                "sources/xyz/config.ini:# databaseFormat = \n"
                "sources/xyz/config.ini:# databaseUser = \n"
                "sources/xyz/config.ini:# databasePassword = ";
            sortConfig(expected);
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);
        }
    }

    void testSync() {
        TestCmdline failure("--sync", NULL);
        CPPUNIT_ASSERT(!failure.m_cmdline->parse());
        CPPUNIT_ASSERT_NO_THROW(failure.expectUsageError("[ERROR] missing parameter for '--sync'\n"));

        TestCmdline failure2("--sync", "foo", NULL);
        CPPUNIT_ASSERT(!failure2.m_cmdline->parse());
        CPPUNIT_ASSERT_EQUAL_DIFF("", failure2.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("[ERROR] '--sync foo': not one of the valid values (two-way, slow, refresh-from-local, refresh-from-remote = refresh, one-way-from-local, one-way-from-remote = one-way, refresh-from-client = refresh-client, refresh-from-server = refresh-server, one-way-from-client = one-way-client, one-way-from-server = one-way-server, local-cache-slow, local-cache-incremental = local-cache, disabled = none)\n", failure2.m_err.str());

        TestCmdline failure3("--sync=foo", NULL);
        CPPUNIT_ASSERT(!failure3.m_cmdline->parse());
        CPPUNIT_ASSERT_EQUAL_DIFF("", failure3.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("[ERROR] '--sync=foo': not one of the valid values (two-way, slow, refresh-from-local, refresh-from-remote = refresh, one-way-from-local, one-way-from-remote = one-way, refresh-from-client = refresh-client, refresh-from-server = refresh-server, one-way-from-client = one-way-client, one-way-from-server = one-way-server, local-cache-slow, local-cache-incremental = local-cache, disabled = none)\n", failure3.m_err.str());

        TestCmdline help("--sync", " ?", NULL);
        help.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("--sync\n"
                                  "   Requests a certain synchronization mode when initiating a sync:\n"
                                  "   \n"
                                  "     two-way\n"
                                  "       only send/receive changes since last sync\n"
                                  "     slow\n"
                                  "       exchange all items\n"
                                  "     refresh-from-remote\n"
                                  "       discard all local items and replace with\n"
                                  "       the items on the peer\n"
                                  "     refresh-from-local\n"
                                  "       discard all items on the peer and replace\n"
                                  "       with the local items\n"
                                  "     one-way-from-remote\n"
                                  "       transmit changes from peer\n"
                                  "     one-way-from-local\n"
                                  "       transmit local changes\n"
                                  "     local-cache-slow (server only)\n"
                                  "       mirror remote data locally, transferring all data\n"
                                  "     local-cache-incremental (server only)\n"
                                  "       mirror remote data locally, transferring only changes;\n"
                                  "       falls back to local-cache-slow automatically if necessary\n"
                                 "     disabled (or none)\n"
                                  "       synchronization disabled\n"
                                  "   \n"
                                  "   refresh/one-way-from-server/client are also supported. Their use is\n"
                                  "   discouraged because the direction of the data transfer depends\n"
                                  "   on the role of the local side (can be server or client), which is\n"
                                  "   not always obvious.\n"
                                  "   \n"
                                  "   When accepting a sync session in a SyncML server (HTTP server), only\n"
                                  "   sources with sync != disabled are made available to the client,\n"
                                  "   which chooses the final sync mode based on its own configuration.\n"
                                  "   When accepting a sync session in a SyncML client (local sync with\n"
                                  "   the server contacting SyncEvolution on a device), the sync mode\n"
                                  "   specified in the client is typically overriden by the server.\n",
                                  help.m_out.str());
        CPPUNIT_ASSERT_EQUAL_DIFF("", help.m_err.str());

        TestCmdline filter("--sync", "refresh-from-server", NULL);
        CPPUNIT_ASSERT(filter.m_cmdline->parse());
        CPPUNIT_ASSERT(!filter.m_cmdline->run());
        CPPUNIT_ASSERT_NO_THROW(filter.expectUsageError("[ERROR] No configuration name specified.\n"));
        CPPUNIT_ASSERT_EQUAL_DIFF("sync = refresh-from-server",
                                  string(filter.m_cmdline->m_props[""].m_sourceProps[""]));
        CPPUNIT_ASSERT_EQUAL_DIFF("",                                  string(filter.m_cmdline->m_props[""].m_syncProps));

        TestCmdline filter2("--source-property", "sync=refresh", NULL);
        CPPUNIT_ASSERT(filter2.m_cmdline->parse());
        CPPUNIT_ASSERT(!filter2.m_cmdline->run());
        CPPUNIT_ASSERT_NO_THROW(filter2.expectUsageError("[ERROR] No configuration name specified.\n"));
        CPPUNIT_ASSERT_EQUAL_DIFF("sync = refresh",
                                  string(filter2.m_cmdline->m_props[""].m_sourceProps[""]));
        CPPUNIT_ASSERT_EQUAL_DIFF("",
                                  string(filter2.m_cmdline->m_props[""].m_syncProps));

        TestCmdline filter3("--source-property", "xyz=1", NULL);
        CPPUNIT_ASSERT(!filter3.m_cmdline->parse());
        CPPUNIT_ASSERT_EQUAL(string(""), filter3.m_out.str());
        CPPUNIT_ASSERT_EQUAL(string("[ERROR] '--source-property xyz=1': no such property\n"), filter3.m_err.str());

        TestCmdline filter4("xyz=1", NULL);
        CPPUNIT_ASSERT(!filter4.m_cmdline->parse());
        CPPUNIT_ASSERT_NO_THROW(filter4.expectUsageError("[ERROR] unrecognized property in 'xyz=1'\n"));

        TestCmdline filter5("=1", NULL);
        CPPUNIT_ASSERT(!filter5.m_cmdline->parse());
        CPPUNIT_ASSERT_NO_THROW(filter5.expectUsageError("[ERROR] a property name must be given in '=1'\n"));
    }

    void testKeyring() {
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        rm_r(m_testDir);
        {
            TestCmdline cmdline(NULL, NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(false, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--sync-property", "keyring=True", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("keyring=True", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=true", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=1", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=Yes", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=false", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_FALSE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=0", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_FALSE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=NO", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_FALSE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=GNOME", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_STRING, keyring.getValue());
            CPPUNIT_ASSERT_EQUAL(std::string("GNOME"), keyring.get());
        }

        // Broken command line: treated like a sync, but config doesn't exist.
        {
            TestCmdline cmdline("keyring=KDE", "@foobar", NULL);
            cmdline.doit(false);
            CPPUNIT_ASSERT_EQUAL(std::string(""), cmdline.m_out.str());
            CPPUNIT_ASSERT_EQUAL(std::string("[INFO] Configuration \"@foobar\" does not refer to a sync peer.\n[ERROR] Cannot proceed with sync without a configuration."), cmdline.m_err.str());
        }
        {
            TestCmdline cmdline("keyring=KDE", "nosuchpeer@foobar", NULL);
            cmdline.doit(false);
            CPPUNIT_ASSERT_EQUAL(std::string(""), cmdline.m_out.str());
            CPPUNIT_ASSERT_EQUAL(std::string("[INFO] Configuration \"nosuchpeer@foobar\" does not exist.\n[ERROR] Cannot proceed with sync without a configuration."), cmdline.m_err.str());
        }

        // empty config prop
        {
            TestCmdline cmdline("--configure", "@default", NULL);
            cmdline.doit();
        }

        // Try broken command line again.
        {
            TestCmdline cmdline("keyring=KDE", "@foobar", NULL);
            cmdline.doit(false);
            CPPUNIT_ASSERT_EQUAL(std::string(""), cmdline.m_out.str());
            CPPUNIT_ASSERT_EQUAL(std::string("[INFO] Configuration \"@foobar\" does not refer to a sync peer.\n[ERROR] Cannot proceed with sync without a configuration."), cmdline.m_err.str());
        }
        {
            TestCmdline cmdline("keyring=KDE", "nosuchpeer@foobar", NULL);
            cmdline.doit(false);
            CPPUNIT_ASSERT_EQUAL(std::string(""), cmdline.m_out.str());
            CPPUNIT_ASSERT_EQUAL(std::string("[INFO] Configuration \"nosuchpeer@foobar\" does not exist.\n[ERROR] Cannot proceed with sync without a configuration."), cmdline.m_err.str());
        }

        {
            TestCmdline cmdline("@foobar", NULL);
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(false, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }

        // now set the value permanently
        {
            TestCmdline cmdline("--keyring", "--configure", "@default", NULL);
            cmdline.doit();
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }
        {
            TestCmdline cmdline("--keyring=KDE", "--configure", "@default", NULL);
            cmdline.doit();
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_STRING, keyring.getValue());
            CPPUNIT_ASSERT_EQUAL(std::string("KDE"), keyring.get());
        }

        // create by setting keyring in @default, then update;
        // @default not strictly needed
        rm_r(m_testDir);
        {
            TestCmdline cmdline("keyring=KDE", "--configure", "@default", NULL);
            cmdline.doit();
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_STRING, keyring.getValue());
        }
        {
            TestCmdline cmdline("keyring=yes", "--configure", "@default", NULL);
            cmdline.doit();
            boost::shared_ptr<SyncContext> context = cmdline.parse();
            CPPUNIT_ASSERT(context);
            InitStateTri keyring = context->getKeyring();
            CPPUNIT_ASSERT_EQUAL(true, keyring.wasSet());
            CPPUNIT_ASSERT_EQUAL(InitStateTri::VALUE_TRUE, keyring.getValue());
        }

        // allow sync operation although --keyring was set
        {
            TestCmdline cmdline("keyring=GNOME", "foobar@default", NULL);
            cmdline.doit(false);
            CPPUNIT_ASSERT_EQUAL(std::string(""), cmdline.m_out.str());
            CPPUNIT_ASSERT_EQUAL(std::string("[INFO] Configuration \"foobar@default\" does not exist.\n[ERROR] Cannot proceed with sync without a configuration."), cmdline.m_err.str());
        }

        // catch invalid "keyring" value
        {
            TestCmdline cmdline("--configure",
                                "username=foo",
                                "password=bar",
                                "syncURL=http://no.such.server",
                                "keyring=no-such-keyring",
                                "foobar@default", NULL);
            cmdline.doit(false);
            CPPUNIT_ASSERT_EQUAL(std::string(""), cmdline.m_out.str());
            CPPUNIT_ASSERT_EQUAL(std::string("[INFO] addressbook: looking for databases...\n"
                                             "[INFO] addressbook: okay\n"
                                             "[INFO] calendar: looking for databases...\n"
                                             "[INFO] calendar: okay\n"
                                             "[INFO] memo: looking for databases...\n"
                                             "[INFO] memo: okay\n"
                                             "[INFO] todo: looking for databases...\n"
                                             "[INFO] todo: okay\n"
                                             "[ERROR] Unsupported value for the \"keyring\" property, no such keyring found: no-such-keyring"),
                                 cmdline.m_err.str());
        }
    }

    void testWebDAV() {
#ifdef ENABLE_DAV
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        // configure Yahoo under a different name, with explicit template selection
        {
            TestCmdline cmdline("--configure",
                                "--template", "yahoo",
                                "target-config@my-yahoo",
                                NULL);
            cmdline.doit();
        }
        {
            TestCmdline cmdline("--print-config", "target-config@my-yahoo", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF(yahoo,
                                      removeComments(filterRandomUUID(filterConfig(cmdline.m_out.str()))));
        }

        // configure Google Calendar with template derived from config name
        {
            TestCmdline cmdline("--configure",
                                "target-config@google-calendar",
                                NULL);
            cmdline.doit();
        }
        {
            TestCmdline cmdline("--print-config", "target-config@google-calendar", NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF(googlecaldav,
                                      removeComments(filterRandomUUID(filterConfig(cmdline.m_out.str()))));
        }

        // test "template not found" error cases
        {
            TestCmdline cmdline("--configure",
                                "--template", "yahooxyz",
                                "target-config@my-yahoo-xyz",
                                NULL);
            CPPUNIT_ASSERT(cmdline.m_cmdline->parse());
            CPPUNIT_ASSERT(!cmdline.m_cmdline->run());
            static const char error[] = "[ERROR] No configuration template for 'yahooxyz' available.\n"
                "[INFO] \n"
                "[INFO] Available configuration templates (clients and servers):\n";
            std::string out = cmdline.m_out.str();
            std::string err = cmdline.m_err.str();
            std::string all = cmdline.m_all.str();
            CPPUNIT_ASSERT(boost::starts_with(err, error));
            CPPUNIT_ASSERT(boost::ends_with(err, "\n"));
            CPPUNIT_ASSERT(!boost::ends_with(err, "\n\n"));
            CPPUNIT_ASSERT_EQUAL(string(""), out);
            CPPUNIT_ASSERT_EQUAL(all, err);
        }
        {
            TestCmdline cmdline("--configure",
                                "target-config@foobar",
                                NULL);
            CPPUNIT_ASSERT(cmdline.m_cmdline->parse());
            CPPUNIT_ASSERT(!cmdline.m_cmdline->run());
            static const char error[] = "[ERROR] No configuration template for 'foobar' available.\n"
                "[INFO] Use '--template none' and/or specify relevant properties on the command line to create a configuration without a template. Need values for: syncURL\n"
                "[INFO] \n"
                "[INFO] Available configuration templates (clients and servers):\n";
            std::string out = cmdline.m_out.str();
            std::string err = cmdline.m_err.str();
            std::string all = cmdline.m_all.str();
            CPPUNIT_ASSERT(boost::starts_with(err, error));
            CPPUNIT_ASSERT(boost::ends_with(err, "\n"));
            CPPUNIT_ASSERT(!boost::ends_with(err, "\n\n"));
            CPPUNIT_ASSERT_EQUAL(string(""), out);
            CPPUNIT_ASSERT_EQUAL(err, all);
        }
#endif
    }

    void testConfigure() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        testSetupScheduleWorld();
        string expected = doConfigure(ScheduleWorldConfig(), "sources/addressbook/config.ini:");

        {
            // updating "type" for peer is mapped to updating "backend",
            // "databaseFormat", "syncFormat", "forceSyncFormat"
            TestCmdline cmdline("--configure",
                                "--source-property", "addressbook/type=file:text/vcard:3.0",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            boost::replace_first(expected,
                                 "backend = addressbook",
                                 "backend = file");
            boost::replace_first(expected,
                                 "# databaseFormat = ",
                                 "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected,
                                      filterConfig(printConfig("scheduleworld")));
            string shared = filterConfig(printConfig("@default"));
            CPPUNIT_ASSERT(shared.find("backend = file") != shared.npos);
            CPPUNIT_ASSERT(shared.find("databaseFormat = text/vcard") != shared.npos);
        }

        {
            // updating type for context must not affect peer
            TestCmdline cmdline("--configure",
                                "--source-property", "type=file:text/x-vcard:2.1",
                                "@default", "addressbook",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            boost::replace_first(expected,
                                 "databaseFormat = text/vcard",
                                 "databaseFormat = text/x-vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected,
                                      filterConfig(printConfig("scheduleworld")));
            string shared = filterConfig(printConfig("@default"));
            CPPUNIT_ASSERT(shared.find("backend = file") != shared.npos);
            CPPUNIT_ASSERT(shared.find("databaseFormat = text/x-vcard") != shared.npos);
        }

        string syncProperties("syncURL (no default, unshared, required)\n"
                              "\n"
                              "username (no default, unshared)\n"
                              "\n"
                              "password (no default, unshared)\n"
                              "\n"
                              "logdir (no default, shared)\n"
                              "\n"
                              "loglevel (0, unshared)\n"
                              "\n"
                              "notifyLevel (3, unshared)\n"
                              "\n"
                              "printChanges (TRUE, unshared)\n"
                              "\n"
                              "dumpData (TRUE, unshared)\n"
                              "\n"
                              "maxlogdirs (10, shared)\n"
                              "\n"
                              "autoSync (0, unshared)\n"
                              "\n"
                              "autoSyncInterval (30M, unshared)\n"
                              "\n"
                              "autoSyncDelay (5M, unshared)\n"
                              "\n"
                              "preventSlowSync (TRUE, unshared)\n"
                              "\n"
                              "useProxy (FALSE, unshared)\n"
                              "\n"
                              "proxyHost (no default, unshared)\n"
                              "\n"
                              "proxyUsername (no default, unshared)\n"
                              "\n"
                              "proxyPassword (no default, unshared)\n"
                              "\n"
                              "clientAuthType (md5, unshared)\n"
                              "\n"
                              "RetryDuration (5M, unshared)\n"
                              "\n"
                              "RetryInterval (2M, unshared)\n"
                              "\n"
                              "remoteIdentifier (no default, unshared)\n"
                              "\n"
                              "PeerIsClient (FALSE, unshared)\n"
                              "\n"
                              "SyncMLVersion (no default, unshared)\n"
                              "\n"
                              "PeerName (no default, unshared)\n"
                              "\n"
                              "deviceId (no default, shared)\n"
                              "\n"
                              "remoteDeviceId (no default, unshared)\n"
                              "\n"
                              "enableWBXML (TRUE, unshared)\n"
                              "\n"
                              "enableRefreshSync (FALSE, unshared)\n"
                              "\n"
                              "maxMsgSize (150000, unshared), maxObjSize (4000000, unshared)\n"
                              "\n"
                              "SSLServerCertificates (" SYNCEVOLUTION_SSL_SERVER_CERTIFICATES ", unshared)\n"
                              "\n"
                              "SSLVerifyServer (TRUE, unshared)\n"
                              "\n"
                              "SSLVerifyHost (TRUE, unshared)\n"
                              "\n"
                              "WebURL (no default, unshared)\n"
                              "\n"
                              "IconURI (no default, unshared)\n"
                              "\n"
                              "ConsumerReady (FALSE, unshared)\n"
                              "\n"
                              "peerType (no default, unshared)\n"
                              "\n"
                              "defaultPeer (no default, global)\n"
                              "\n"
                              "keyring (yes, global)\n");

        string sourceProperties("sync (disabled, unshared, required)\n"
                                "\n"
                                "uri (no default, unshared)\n"
                                "\n"
                                "backend (select backend, shared)\n"
                                "\n"
                                "syncFormat (no default, unshared)\n"
                                "\n"
                                "forceSyncFormat (FALSE, unshared)\n"
                                "\n"
                                "database = evolutionsource (no default, shared)\n"
                                "\n"
                                "databaseFormat (no default, shared)\n"
                                "\n"
                                "databaseUser = evolutionuser (no default, shared), databasePassword = evolutionpassword (no default, shared)\n");

        {
            TestCmdline cmdline("--sync-property", "?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF(syncProperties,
                                      filterIndented(cmdline.m_out.str()));
        }

        {
            TestCmdline cmdline("--source-property", "?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF(sourceProperties,
                                      filterIndented(cmdline.m_out.str()));
        }

        {
            TestCmdline cmdline("--source-property", "?",
                                "--sync-property", "?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF(sourceProperties + syncProperties,
                                      filterIndented(cmdline.m_out.str()));
        }

        {
            TestCmdline cmdline("--sync-property", "?",
                                "--source-property", "?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF(syncProperties + sourceProperties,
                                      filterIndented(cmdline.m_out.str()));
        }

        {
            TestCmdline cmdline("--source-property", "sync=?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("'--source-property sync=?'\n",
                                      filterIndented(cmdline.m_out.str()));
        }

        {
            TestCmdline cmdline("sync=?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("'sync=?'\n",
                                      filterIndented(cmdline.m_out.str()));
        }

        {
            TestCmdline cmdline("syncURL=?",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("'syncURL=?'\n",
                                      filterIndented(cmdline.m_out.str()));
        }
    }

    void testConfigureSources() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        // create from scratch with only addressbook configured
        {
            TestCmdline cmdline("--configure",
                                "--source-property", "database = file://tmp/test",
                                "--source-property", "type = file:text/x-vcard",
                                "@foobar",
                                "addressbook",
                                NULL);
            cmdline.doit();
        }
        string root = m_testDir;
        root += "/syncevolution/foobar";
        string res = scanFiles(root);
        removeRandomUUID(res);
        string expected =
            StringPrintf(".internal.ini:contextMinVersion = %d\n"
                         ".internal.ini:contextCurVersion = %d\n"
                         "config.ini:# logdir = \n"
                         "config.ini:# maxlogdirs = 10\n"
                         "config.ini:deviceId = fixed-devid\n"
                         "sources/addressbook/config.ini:backend = file\n"
                         "sources/addressbook/config.ini:database = file://tmp/test\n"
                         "sources/addressbook/config.ini:databaseFormat = text/x-vcard\n"
                         "sources/addressbook/config.ini:# databaseUser = \n"
                         "sources/addressbook/config.ini:# databasePassword = \n",
                         CONFIG_CONTEXT_MIN_VERSION,
                         CONFIG_CONTEXT_CUR_VERSION);
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);

        // add calendar
        {
            TestCmdline cmdline("--configure",
                                "--source-property", "database@foobar = file://tmp/test2",
                                "--source-property", "backend = calendar",
                                "@foobar",
                                "calendar",
                                NULL);
            cmdline.doit();
        }
        res = scanFiles(root);
        removeRandomUUID(res);
        expected +=
            "sources/calendar/config.ini:backend = calendar\n"
            "sources/calendar/config.ini:database = file://tmp/test2\n"
            "sources/calendar/config.ini:# databaseFormat = \n"
            "sources/calendar/config.ini:# databaseUser = \n"
            "sources/calendar/config.ini:# databasePassword = \n";
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);

        // add ScheduleWorld peer: must reuse existing backend settings
        {
            TestCmdline cmdline("--configure",
                                "scheduleworld@foobar",
                                NULL);
            cmdline.doit();
        }
        res = scanFiles(root);
        removeRandomUUID(res);
        expected = ScheduleWorldConfig();
        boost::replace_all(expected,
                           "addressbook/config.ini:backend = addressbook",
                           "addressbook/config.ini:backend = file");
        boost::replace_all(expected,
                           "addressbook/config.ini:# database = ",
                           "addressbook/config.ini:database = file://tmp/test");
        boost::replace_all(expected,
                           "addressbook/config.ini:# databaseFormat = ",
                           "addressbook/config.ini:databaseFormat = text/x-vcard");
        boost::replace_all(expected,
                           "calendar/config.ini:# database = ",
                           "calendar/config.ini:database = file://tmp/test2");
        sortConfig(expected);
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);

        // disable all sources except for addressbook
        {
            TestCmdline cmdline("--configure",
                                "--source-property", "addressbook/sync=two-way",
                                "--source-property", "sync=none",
                                "scheduleworld@foobar",
                                NULL);
            cmdline.doit();
        }
        res = scanFiles(root);
        removeRandomUUID(res);
        boost::replace_all(expected, "sync = two-way", "sync = disabled");
        boost::replace_first(expected, "sync = disabled", "sync = two-way");
        CPPUNIT_ASSERT_EQUAL_DIFF(expected, res);

        // override type in template while creating from scratch
        {
            TestCmdline cmdline("--configure",
                                "--template", "SyncEvolution",
                                "--source-property", "addressbook/type=file:text/vcard:3.0",
                                "--source-property", "calendar/type=file:text/calendar:2.0",
                                "syncevo@syncevo",
                                NULL);
            cmdline.doit();
        }
        string syncevoroot = m_testDir + "/syncevolution/syncevo";
        res = scanFiles(syncevoroot + "/sources/addressbook");
        CPPUNIT_ASSERT(res.find("backend = file\n") != res.npos);
        CPPUNIT_ASSERT(res.find("databaseFormat = text/vcard\n") != res.npos);
        res = scanFiles(syncevoroot + "/sources/calendar");
        CPPUNIT_ASSERT(res.find("backend = file\n") != res.npos);
        CPPUNIT_ASSERT(res.find("databaseFormat = text/calendar\n") != res.npos);
    }

    void testOldConfigure() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        string oldConfig = OldScheduleWorldConfig();
        InitList<string> props = InitList<string>("serverNonce") +
            "clientNonce" +
            "devInfoHash" +
            "HashCode" +
            "ConfigDate" +
            "deviceData" +
            "adminData" +
            "synthesisID" +
            "rootMinVersion" +
            "rootCurVersion" +
            "contextMinVersion" +
            "contextCurVersion" +
            "peerMinVersion" +
            "peerCurVersion" +
            "lastNonce" +
            "last";
        BOOST_FOREACH(string &prop, props) {
            boost::replace_all(oldConfig,
                               prop + " = ",
                               prop + " = internal value");
        }

        rm_r(m_testDir);
        createFiles(m_testDir + "/.sync4j/evolution/scheduleworld", oldConfig);

        // Cannot read/and write old format anymore.
        SyncContext::setStableRelease(false);
        expectMigration("scheduleworld");

        // Migrate explicitly.
        {
            TestCmdline cmdline("--migrate", "scheduleworld", NULL);
            cmdline.doit();
        }

        // now test with new format
        string expected = ScheduleWorldConfig();
        boost::replace_first(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
        boost::replace_first(expected, "# database = ", "database = xyz");
        boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
        boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
        // migrating "type" sets forceSyncFormat if not the default,
        // and databaseFormat (if format was part of type, as for addressbook)
        boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
        doConfigure(expected, "sources/addressbook/config.ini:");
    }

    string doConfigure(const string &SWConfig, const string &addressbookPrefix) {
        string expected;

        {
            TestCmdline cmdline("--configure",
                                "--source-property", "sync = disabled",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            expected = filterConfig(internalToIni(SWConfig));
            boost::replace_all(expected,
                               "sync = two-way",
                               "sync = disabled");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected,
                                      filterConfig(printConfig("scheduleworld")));
        }

        {
            TestCmdline cmdline("--configure",
                                "--source-property", "sync = one-way-from-server",
                                "scheduleworld",
                                "addressbook",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            expected = SWConfig;
            boost::replace_all(expected,
                               "sync = two-way",
                               "sync = disabled");
            boost::replace_first(expected,
                                 addressbookPrefix + "sync = disabled",
                                 addressbookPrefix + "sync = one-way-from-server");
            expected = filterConfig(internalToIni(expected));
            CPPUNIT_ASSERT_EQUAL_DIFF(expected,
                                      filterConfig(printConfig("scheduleworld")));
        }

        {
            TestCmdline cmdline("--configure",
                                "--sync", "two-way",
                                "-z", "database=source",
                                // note priority of suffix: most specific wins
                                "--sync-property", "maxlogdirs@scheduleworld@default=20",
                                "--sync-property", "maxlogdirs@default=10",
                                "--sync-property", "maxlogdirs=5",
                                "-y", "LOGDIR@default=logdir",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            boost::replace_all(expected,
                               "sync = one-way-from-server",
                               "sync = two-way");
            boost::replace_all(expected,
                               "sync = disabled",
                               "sync = two-way");
            boost::replace_all(expected,
                               "# database = ",
                               "database = source");
            boost::replace_all(expected,
                               "database = xyz",
                               "database = source");
            boost::replace_all(expected,
                               "# maxlogdirs = 10",
                               "maxlogdirs = 20");
            boost::replace_all(expected,
                               "# logdir = ",
                               "logdir = logdir");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected,
                                      filterConfig(printConfig("scheduleworld")));
        }

        return expected;
    }

    void testMigrate() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        string oldRoot = m_testDir + "/.sync4j/evolution/scheduleworld";
        string newRoot = m_testDir + "/syncevolution/default";

        string oldConfig = OldScheduleWorldConfig();

        {
            // migrate old config
            createFiles(oldRoot, oldConfig);
            string createdConfig = scanFiles(oldRoot);
            TestCmdline cmdline("--migrate",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());

            string migratedConfig = scanFiles(newRoot);
            string expected = ScheduleWorldConfig();
            sortConfig(expected);
            // migrating SyncEvolution < 1.2 configs sets
            // ConsumerReady, to keep config visible in the updated
            // sync-ui
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            // migrating "type" sets forceSyncFormat if different from the "false" default
            // and databaseFormat (if format was part of type, as for addressbook)
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            string renamedConfig = scanFiles(oldRoot + ".old");
            CPPUNIT_ASSERT_EQUAL_DIFF(createdConfig, renamedConfig);
        }

        {
            // rewrite existing config with obsolete properties
            // => these properties should get removed
            //
            // There is one limitation: shared nodes are not rewritten.
            // This is acceptable.
            createFiles(newRoot + "/peers/scheduleworld",
                        "config.ini:# obsolete comment\n"
                        "config.ini:obsoleteprop = foo\n",
                        true);
            string createdConfig = scanFiles(newRoot, "scheduleworld");

            TestCmdline cmdline("--migrate",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());

            string migratedConfig = scanFiles(newRoot, "scheduleworld");
            string expected = ScheduleWorldConfig();
            sortConfig(expected);
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            string renamedConfig = scanFiles(newRoot, "scheduleworld.old.1");
            boost::replace_first(createdConfig, "ConsumerReady = 1", "ConsumerReady = 0");
            boost::replace_all(createdConfig, "/scheduleworld/", "/scheduleworld.old.1/");
            CPPUNIT_ASSERT_EQUAL_DIFF(createdConfig, renamedConfig);
        }

        {
            // migrate old config with changes and .synthesis directory, a second time
            createFiles(oldRoot, oldConfig);
            createFiles(oldRoot,
                        ".synthesis/dummy-file.bfi:dummy = foobar\n"
                        "spds/sources/addressbook/changes/config.txt:foo = bar\n"
                        "spds/sources/addressbook/changes/config.txt:foo2 = bar2\n",
                        true);
            string createdConfig = scanFiles(oldRoot);
            rm_r(newRoot);
            TestCmdline cmdline("--migrate",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());

            string migratedConfig = scanFiles(newRoot);
            string expected = ScheduleWorldConfig();
            sortConfig(expected);
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            boost::replace_first(expected,
                                 "peers/scheduleworld/sources/addressbook/config.ini",
                                 "peers/scheduleworld/sources/addressbook/.other.ini:foo = bar\n"
                                 "peers/scheduleworld/sources/addressbook/.other.ini:foo2 = bar2\n"
                                 "peers/scheduleworld/sources/addressbook/config.ini");
            boost::replace_first(expected,
                                 "peers/scheduleworld/config.ini",
                                 "peers/scheduleworld/.synthesis/dummy-file.bfi:dummy = foobar\n"
                                 "peers/scheduleworld/config.ini");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            string renamedConfig = scanFiles(oldRoot + ".old.1");
            boost::replace_first(createdConfig, "ConsumerReady = 1", "ConsumerReady = 0");
            CPPUNIT_ASSERT_EQUAL_DIFF(createdConfig, renamedConfig);
        }

        {
            string otherRoot = m_testDir + "/syncevolution/other";
            rm_r(otherRoot);

            // migrate old config into non-default context
            createFiles(oldRoot, oldConfig);
            string createdConfig = scanFiles(oldRoot);
            {
                TestCmdline cmdline("--migrate",
                                    "scheduleworld@other",
                                    NULL);
                cmdline.doit();
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            }

            string migratedConfig = scanFiles(otherRoot);
            string expected = ScheduleWorldConfig();
            sortConfig(expected);
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            string renamedConfig = scanFiles(oldRoot + ".old");
            CPPUNIT_ASSERT_EQUAL_DIFF(createdConfig, renamedConfig);

            // migrate the migrated config again inside the "other" context,
            // with no "default" context which might interfere with the tests
            //
            // ConsumerReady was set as part of previous migration,
            // must be removed during migration to hide the migrated
            // config from average users.
            rm_r(newRoot);
            {
                TestCmdline cmdline("--migrate",
                                    "scheduleworld@other",
                                    NULL);
                cmdline.doit();
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            }
            migratedConfig = scanFiles(otherRoot, "scheduleworld");
            expected = ScheduleWorldConfig();
            sortConfig(expected);
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            renamedConfig = scanFiles(otherRoot, "scheduleworld.old.3");
            boost::replace_all(expected, "/scheduleworld/", "/scheduleworld.old.3/");
            boost::replace_all(expected, "ConsumerReady = 1", "ConsumerReady = 0");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, renamedConfig);

            // migrate once more, this time without the explicit context in
            // the config name => must not change the context, need second .old dir
            {
                TestCmdline cmdline("--migrate",
                                    "scheduleworld",
                                    NULL);
                cmdline.doit();
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            }
            migratedConfig = scanFiles(otherRoot, "scheduleworld");
            boost::replace_all(expected, "/scheduleworld.old.3/", "/scheduleworld/");
            boost::replace_all(expected, "ConsumerReady = 0", "ConsumerReady = 1");          
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            renamedConfig = scanFiles(otherRoot, "scheduleworld.old.4");
            boost::replace_all(expected, "/scheduleworld/", "/scheduleworld.old.4/");
            boost::replace_all(expected, "ConsumerReady = 1", "ConsumerReady = 0");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, renamedConfig);

            // remove ConsumerReady: must be remain unset when migrating
            // hidden SyncEvolution >= 1.2 configs
            {
                TestCmdline cmdline("--configure",
                                    "--sync-property", "ConsumerReady=0",
                                    "scheduleworld",
                                    NULL);
                cmdline.doit();
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            }

            // migrate once more => keep ConsumerReady unset
            {
                TestCmdline cmdline("--migrate",
                                    "scheduleworld",
                                    NULL);
                cmdline.doit();
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
                CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());
            }
            migratedConfig = scanFiles(otherRoot, "scheduleworld");
            boost::replace_all(expected, "/scheduleworld.old.4/", "/scheduleworld/");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            renamedConfig = scanFiles(otherRoot, "scheduleworld.old.5");
            boost::replace_all(expected, "/scheduleworld/", "/scheduleworld.old.5/");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, renamedConfig);
        }
    }

    void testMigrateContext()
    {
        // Migrate context containing a peer. Must also migrate peer.
        // Covers special case of inconsistent "type".

        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        string root = m_testDir + "/syncevolution/default";

        string oldConfig =
            "config.ini:logDir = none\n"
            "peers/scheduleworld/config.ini:syncURL = http://sync.scheduleworld.com/funambol/ds\n"
            "peers/scheduleworld/config.ini:# username = \n"
            "peers/scheduleworld/config.ini:# password = \n"

            "peers/scheduleworld/sources/addressbook/config.ini:sync = two-way\n"
            "peers/scheduleworld/sources/addressbook/config.ini:uri = card3\n"
            "peers/scheduleworld/sources/addressbook/config.ini:type = addressbook:text/vcard\n" // correct!
            "sources/addressbook/config.ini:type = calendar\n" // wrong!

            "peers/funambol/config.ini:syncURL = http://sync.funambol.com/funambol/ds\n"
            "peers/funambol/config.ini:# username = \n"
            "peers/funambol/config.ini:# password = \n"

            "peers/funambol/sources/calendar/config.ini:sync = refresh-from-server\n"
            "peers/funambol/sources/calendar/config.ini:uri = cal\n"
            "peers/funambol/sources/calendar/config.ini:type = calendar\n" // correct!
            "peers/funambol/sources/addressbook/config.ini:# sync = disabled\n"
            "peers/funambol/sources/addressbook/config.ini:type = file\n" // not used for context because source disabled
            "sources/calendar/config.ini:type = memos\n" // wrong!

            "peers/memotoo/config.ini:syncURL = http://sync.memotoo.com/memotoo/ds\n"
            "peers/memotoo/config.ini:# username = \n"
            "peers/memotoo/config.ini:# password = \n"

            "peers/memotoo/sources/memo/config.ini:sync = refresh-from-client\n"
            "peers/memotoo/sources/memo/config.ini:uri = cal\n"
            "peers/memotoo/sources/memo/config.ini:type = memo:text/plain\n" // correct!
            "sources/memo/config.ini:type = todo\n" // wrong!
            ;

        {
            createFiles(root, oldConfig);
            TestCmdline cmdline("--migrate",
                                "memo/backend=file", // override memo "backend" during migration
                                "@default",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());

            string migratedConfig = scanFiles(root);
            CPPUNIT_ASSERT(migratedConfig.find("peers/scheduleworld/") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("sources/addressbook/config.ini:backend = addressbook") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("sources/addressbook/config.ini:databaseFormat = text/vcard") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/scheduleworld/sources/addressbook/config.ini:syncFormat = text/vcard") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/scheduleworld/sources/addressbook/config.ini:sync = two-way") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/scheduleworld/sources/calendar/config.ini:# sync = disabled") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/scheduleworld/sources/memo/config.ini:# sync = disabled") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("sources/calendar/config.ini:backend = calendar") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("sources/calendar/config.ini:# databaseFormat = ") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/funambol/sources/calendar/config.ini:# syncFormat = ") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/funambol/sources/addressbook/config.ini:# sync = disabled") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/funambol/sources/calendar/config.ini:sync = refresh-from-server") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/funambol/sources/memo/config.ini:# sync = disabled") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("sources/memo/config.ini:backend = file") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("sources/memo/config.ini:databaseFormat = text/plain") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/memotoo/sources/memo/config.ini:syncFormat = text/plain") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/memotoo/sources/addressbook/config.ini:# sync = disabled") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/memotoo/sources/calendar/config.ini:# sync = disabled") != migratedConfig.npos);
            CPPUNIT_ASSERT(migratedConfig.find("peers/memotoo/sources/memo/config.ini:sync = refresh-from-client") != migratedConfig.npos);
        }
    }

    void testMigrateAutoSync() {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        string oldRoot = m_testDir + "/.sync4j/evolution/scheduleworld";
        string newRoot = m_testDir + "/syncevolution/default";

        string oldConfig = "spds/syncml/config.txt:autoSync = 1\n";
        oldConfig += OldScheduleWorldConfig();

        {
            // migrate old config
            createFiles(oldRoot, oldConfig);
            string createdConfig = scanFiles(oldRoot);
            TestCmdline cmdline("--migrate",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());

            string migratedConfig = scanFiles(newRoot);
            string expected = ScheduleWorldConfig();
            boost::replace_first(expected, "# autoSync = 0", "autoSync = 1");
            sortConfig(expected);
            // migrating SyncEvolution < 1.2 configs sets
            // ConsumerReady, to keep config visible in the updated
            // sync-ui
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            // migrating "type" sets forceSyncFormat if not already the default,
            // and databaseFormat (if format was part of type, as for addressbook)
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            string renamedConfig = scanFiles(oldRoot + ".old");
            // autoSync must have been unset
            boost::replace_first(createdConfig, ":autoSync = 1", ":autoSync = 0");
            CPPUNIT_ASSERT_EQUAL_DIFF(createdConfig, renamedConfig);
        }

        {
            // rewrite existing config with autoSync set
            string createdConfig = scanFiles(newRoot, "scheduleworld");

            TestCmdline cmdline("--migrate",
                                "scheduleworld",
                                NULL);
            cmdline.doit();
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
            CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_out.str());

            string migratedConfig = scanFiles(newRoot, "scheduleworld");
            string expected = ScheduleWorldConfig();
            boost::replace_first(expected, "# autoSync = 0", "autoSync = 1");
            sortConfig(expected);
            boost::replace_all(expected, "# ConsumerReady = 0", "ConsumerReady = 1");
            boost::replace_first(expected, "# database = ", "database = xyz");
            boost::replace_first(expected, "# databaseUser = ", "databaseUser = foo");
            boost::replace_first(expected, "# databasePassword = ", "databasePassword = bar");
            boost::replace_first(expected, "# databaseFormat = ", "databaseFormat = text/vcard");
            CPPUNIT_ASSERT_EQUAL_DIFF(expected, migratedConfig);
            string renamedConfig = scanFiles(newRoot, "scheduleworld.old.1");
            // autoSync must have been unset
            boost::replace_first(createdConfig, ":autoSync = 1", ":autoSync = 0");
            // the scheduleworld config was consumer ready, the migrated one isn't
            boost::replace_all(createdConfig, "ConsumerReady = 1", "ConsumerReady = 0");
            boost::replace_all(createdConfig, "/scheduleworld/", "/scheduleworld.old.1/");
            CPPUNIT_ASSERT_EQUAL_DIFF(createdConfig, renamedConfig);
        }
    }

    const string m_testDir;        

private:

    /**
     * vararg constructor with NULL termination,
     * out and error stream into stringstream members
     */
    class TestCmdline : private Logger {
        void init() {
            pushLogger(this);

            m_argv.reset(new const char *[m_argvstr.size() + 1]);
            m_argv[0] = "client-test";
            for (size_t index = 0;
                 index < m_argvstr.size();
                 ++index) {
                m_argv[index + 1] = m_argvstr[index].c_str();
            }

            m_cmdline.set(new KeyringSyncCmdline(m_argvstr.size() + 1, m_argv.get()), "cmdline");
        }

    public:
        TestCmdline(const char *arg, ...) {
            va_list argList;
            va_start (argList, arg);
            for (const char *curr = arg;
                 curr;
                 curr = va_arg(argList, const char *)) {
                m_argvstr.push_back(curr);
            }
            va_end(argList);
            init();
        }

        TestCmdline(const char * const argv[]) {
            for (int i = 0; argv[i]; i++) {
                m_argvstr.push_back(argv[i]);
            }
            init();
        }

        ~TestCmdline() {
            popLogger();
        }

        boost::shared_ptr<SyncContext> parse()
        {
            if (!m_cmdline->parse()) {
                return boost::shared_ptr<SyncContext>();
            }
            boost::shared_ptr<SyncContext> context(new SyncContext(m_cmdline->m_server));
            context->setConfigFilter(true, "", m_cmdline->m_props.createSyncFilter(m_cmdline->m_server));
            return context;
        }

        void doit(bool expectSuccess = true) {
            bool success = false;
            m_out.str("");
            m_err.str("");
            // emulates syncevolution.cpp exception handling
            try {
                success = m_cmdline->parse() &&
                    m_cmdline->run();
            } catch (const std::exception &ex) {
                m_err << "[ERROR] " << ex.what();
            } catch (...) {
                std::string explanation;
                Exception::handle(explanation);
                m_err << "[ERROR] " << explanation;
            }
            if (expectSuccess && m_err.str().size()) {
                m_out << endl << m_err.str();
            }
            CPPUNIT_ASSERT_MESSAGE(m_out.str(), success == expectSuccess);
        }

        /** verify that Cmdline::usage() produced a short usage info followed by a specific error message */
        void expectUsageError(const std::string &error)
        {
            // expect short usage info as normal output
            std::string out = m_out.str();
            std::string err = m_err.str();
            std::string all = m_all.str();
            CPPUNIT_ASSERT(boost::starts_with(out, "List and manipulate databases:\n"));
            CPPUNIT_ASSERT(out.find("\nOptions:\n") == std::string::npos);
            CPPUNIT_ASSERT(boost::ends_with(out,
                                            "Remove item(s):\n"
                                            "  syncevolution --delete-items [--] <config> <source> (<luid> ... | '*')\n\n"));
            // exact error message
            CPPUNIT_ASSERT_EQUAL(error, err);

            // also check order
            CPPUNIT_ASSERT_EQUAL_DIFF(out + err, all);
        }

        // separate streams for normal messages and error messages
        ostringstream m_out, m_err;
        // combined stream with all messages
        ostringstream m_all;

        cxxptr<Cmdline> m_cmdline;

    private:
        vector<string> m_argvstr;
        boost::scoped_array<const char *> m_argv;

        /** capture output produced while test ran */
        void messagev(const MessageOptions &options,
                      const char *format,
                      va_list args)
        {
            Level level = options.m_level;
            if (level <= INFO) {
                ostringstream &out = level != SHOW ? m_err : m_out;
                std::string str = StringPrintfV(format, args);
                if (level != SHOW) {
                    out << "[" << levelToStr(level) << "] ";
                    m_all << "[" << levelToStr(level) << "] ";
                }
                out << str;
                m_all << str;
                if (!boost::ends_with(str, "\n")) {
                    out << std::endl;
                    m_all << std::endl;
                }
            }
        }
    };

    string DefaultConfig() {
        string config = ScheduleWorldConfig();
        boost::replace_first(config,
                             "syncURL = http://sync.scheduleworld.com/funambol/ds",
                             "syncURL = http://yourserver:port");
        boost::replace_first(config, "http://www.scheduleworld.com", "http://www.syncevolution.org");
        boost::replace_all(config, "ScheduleWorld", "SyncEvolution");
        boost::replace_all(config, "scheduleworld", "syncevolution");
        boost::replace_first(config, "PeerName = SyncEvolution", "# PeerName = ");
        boost::replace_first(config, "# ConsumerReady = 0", "ConsumerReady = 1");
        boost::replace_first(config, "uri = card3", "uri = addressbook");
        boost::replace_first(config, "uri = cal2", "uri = calendar");
        boost::replace_first(config, "uri = task2", "uri = todo");
        boost::replace_first(config, "uri = note", "uri = memo");
        boost::replace_first(config, "syncFormat = text/vcard", "# syncFormat = ");
        return config;
    }

    string ScheduleWorldConfig(int contextMinVersion = CONFIG_CONTEXT_MIN_VERSION,
                               int contextCurVersion = CONFIG_CONTEXT_CUR_VERSION,
                               int peerMinVersion = CONFIG_PEER_MIN_VERSION,
                               int peerCurVersion = CONFIG_PEER_CUR_VERSION) {
        // properties sorted by the order in which they are defined
        // in the sync and sync source property registry
        string config =
            StringPrintf("peers/scheduleworld/.internal.ini:peerMinVersion = %d\n"
                         "peers/scheduleworld/.internal.ini:peerCurVersion = %d\n"
                         "peers/scheduleworld/.internal.ini:# HashCode = 0\n"
                         "peers/scheduleworld/.internal.ini:# ConfigDate = \n"
                         "peers/scheduleworld/.internal.ini:# lastNonce = \n"
                         "peers/scheduleworld/.internal.ini:# deviceData = \n"
                         "peers/scheduleworld/.internal.ini:# webDAVCredentialsOkay = 0\n"
                         "peers/scheduleworld/config.ini:syncURL = http://sync.scheduleworld.com/funambol/ds\n"
                         "peers/scheduleworld/config.ini:# username = \n"
                         "peers/scheduleworld/config.ini:# password = \n"
                         ".internal.ini:contextMinVersion = %d\n"
                         ".internal.ini:contextCurVersion = %d\n"
                         "config.ini:# logdir = \n"
                         "peers/scheduleworld/config.ini:# loglevel = 0\n"
                         "peers/scheduleworld/config.ini:# notifyLevel = 3\n"
                         "peers/scheduleworld/config.ini:# printChanges = 1\n"
                         "peers/scheduleworld/config.ini:# dumpData = 1\n"
                         "config.ini:# maxlogdirs = 10\n"
                         "peers/scheduleworld/config.ini:# autoSync = 0\n"
                         "peers/scheduleworld/config.ini:# autoSyncInterval = 30M\n"
                         "peers/scheduleworld/config.ini:# autoSyncDelay = 5M\n"
                         "peers/scheduleworld/config.ini:# preventSlowSync = 1\n"
                         "peers/scheduleworld/config.ini:# useProxy = 0\n"
                         "peers/scheduleworld/config.ini:# proxyHost = \n"
                         "peers/scheduleworld/config.ini:# proxyUsername = \n"
                         "peers/scheduleworld/config.ini:# proxyPassword = \n"
                         "peers/scheduleworld/config.ini:# clientAuthType = md5\n"
                         "peers/scheduleworld/config.ini:# RetryDuration = 5M\n"
                         "peers/scheduleworld/config.ini:# RetryInterval = 2M\n"
                         "peers/scheduleworld/config.ini:# remoteIdentifier = \n"
                         "peers/scheduleworld/config.ini:# PeerIsClient = 0\n"
                         "peers/scheduleworld/config.ini:# SyncMLVersion = \n"
                         "peers/scheduleworld/config.ini:PeerName = ScheduleWorld\n"
                         "config.ini:deviceId = fixed-devid\n" /* this is not the default! */
                         "peers/scheduleworld/config.ini:# remoteDeviceId = \n"
                         "peers/scheduleworld/config.ini:# enableWBXML = 1\n"
                         "peers/scheduleworld/config.ini:# enableRefreshSync = 0\n"
                         "peers/scheduleworld/config.ini:# maxMsgSize = 150000\n"
                         "peers/scheduleworld/config.ini:# maxObjSize = 4000000\n"
                         "peers/scheduleworld/config.ini:# SSLServerCertificates = \n"
                         "peers/scheduleworld/config.ini:# SSLVerifyServer = 1\n"
                         "peers/scheduleworld/config.ini:# SSLVerifyHost = 1\n"
                         "peers/scheduleworld/config.ini:WebURL = http://www.scheduleworld.com\n"
                         "peers/scheduleworld/config.ini:IconURI = image://themedimage/icons/services/scheduleworld\n"
                         "peers/scheduleworld/config.ini:# ConsumerReady = 0\n"
                         "peers/scheduleworld/config.ini:# peerType = \n"

                         "peers/scheduleworld/sources/addressbook/.internal.ini:# adminData = \n"
                         "peers/scheduleworld/sources/addressbook/.internal.ini:# synthesisID = 0\n"
                         "peers/scheduleworld/sources/addressbook/config.ini:sync = two-way\n"
                         "peers/scheduleworld/sources/addressbook/config.ini:uri = card3\n"
                         "sources/addressbook/config.ini:backend = addressbook\n"
                         "peers/scheduleworld/sources/addressbook/config.ini:syncFormat = text/vcard\n"
                         "peers/scheduleworld/sources/addressbook/config.ini:# forceSyncFormat = 0\n"
                         "sources/addressbook/config.ini:# database = \n"
                         "sources/addressbook/config.ini:# databaseFormat = \n"
                         "sources/addressbook/config.ini:# databaseUser = \n"
                         "sources/addressbook/config.ini:# databasePassword = \n"

                         "peers/scheduleworld/sources/calendar/.internal.ini:# adminData = \n"
                         "peers/scheduleworld/sources/calendar/.internal.ini:# synthesisID = 0\n"
                         "peers/scheduleworld/sources/calendar/config.ini:sync = two-way\n"
                         "peers/scheduleworld/sources/calendar/config.ini:uri = cal2\n"
                         "sources/calendar/config.ini:backend = calendar\n"
                         "peers/scheduleworld/sources/calendar/config.ini:# syncFormat = \n"
                         "peers/scheduleworld/sources/calendar/config.ini:# forceSyncFormat = 0\n"
                         "sources/calendar/config.ini:# database = \n"
                         "sources/calendar/config.ini:# databaseFormat = \n"
                         "sources/calendar/config.ini:# databaseUser = \n"
                         "sources/calendar/config.ini:# databasePassword = \n"

                         "peers/scheduleworld/sources/memo/.internal.ini:# adminData = \n"
                         "peers/scheduleworld/sources/memo/.internal.ini:# synthesisID = 0\n"
                         "peers/scheduleworld/sources/memo/config.ini:sync = two-way\n"
                         "peers/scheduleworld/sources/memo/config.ini:uri = note\n"
                         "sources/memo/config.ini:backend = memo\n"
                         "peers/scheduleworld/sources/memo/config.ini:# syncFormat = \n"
                         "peers/scheduleworld/sources/memo/config.ini:# forceSyncFormat = 0\n"
                         "sources/memo/config.ini:# database = \n"
                         "sources/memo/config.ini:# databaseFormat = \n"
                         "sources/memo/config.ini:# databaseUser = \n"
                         "sources/memo/config.ini:# databasePassword = \n"

                         "peers/scheduleworld/sources/todo/.internal.ini:# adminData = \n"
                         "peers/scheduleworld/sources/todo/.internal.ini:# synthesisID = 0\n"
                         "peers/scheduleworld/sources/todo/config.ini:sync = two-way\n"
                         "peers/scheduleworld/sources/todo/config.ini:uri = task2\n"
                         "sources/todo/config.ini:backend = todo\n"
                         "peers/scheduleworld/sources/todo/config.ini:# syncFormat = \n"
                         "peers/scheduleworld/sources/todo/config.ini:# forceSyncFormat = 0\n"
                         "sources/todo/config.ini:# database = \n"
                         "sources/todo/config.ini:# databaseFormat = \n"
                         "sources/todo/config.ini:# databaseUser = \n"
                         "sources/todo/config.ini:# databasePassword = ",
                         peerMinVersion, peerCurVersion,
                         contextMinVersion, contextCurVersion);
#ifdef ENABLE_LIBSOUP
        // path to SSL certificates has to be set only for libsoup
        boost::replace_first(config,
                             "SSLServerCertificates = ",
                             "SSLServerCertificates = /etc/ssl/certs/ca-certificates.crt:/etc/pki/tls/certs/ca-bundle.crt:/usr/share/ssl/certs/ca-bundle.crt");
#endif

#if 0
        // Currently we don't have an icon for ScheduleWorld. If we
        // had (MB #2062) one, then this code would ensure that the
        // reference config also has the right path for it.
        const char *templateDir = getenv("SYNCEVOLUTION_TEMPLATE_DIR");
        if (!templateDir) {
            templateDir = TEMPLATE_DIR;
        }


        if (isDir(string(templateDir) + "/ScheduleWorld")) {
            boost::replace_all(config,
                               "# IconURI = ",
                               string("IconURI = file://") + templateDir + "/ScheduleWorld/icon.png");
        }
#endif
        return config;
    }

    string OldScheduleWorldConfig() {
        // old style paths
        string oldConfig =
            "spds/syncml/config.txt:syncURL = http://sync.scheduleworld.com/funambol/ds\n"
            "spds/syncml/config.txt:# username = \n"
            "spds/syncml/config.txt:# password = \n"
            "spds/syncml/config.txt:# logdir = \n"
            "spds/syncml/config.txt:# loglevel = 0\n"
            "spds/syncml/config.txt:# notifyLevel = 3\n"
            "spds/syncml/config.txt:# printChanges = 1\n"
            "spds/syncml/config.txt:# dumpData = 1\n"
            "spds/syncml/config.txt:# maxlogdirs = 10\n"
            "spds/syncml/config.txt:# autoSync = 0\n"
            "spds/syncml/config.txt:# autoSyncInterval = 30M\n"
            "spds/syncml/config.txt:# autoSyncDelay = 5M\n"
            "spds/syncml/config.txt:# preventSlowSync = 1\n"
            "spds/syncml/config.txt:# useProxy = 0\n"
            "spds/syncml/config.txt:# proxyHost = \n"
            "spds/syncml/config.txt:# proxyUsername = \n"
            "spds/syncml/config.txt:# proxyPassword = \n"
            "spds/syncml/config.txt:# clientAuthType = md5\n"
            "spds/syncml/config.txt:# RetryDuration = 5M\n"
            "spds/syncml/config.txt:# RetryInterval = 2M\n"
            "spds/syncml/config.txt:# remoteIdentifier = \n"
            "spds/syncml/config.txt:# PeerIsClient = 0\n"
            "spds/syncml/config.txt:# SyncMLVersion = \n"
            "spds/syncml/config.txt:PeerName = ScheduleWorld\n"
            "spds/syncml/config.txt:deviceId = fixed-devid\n" /* this is not the default! */
            "spds/syncml/config.txt:# remoteDeviceId = \n"
            "spds/syncml/config.txt:# enableWBXML = 1\n"
            "spds/syncml/config.txt:# enableRefreshSync = 0\n"
            "spds/syncml/config.txt:# maxMsgSize = 150000\n"
            "spds/syncml/config.txt:# maxObjSize = 4000000\n"
#ifdef ENABLE_LIBSOUP
            // path to SSL certificates is only set for libsoup
            "spds/syncml/config.txt:# SSLServerCertificates = /etc/ssl/certs/ca-certificates.crt:/etc/pki/tls/certs/ca-bundle.crt:/usr/share/ssl/certs/ca-bundle.crt\n"

#else
            "spds/syncml/config.txt:# SSLServerCertificates = \n"
#endif
            "spds/syncml/config.txt:# SSLVerifyServer = 1\n"
            "spds/syncml/config.txt:# SSLVerifyHost = 1\n"
            "spds/syncml/config.txt:WebURL = http://www.scheduleworld.com\n"
            "spds/syncml/config.txt:IconURI = image://themedimage/icons/services/scheduleworld\n"
            "spds/syncml/config.txt:# ConsumerReady = 0\n"
            "spds/sources/addressbook/config.txt:sync = two-way\n"
            "spds/sources/addressbook/config.txt:type = addressbook:text/vcard\n"
            "spds/sources/addressbook/config.txt:evolutionsource = xyz\n"
            "spds/sources/addressbook/config.txt:uri = card3\n"
            "spds/sources/addressbook/config.txt:evolutionuser = foo\n"
            "spds/sources/addressbook/config.txt:evolutionpassword = bar\n"
            "spds/sources/calendar/config.txt:sync = two-way\n"
            "spds/sources/calendar/config.txt:type = calendar\n"
            "spds/sources/calendar/config.txt:# database = \n"
            "spds/sources/calendar/config.txt:uri = cal2\n"
            "spds/sources/calendar/config.txt:# evolutionuser = \n"
            "spds/sources/calendar/config.txt:# evolutionpassword = \n"
            "spds/sources/memo/config.txt:sync = two-way\n"
            "spds/sources/memo/config.txt:type = memo\n"
            "spds/sources/memo/config.txt:# database = \n"
            "spds/sources/memo/config.txt:uri = note\n"
            "spds/sources/memo/config.txt:# evolutionuser = \n"
            "spds/sources/memo/config.txt:# evolutionpassword = \n"
            "spds/sources/todo/config.txt:sync = two-way\n"
            "spds/sources/todo/config.txt:type = todo\n"
            "spds/sources/todo/config.txt:# database = \n"
            "spds/sources/todo/config.txt:uri = task2\n"
            "spds/sources/todo/config.txt:# evolutionuser = \n"
            "spds/sources/todo/config.txt:# evolutionpassword = \n";
        return oldConfig;
    }

    string FunambolConfig() {
        string config = ScheduleWorldConfig();
        boost::replace_all(config, "/scheduleworld/", "/funambol/");
        boost::replace_all(config, "PeerName = ScheduleWorld", "PeerName = Funambol");

        boost::replace_first(config,
                             "syncURL = http://sync.scheduleworld.com/funambol/ds",
                             "syncURL = http://my.funambol.com/sync");

        boost::replace_first(config,
                             "WebURL = http://www.scheduleworld.com",
                             "WebURL = http://my.funambol.com");

        boost::replace_first(config,
                             "IconURI = image://themedimage/icons/services/scheduleworld",
                             "IconURI = image://themedimage/icons/services/funambol");

        boost::replace_first(config,
                             "# ConsumerReady = 0",
                             "ConsumerReady = 1");

        boost::replace_first(config,
                             "# enableWBXML = 1",
                             "enableWBXML = 0");

        boost::replace_first(config,
                             "# enableRefreshSync = 0",
                             "enableRefreshSync = 1");

        boost::replace_first(config,
                             "# RetryInterval = 2M",
                             "RetryInterval = 0");

        boost::replace_first(config,
                             "addressbook/config.ini:uri = card3",
                             "addressbook/config.ini:uri = card");
        boost::replace_all(config,
                           "addressbook/config.ini:syncFormat = text/vcard",
                           "addressbook/config.ini:# syncFormat = ");

        boost::replace_first(config,
                             "calendar/config.ini:uri = cal2",
                             "calendar/config.ini:uri = event");
        boost::replace_all(config,
                           "calendar/config.ini:# syncFormat = ",
                           "calendar/config.ini:syncFormat = text/calendar");
        boost::replace_all(config,
                           "calendar/config.ini:# forceSyncFormat = 0",
                           "calendar/config.ini:forceSyncFormat = 1");

        boost::replace_first(config,
                             "todo/config.ini:uri = task2",
                             "todo/config.ini:uri = task");
        boost::replace_all(config,
                           "todo/config.ini:# syncFormat = ",
                           "todo/config.ini:syncFormat = text/calendar");
        boost::replace_all(config,
                           "todo/config.ini:# forceSyncFormat = 0",
                           "todo/config.ini:forceSyncFormat = 1");

        return config;
    }

    string SynthesisConfig() {
        string config = ScheduleWorldConfig();
        boost::replace_all(config, "/scheduleworld/", "/synthesis/");
        boost::replace_all(config, "PeerName = ScheduleWorld", "PeerName = Synthesis");

        boost::replace_first(config,
                             "syncURL = http://sync.scheduleworld.com/funambol/ds",
                             "syncURL = http://www.synthesis.ch/sync");

        boost::replace_first(config,
                             "WebURL = http://www.scheduleworld.com",
                             "WebURL = http://www.synthesis.ch");

        boost::replace_first(config,
                             "IconURI = image://themedimage/icons/services/scheduleworld",
                             "IconURI = image://themedimage/icons/services/synthesis");

        boost::replace_first(config,
                             "addressbook/config.ini:uri = card3",
                             "addressbook/config.ini:uri = contacts");
        boost::replace_all(config,
                           "addressbook/config.ini:syncFormat = text/vcard",
                           "addressbook/config.ini:# syncFormat = ");

        boost::replace_first(config,
                             "calendar/config.ini:uri = cal2",
                             "calendar/config.ini:uri = events");
        boost::replace_first(config,
                             "calendar/config.ini:sync = two-way",
                             "calendar/config.ini:sync = disabled");

        boost::replace_first(config,
                             "memo/config.ini:uri = note",
                             "memo/config.ini:uri = notes");

        boost::replace_first(config,
                             "todo/config.ini:uri = task2",
                             "todo/config.ini:uri = tasks");
        boost::replace_first(config,
                             "todo/config.ini:sync = two-way",
                             "todo/config.ini:sync = disabled");

        return config;
    }          

    /** create directory hierarchy, overwriting previous content */
    void createFiles(const string &root, const string &content, bool append = false) {
        if (!append) {
            rm_r(root);
        }

        size_t start = 0;
        ofstream out;
        string outname;

        out.exceptions(ios_base::badbit|ios_base::failbit);
        while (start < content.size()) {
            size_t delim = content.find(':', start);
            size_t end = content.find('\n', start);
            if (delim == content.npos ||
                end == content.npos) {
                // invalid content ?!
                break;
            }
            string newname = content.substr(start, delim - start);
            string line = content.substr(delim + 1, end - delim - 1);
            if (newname != outname) {
                if (out.is_open()) {
                    out.close();
                }
                string fullpath = root + "/" + newname;
                size_t fileoff = fullpath.rfind('/');
                mkdir_p(fullpath.substr(0, fileoff));
                out.open(fullpath.c_str(),
                         append ? (ios_base::out|ios_base::ate|ios_base::app) : (ios_base::out|ios_base::trunc));
                outname = newname;
            }
            out << line << endl;
            start = end + 1;
        }
    }

    /** turn directory hierarchy into string
     *
     * @param root       root path in file system
     * @param peer       if non-empty, then ignore all <root>/peers/<foo> directories
     *                   where <foo> != peer
     * @param onlyProps  ignore lines which are comments
     */
    string scanFiles(const string &root, const string &peer = "", bool onlyProps = true) {
        ostringstream out;

        scanFiles(root, "", peer, out, onlyProps);
        return out.str();
    }

    void scanFiles(const string &root, const string &dir, const string &peer, ostringstream &out, bool onlyProps) {
        string newroot = root;
        newroot += "/";
        newroot += dir;
        ReadDir readDir(newroot);
        sort(readDir.begin(), readDir.end());

        BOOST_FOREACH(const string &entry, readDir) {
            if (isDir(newroot + "/" + entry)) {
                if (boost::ends_with(newroot, "/peers") &&
                    !peer.empty() &&
                    entry != peer) {
                    // skip different peer directory
                    continue;
                } else {
                    scanFiles(root, dir + (dir.empty() ? "" : "/") + entry, peer, out, onlyProps);
                }
            } else {
                ifstream in;
                in.exceptions(ios_base::badbit /* failbit must not trigger exception because is set when reaching eof ?! */);
                in.open((newroot + "/" + entry).c_str());
                string line;
                while (!in.eof()) {
                    getline(in, line);
                    if ((line.size() || !in.eof()) && 
                        (!onlyProps ||
                         (boost::starts_with(line, "# ") ?
                          isPropAssignment(line.substr(2)) :
                          !line.empty()))) {
                        if (dir.size()) {
                            out << dir << "/";
                        }
                        out << entry << ":";
                        out << line << '\n';
                    }
                }
            }
        }
    }

    string printConfig(const string &server) {
        ScopedEnvChange templates("SYNCEVOLUTION_TEMPLATE_DIR", "templates");
        ScopedEnvChange xdg("XDG_CONFIG_HOME", m_testDir);
        ScopedEnvChange home("HOME", m_testDir);

        TestCmdline cmdline("--print-config", server.c_str(), NULL);
        cmdline.doit();
        CPPUNIT_ASSERT_EQUAL_DIFF("", cmdline.m_err.str());
        return cmdline.m_out.str();
    }
};

SYNCEVOLUTION_TEST_SUITE_REGISTRATION(CmdlineTest);

#endif // ENABLE_UNIT_TESTS

SE_END_CXX