File: rsnapshot-program.pl

package info (click to toggle)
rsnapshot 1.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,280 kB
  • sloc: perl: 4,329; sh: 3,225; makefile: 138
file content (7274 lines) | stat: -rwxr-xr-x 217,533 bytes parent folder | download
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
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
#!/usr/bin/perl -w

########################################################################
#                                                                      #
# rsnapshot                                                            #
# by Nathan Rosenquist                                                 #
# now maintained by David Keegel                                       #
#                                                                      #
# The official rsnapshot website is located at                         #
# http://www.rsnapshot.org/                                            #
#                                                                      #
# Copyright (C) 2003-2005 Nathan Rosenquist                            #
#                                                                      #
# Portions Copyright (C) 2002-2006 Mike Rubel, Carl Wilhelm Soderstrom,#
# Ted Zlatanov, Carl Boe, Shane Liebling, Bharat Mediratta,            #
# Peter Palfrader, Nicolas Kaiser, David Cantrell, Chris Petersen,     #
# Robert Jackson, Justin Grote, David Keegel, Alan Batie               #
#                                                                      #
# rsnapshot comes with ABSOLUTELY NO WARRANTY.  This is free software, #
# and you may copy, distribute and/or modify it under the terms of     #
# the GNU GPL (version 2 or at your option any later version).         #
# See the GNU General Public License (in file: COPYING) for details.   #
#                                                                      #
# Based on code originally by Mike Rubel                               #
# http://www.mikerubel.org/computers/rsync_snapshots/                  #
#                                                                      #
########################################################################

# $Id: rsnapshot-program.pl,v 1.398 2008/08/09 02:15:49 djk20 Exp $

# tabstops are set to 4 spaces
# in vi, do: set ts=4 sw=4

########################################
###         STANDARD MODULES         ###
########################################

require 5.004;
use strict;
use DirHandle;			# DirHandle()
use Cwd;				# cwd()
use Getopt::Std;		# getopts()
use File::Path;			# mkpath(), rmtree()
use File::stat;			# stat(), lstat()
use POSIX qw(locale_h);	# setlocale()
use Fcntl;				# sysopen()
use IO::File;			# recursive open in parse_config_file

########################################
###           CPAN MODULES           ###
########################################

# keep track of whether we have access to the Lchown module
my $have_lchown = 0;

# use_lchown() is called later, so we can log the results

########################################
###     DECLARE GLOBAL VARIABLES     ###
########################################

# turn off buffering
$| = 1;

# version of rsnapshot
my $VERSION = '1.3.1';

# command or interval to execute (first cmd line arg)
my $cmd;

# default configuration file
my $config_file;

# hash to hold variables from the configuration file
my %config_vars;

# array of hash_refs containing the destination backup point
# and either a source dir or a script to run
my @backup_points;

# array of backup points to rollback, in the event of failure
my @rollback_points;

# "intervals" are user defined time periods (e.g., hourly, daily)
# this array holds hash_refs containing the name of the interval,
# and the number of snapshots to keep of it
#
# NB, intervals and now called backup levels, and the config parameter
# is 'retain'

my @intervals;

# store interval data (mostly info about which one we're on, what was before, etc.)
# this is a convenient reference to some of the data from and metadata about @intervals
my $interval_data_ref;

# intervals can't have these values, because they're either taken by other commands
# or reserved for future use
my @reserved_words = qw(
	archive
	check-config-version
	configtest
	diff
	delete
	du
	get-latest-snapshot
	help
	history
	list
	print-config
	restore
	rollback
	sync
	upgrade-config-file
	version
	version-only
);

# global flags that change the outcome of the program,
# and are configurable by both cmd line and config flags
#
my $test			= 0; # turn verbose on, but don't execute
                                     # any filesystem commands
my $do_configtest		= 0; # parse config file and exit
my $one_fs			= 0; # one file system (don't cross
                                     # partitions within a backup point)
my $link_dest			= 0; # use the --link-dest option to rsync
my $stop_on_stale_lockfile	= 0; # stop if there is a stale lockfile

# how much noise should we make? the default is 2
#
# please note that direct rsync output does not get written to the log file, only to STDOUT
# this is because we're not intercepting STDOUT while rsync runs
#
#	0	Absolutely quiet (reserved, but not implemented)
#	1	Don't display warnings about FIFOs and special files
#	2	Default (errors only)
#	3	Verbose (show shell commands and equivalents)
#	4	Extra verbose messages (individual actions inside some subroutines, output from rsync)
#	5	Debug
#
# define verbose and loglevel
my $verbose		= undef;
my $loglevel	= undef;

# set defaults for verbose and loglevel
my $default_verbose		= 2;
my $default_loglevel	= 3;

# assume the config file is valid until we find an error
my $config_perfect = 1;

# exit code for rsnapshot
my $exit_code = 0;

# global defaults for external programs
my $default_rsync_short_args	= '-a';
my $default_rsync_long_args		= '--delete --numeric-ids --relative --delete-excluded';
my $default_ssh_args			= undef;
my $default_du_args				= '-csh';

# set default for use_lazy_deletes
my $use_lazy_deletes = 0;	# do not delete the oldest archive until after backup

# set default for number of tries
my $rsync_numtries = 1; # by default, try once

# exactly how the program was called, with all arguments
# this is set before getopts() modifies @ARGV
my $run_string = "$0 " . join(' ', @ARGV);

# if we have any errors, we print the run string once, at the top of the list
my $have_printed_run_string = 0;
	
# pre-buffer the include/exclude parameter flags
# local to parse_config_file and validate_config_file
my $rsync_include_args		= undef;
my $rsync_include_file_args	= undef;

########################################
###         SIGNAL HANDLERS          ###
########################################

# shut down gracefully if necessary
$SIG{'HUP'}		= 'IGNORE';
$SIG{'INT'}		= sub { bail('rsnapshot was sent INT signal... cleaning up');  };
$SIG{'QUIT'}	= sub { bail('rsnapshot was sent QUIT signal... cleaning up'); };
$SIG{'ABRT'}	= sub { bail('rsnapshot was sent ABRT signal... cleaning up'); };
$SIG{'TERM'}	= sub { bail('rsnapshot was sent TERM signal... cleaning up'); };

########################################
###      CORE PROGRAM STRUCTURE      ###
########################################

# what follows is a linear sequence of events.
# all of these subroutines will either succeed or terminate the program safely.

# figure out the path to the default config file (with autoconf we have to check)
# this sets $config_file to the full config file path
find_config_file();

# parse command line options
# (this can override $config_file, if the -c flag is used on the command line)
parse_cmd_line_opts();

# if we need to run a command that doesn't require fully parsing the config file, do it now (and exit)
if (!defined($cmd) or ((! $cmd) && ('0' ne $cmd))) {
	show_usage();
} elsif ($cmd eq 'help') {
	show_help();
} elsif ($cmd eq 'version') {
	show_version();
} elsif ($cmd eq 'version-only') {
	show_version_only();
} elsif ($cmd eq 'check-config-version') {
	check_config_version();
} elsif ($cmd eq 'upgrade-config-file') {
	upgrade_config_file();
}

# if we're just doing a configtest, set that flag
if ($cmd eq 'configtest') {
	$do_configtest = 1;
}

# parse config file (if it exists)
if (defined($config_file) && (-f "$config_file") && (-r "$config_file")) {
	# if there is a problem, this subroutine will exit the program and notify the user of the error
	parse_config_file();
	validate_config_file();
	
# no config file found
} else {
	# warn user and exit the program
	exit_no_config_file();
}

# attempt to load the Lchown module: http://search.cpan.org/dist/Lchown/
use_lchown();

# if we're just doing a configtest, exit here with the results
if (1 == $do_configtest) {
	exit_configtest();
}

# if we're just using "du" or "rsnapshot-diff" to check the disk space, do it now (and exit)
# these commands are down here because they needs to know the contents of the config file
if ($cmd eq 'du') {
	show_disk_usage();
} elsif ($cmd eq 'diff') {
	show_rsnapshot_diff();
} elsif ($cmd eq 'get-latest-snapshot') {
	show_latest_snapshot();
}

#
# IF WE GOT THIS FAR, PREPARE TO RUN A BACKUP
#

# log the beginning of this run
log_startup();

# this is reported to fix some semi-obscure problems with rmtree()
set_posix_locale();

# if we're using a lockfile, try to add it
# (the program will bail if one exists and it's not stale)
add_lockfile();

# create snapshot_root if it doesn't exist (and no_create_root != 1)
create_snapshot_root();

# now chdir to the snapshot_root.
# note that this is needed because in the rare case that you do this ...
# sudo -u peon rsnapshot ... and are in a directory that 'peon' can't
# read, then some versions of GNU rm will later fail, as they try to
# lstat the cwd.  It's safe to chdir because all directories etc that
# we ever mention are absolute.
chdir($config_vars{'snapshot_root'});

# actually run the backup job
# $cmd should store the name of the interval we'll run against
handle_interval( $cmd );

# if we have a lockfile, remove it
remove_lockfile();

# if we got this far, the program is done running
# write to the log and syslog with the status of the outcome
#
exit_with_status();

########################################
###           SUBROUTINES            ###
########################################

# concise usage information
# runs when rsnapshot is called with no arguments
# exits with an error condition
sub show_usage {
	print<<HERE;
rsnapshot $VERSION
Usage: rsnapshot [-vtxqVD] [-c cfgfile] [command] [args]
Type \"rsnapshot help\" or \"man rsnapshot\" for more information.
HERE
	
	exit(1);
}

# extended usage information
# runs when rsnapshot is called with "help" as an argument
# exits 0
sub show_help {
	print<<HERE;
rsnapshot $VERSION
Usage: rsnapshot [-vtxqVD] [-c cfgfile] [command] [args]
Type "man rsnapshot" for more information.

rsnapshot is a filesystem snapshot utility. It can take incremental
snapshots of local and remote filesystems for any number of machines.

rsnapshot comes with ABSOLUTELY NO WARRANTY.  This is free software,
and you are welcome to redistribute it under certain conditions.
See the GNU General Public License for details.

Options:
    -v verbose       - Show equivalent shell commands being executed.
    -t test          - Show verbose output, but don't touch anything.
                       This will be similar, but not always exactly the same
                       as the real output from a live run.
    -c [file]        - Specify alternate config file (-c /path/to/file)
    -q quiet         - Suppress non-fatal warnings.
    -V extra verbose - The same as -v, but with more detail.
    -D debug         - A firehose of diagnostic information.
    -x one_fs        - Don't cross filesystems (same as -x option to rsync).

Commands:
    [backuplevel]    - A backup level as defined in rsnapshot.conf.
    configtest       - Syntax check the config file.
    sync [dest]      - Sync files, without rotating. "sync_first" must be
                       enabled for this to work. If a full backup point
                       destination is given as an optional argument, only
                       those files will be synced.
    diff             - Front-end interface to the rsnapshot-diff program.
                       Accepts two optional arguments which can be either
                       filesystem paths or backup directories within the
                       snapshot_root (e.g., /etc/ daily.0/etc/). The default
                       is to compare the two most recent snapshots.
    du               - Show disk usage in the snapshot_root.
                       Accepts an optional destination path for comparison
                       across snapshots (e.g., localhost/home/user/foo).
    version          - Show the version number for rsnapshot.
    help             - Show this help message.
HERE
	
	exit(0);
}

# prints out the name and version
# exits 0
sub show_version {
	print "rsnapshot $VERSION\n";
	exit(0);
}

# prints only the version number
# this is "undocumented", just for use with some of the makefile targets
# exits 0
sub show_version_only {
	print "$VERSION\n";
	exit(0);
}

# For Getopt::Std
sub VERSION_MESSAGE {
	show_version;
}

# For Getopt::Std
sub HELP_MESSAGE {
	show_help;
}

# accepts no arguments
# sets the $config_file global variable
#
# this program works both "as-is" in the source tree, and when it has been parsed by autoconf for installation
# the variables with "@" symbols on both sides get replaced during ./configure
# this subroutine returns the correct path to the default config file
#
sub find_config_file {
	# autoconf variables (may have too many slashes)
	my $autoconf_sysconfdir	= '@sysconfdir@';
	my $autoconf_prefix		= '@prefix@';
	my $default_config_file	= '/etc/rsnapshot.conf';
	
	# consolidate multiple slashes
	$autoconf_sysconfdir	=~ s/\/+/\//g;
	$autoconf_prefix		=~ s/\/+/\//g;
	
	# remove trailing slashes
	$autoconf_sysconfdir	=~ s/\/$//g;
	$autoconf_prefix		=~ s/\/$//g;
	
	# if --sysconfdir was not set explicitly during ./configure, but we did use autoconf
	if ($autoconf_sysconfdir eq '${prefix}/etc') {
		$default_config_file = "$autoconf_prefix/etc/rsnapshot.conf";
		
	# if --sysconfdir was set explicitly at ./configure, overriding the --prefix setting
	} elsif ($autoconf_sysconfdir ne ('@' . 'sysconfdir' . '@')) {
		$default_config_file = "$autoconf_sysconfdir/rsnapshot.conf";
	}
	
	# set global variable
	$config_file = $default_config_file;
}

# accepts no args
# returns no args
# sets some global flag variables
# exits the program with an error if we were passed invalid options
sub parse_cmd_line_opts {
	my %opts;
	my $result;
	
	# get command line options
	$result = getopts('vtxqVDc:', \%opts);
	
	#
	# validate command line args
	#
	
	# make sure config file is a file
	if (defined($opts{'c'})) {
		if ( ! -r "$opts{'c'}" ) {
			print STDERR "File not found: $opts{'c'}\n";
			$result = undef;
		}
	}
	
	# die if we don't understand all the flags
	if (!defined($result) or (1 != $result)) {
		# At this point, getopts() or our @ARGV check will have printed out "Unknown option: -X"
		print STDERR "Type \"rsnapshot help\" or \"man rsnapshot\" for more information.\n";
		exit(1);
	}
	
	#
	# with that out of the way, we can go about the business of setting global variables
	#
	
	# set command
	$cmd = $ARGV[0];
	
	# check for extra bogus arguments that getopts() didn't catch
	if (defined($cmd) && ('du' ne $cmd) && ('diff' ne $cmd) && ('sync' ne $cmd)) {
		if (scalar(@ARGV) > 1) {
			for (my $i=1; $i<scalar(@ARGV); $i++) {
				print STDERR "Unknown option: $ARGV[$i]\n";
				print STDERR "Please make sure all switches come before commands\n";
				print STDERR "(e.g., 'rsnapshot -v hourly', not 'rsnapshot hourly -v')\n";
				exit(1);
			}
			
			$result = undef;
		}
	}
	
	# alternate config file?
	if (defined($opts{'c'})) {
		$config_file = $opts{'c'};
	}
	
	# test? (just show what WOULD be done)
	if (defined($opts{'t'})) {
		$test = 1;
		$verbose = 3;
	}
	
	# quiet?
	if (defined($opts{'q'}))	{ $verbose = 1; }
	
	# verbose (or extra verbose)?
	if (defined($opts{'v'}))	{ $verbose = 3; }
	if (defined($opts{'V'}))	{ $verbose = 4; }
	
	# debug
	if (defined($opts{'D'}))	{ $verbose = 5; }
	
	# one file system? (don't span partitions with rsync)
	if (defined($opts{'x'}))	{ $one_fs = 1; }
}

# accepts an optional argument - no arg means to parse the default file,
#   if an arg is present parse that file instead
# returns no value
# this subroutine parses the config file (rsnapshot.conf)
#
sub parse_config_file {
	# count the lines in the config file, so the user can pinpoint errors more precisely
	my $file_line_num = 0;
	my @configs = ();
	
	# open the config file
	my $config_file = shift() || $config_file;
	my $CONFIG;
	if($config_file =~ /^`(.*)`$/) {
	    open($CONFIG, "$1|") ||
	        bail("Couldn't execute \"$config_file\" to get config information\nAre you sure you have permission?");
	} else {
	    $CONFIG = IO::File->new($config_file)
		or bail("Could not open config file \"$config_file\"\nAre you sure you have permission?");
        }
	
	# read it line by line
	@configs = <$CONFIG>;
	while (my $line = $configs[$file_line_num]) {
		chomp($line);
		
		# count line numbers
		$file_line_num++;
		
		# assume the line is formatted incorrectly
		my $line_syntax_ok = 0;
		
		# ignore comments
		if (is_comment($line)) { next; }
		
		# ignore blank lines
		if (is_blank($line)) { next; }

		# if the next line begins with space or tab it belongs to this line
		while (defined ($configs[$file_line_num]) && $configs[$file_line_num] =~ /^(\t|\s)/) {
			(my $newline = $configs[$file_line_num]) =~ s/^\s+|\s+$//g;
			$line = $line . "\t" . $newline;
			$file_line_num++;
		}
		
		# parse line
		my ($var, $value, $value2, $value3) = split(/\t+/, $line, 4);
		
		# warn about entries we don't understand, and immediately prevent the
		# program from running or parsing anything else
		if (!defined($var)) {
			config_err($file_line_num, "$line - could not find a first word on this line");
			next;
		}
		if (!defined($value) && $var eq $line) {
			# No tabs found in $line.
			if ($line =~ /\s/) {
				# User put spaces in config line instead of tabs.
				config_err($file_line_num, "$line - missing tabs to separate words - change spaces to tabs.");
				next;
			} else {
				# User put only one word
				config_err($file_line_num, "$line - could not find second word on this line");
				next;
			}
		}
		foreach (grep {
		    defined($_) && index($_, ' ') == 0
		} ($value, $value2, $value3)) {
		    print_warn("$line - extra space found between tab and $_");
		}
		
		# INCLUDEs
		if($var eq 'include_conf') {
			$value =~ /^`(.*)`$/;
			if(
			    (defined($value) && -f $value && -r $value) ||
			    (defined($1) && -x $1)
			) {
				$line_syntax_ok = 1;
				parse_config_file($value);
			} else {
				config_err($file_line_num, "$line - can't find or read file '$value'");
				next;
			}
		}

		# CONFIG_VERSION
		if ($var eq 'config_version') {
			if (defined($value)) {
				# right now 1.2 is the only possible value
				if ('1.2' eq $value) {
					$config_vars{'config_version'} = $value;
					$line_syntax_ok = 1;
					next;
				} else {
					config_err($file_line_num, "$line - config_version not recognized!");
					next;
				}
			} else {
				config_err($file_line_num, "$line - config_version not defined!");
				next;
			}
		}
		
		# SNAPSHOT_ROOT
		if ($var eq 'snapshot_root') {
			# make sure this is a full path
			if (0 == is_valid_local_abs_path($value)) {
				if (is_ssh_path($value) || is_anon_rsync_path($value) || is_cwrsync_path($value)) {
					config_err($file_line_num, "$line - snapshot_root must be a local path - you cannot have a remote snapshot_root");
				} else {
					config_err($file_line_num, "$line - snapshot_root must be a full path");
				}
				next;
			# if the snapshot root already exists:
			} elsif ( -e "$value" ) {
				# if path exists already, make sure it's a directory
				if ((-e "$value") && (! -d "$value")) {
					config_err($file_line_num, "$line - snapshot_root must be a directory");
					next;
				}
				# make sure it's readable
				if ( ! -r "$value" ) {
					config_err($file_line_num, "$line - snapshot_root exists but is not readable");
					next;
				}
				# make sure it's writable
				if ( ! -w "$value" ) {
					config_err($file_line_num, "$line - snapshot_root exists but is not writable");
					next;
				}
			}
			
			# remove the trailing slash(es) if present
			$value = remove_trailing_slash($value);
			
			$config_vars{'snapshot_root'} = $value;
			$line_syntax_ok = 1;
			next;
		}
		
		# SYNC_FIRST
		# if this is enabled, rsnapshot syncs data to a staging directory with the "rsnapshot sync" command,
		# and all "interval" runs will simply rotate files. this changes the behaviour of the lowest interval.
		# when a sync occurs, no directories are rotated. the sync directory is kind of like a staging area for data transfers.
		# the files in the sync directory will be hard linked with the others in the other snapshot directories.
		# the sync directory lives at: /<snapshot_root>/.sync/
		#
		if ($var eq 'sync_first') {
			if (defined($value)) {
				if ('1' eq $value) {
					$config_vars{'sync_first'} = 1;
					$line_syntax_ok = 1;
					next;
				} elsif ('0' eq $value) {
					$config_vars{'sync_first'} = 0;
					$line_syntax_ok = 1;
					next;
				} else {
					config_err($file_line_num, "$line - sync_first must be set to either 1 or 0");
					next;
				}
			}
		}
		
		# NO_CREATE_ROOT
		if ($var eq 'no_create_root') {
			if (defined($value)) {
				if ('1' eq $value) {
					$config_vars{'no_create_root'} = 1;
					$line_syntax_ok = 1;
					next;
				} elsif ('0' eq $value) {
					$config_vars{'no_create_root'} = 0;
					$line_syntax_ok = 1;
					next;
				} else {
					config_err($file_line_num, "$line - no_create_root must be set to either 1 or 0");
					next;
				}
			}
		}
		
		# CHECK FOR RSYNC (required)
		if ($var eq 'cmd_rsync') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_rsync'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR SSH (optional)
		if ($var eq 'cmd_ssh') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_ssh'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR GNU cp (optional)
		if ($var eq 'cmd_cp') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_cp'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR rm (optional)
		if ($var eq 'cmd_rm') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_rm'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR LOGGER (syslog program) (optional)
		if ($var eq 'cmd_logger') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_logger'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR du (optional)
		if ($var eq 'cmd_du') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_du'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR lvcreate (optional)
		if ($var eq 'linux_lvm_cmd_lvcreate') {
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'linux_lvm_cmd_lvcreate'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		# CHECK FOR lvremove (optional)
		if ($var eq 'linux_lvm_cmd_lvremove') {
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'linux_lvm_cmd_lvremove'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		# CHECK FOR mount (optional)
		if ($var eq 'linux_lvm_cmd_mount') {
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'linux_lvm_cmd_mount'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		# CHECK FOR umount (optional)
		if ($var eq 'linux_lvm_cmd_umount') {
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'linux_lvm_cmd_umount'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# CHECK FOR cmd_preexec (optional)
		if ($var eq 'cmd_preexec') {
			my $script;			# script file (no args)
			
			# make sure script exists and is executable
			if ( ! is_valid_script($value, \$script) ) {
				config_err($file_line_num, "$line - \"$script\" is not executable or can't be found.".($script !~ m{^/} ? " Please use an absolute path.":""));
				next;
			}
			
			$config_vars{$var} = $value;
			
			$line_syntax_ok = 1;
			next;
		}
		
		# CHECK FOR cmd_postexec (optional)
		if ($var eq 'cmd_postexec') {
			my $script;			# script file (no args)
			
			# make sure script exists and is executable
			if ( ! is_valid_script($value, \$script) ) {
				config_err($file_line_num, "$line - \"$script\" is not executable or can't be found.".($script !~ m{^/} ? " Please use an absolute path.":""));
				next;
			}
			
			$config_vars{$var} = $value;
			
			$line_syntax_ok = 1;
			next;
		}
		
		# CHECK FOR rsnapshot-diff (optional)
		if ($var eq 'cmd_rsnapshot_diff') {
                        $value =~ s/\s+$//;
			if ((-f "$value") && (-x "$value") && (1 == is_real_local_abs_path($value))) {
				$config_vars{'cmd_rsnapshot_diff'} = $value;
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - $value is not executable");
				next;
			}
		}
		
		# INTERVALS
		# 'retain' is the new name for this parameter, although for
		# Laziness reasons (plus the fact that I'm making this change
		# at 10 minutes to midnight and so am wary of making changes
		# throughout the code and getting it wrong) the code will
		# still call it 'interval'.  Documentation and messages should
		# refer to 'retain'.  The old 'interval' will be kept as an
		# alias.
		if ($var eq 'interval' || $var eq 'retain') {
			my $retain = $var;	# either 'interval' or 'retain'
			# check if interval is blank
			if (!defined($value)) { config_err($file_line_num, "$line - $retain can not be blank"); }
			
			foreach my $word (@reserved_words) {
				if ($value eq $word) {
					config_err($file_line_num,
						"$line - \"$value\" is not a valid interval name, reserved word conflict");
					next;
				}
			}
			
			# make sure interval is alpha-numeric
			if ($value !~ m/^[\w\d]+$/) {
				config_err($file_line_num,
					"$line - \"$value\" is not a valid $retain name, must be alphanumeric characters only");
				next;
			}
			
			# check if number is blank
			if (!defined($value2)) {
				config_err($file_line_num, "$line - \"$value\" number can not be blank");
				next;
			}
			
			# check if number is valid
			if ($value2 !~ m/^\d+$/) {
				config_err($file_line_num, "$line - \"$value2\" is not a legal value for a retention count");
				next;
			# ok, it's a number. is it positive?
			} else {
				# make sure number is positive
				if ($value2 <= 0) {
					config_err($file_line_num, "$line - \"$value\" must be at least 1 or higher");
					next;
				}
			}
			
			my %hash;
			$hash{'interval'}	= $value;
			$hash{'number'}		= $value2;
			push(@intervals, \%hash);
			$line_syntax_ok = 1;
			next;
		}
		
		# BACKUP POINTS
		if ($var eq 'backup') {
			my $src			= $value;	# source directory
			my $dest		= $value2;	# dest directory
			my $opt_str		= $value3;	# option string from this backup point
			my $opts_ref	= undef;	# array_ref to hold parsed opts
			
			if ( !defined($config_vars{'snapshot_root'}) ) {
				config_err($file_line_num, "$line - snapshot_root needs to be defined before backup points");
				next;
			}
			
			if (!defined($src))	{
				config_err($file_line_num, "$line - no source path specified for backup point");
				next;
			}
			
			if (!defined($dest))	{
				config_err($file_line_num, "$line - no destination path specified for backup point");
				next;
			}
			
			# make sure we have a local path for the destination
			# (we do NOT want an absolute path)
			if ( is_valid_local_abs_path($dest) ) {
				config_err($file_line_num, "$line - Backup destination $dest must be a local, relative path");
				next;
			}
			
			# make sure we aren't traversing directories
			if ( is_directory_traversal($src) ) {
				config_err($file_line_num, "$line - Directory traversal attempted in $src");
				next;
			}
			if ( is_directory_traversal($dest) ) {
				config_err($file_line_num, "$line - Directory traversal attempted in $dest");
				next;
			}
			
			# validate source path
			#
			# local absolute?
			if ( is_real_local_abs_path($src) ) {
				$line_syntax_ok = 1;
				
			# syntactically valid remote ssh?
			} elsif ( is_ssh_path($src) ) {
				# if it's an absolute ssh path, make sure we have ssh
				if (!defined($config_vars{'cmd_ssh'})) {
					config_err($file_line_num, "$line - Cannot handle $src, cmd_ssh not defined in $config_file");
					next;
				}
				$line_syntax_ok = 1;
				
			# if it's anonymous rsync, we're ok
			} elsif ( is_anon_rsync_path($src) ) {
				$line_syntax_ok = 1;
				
			# check for cwrsync
			} elsif ( is_cwrsync_path($src) ) {
				$line_syntax_ok = 1;
				
			# check for lvm
			} elsif ( is_linux_lvm_path($src) ) {
				# if it's an lvm path, make sure we have lvm commands and arguments
				if (!defined($config_vars{'linux_lvm_cmd_lvcreate'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_cmd_lvcreate not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_cmd_lvremove'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_cmd_lvremove not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_cmd_mount'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_cmd_mount not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_cmd_umount'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_cmd_umount not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_snapshotsize'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_snapshotsize not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_snapshotname'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_snapshotname not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_vgpath'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_vgpath not defined in $config_file");
					next;
				}
				if (!defined($config_vars{'linux_lvm_mountpath'})) {
					config_err($file_line_num, "$line - Cannot handle $src, linux_lvm_mountpath not defined in $config_file");
					next;
				}
				$line_syntax_ok = 1;

			# fear the unknown
			} else {
				config_err($file_line_num, "$line - Source directory \"$src\" doesn't exist");
				next;
			}
			
			# validate destination path
			#
			if ( is_valid_local_abs_path($dest) ) {
				config_err($file_line_num, "$line - Full paths not allowed for backup destinations");
				next;
			}
			
			# if we have special options specified for this backup point, remember them
			if (defined($opt_str) && $opt_str) {
				$opts_ref = parse_backup_opts($opt_str);
				if (!defined($opts_ref)) {
					config_err(
						$file_line_num, "$line - Syntax error on line $file_line_num in extra opts: $opt_str"
					);
					next;
				}
			}
			
			# remember src/dest
			# also, first check to see that we're not backing up the snapshot directory
			#
			# there are now two methods of making sure the user doesn't accidentally backup their snapshot_root
			# recursively in a backup point: the good way, and the old way.
			#
			# in the old way, when rsnapshot detects the snapshot_root is under a backup point, the files and
			# directories under that backup point are enumerated and get turned into several distinct rsync calls.
			# for example, if you tried to back up "/", it would do a separate rsync invocation for "/bin/", "/etc/",
			# and so on. this wouldn't be so bad except that it makes certain rsync options like one_fs and the
			# include/exclude rules act funny since rsync isn't starting where the user expects (and there is no
			# really good way to provide a workaround, either automatically or manually). however, changing this
			# behaviour that users have come to rely on would not be very nice, so the old code path is left here
			# for those that specifically enable the rsync_long_args parameter but don't set the --relative option.
			#
			# the new way is much nicer, but relies on the --relative option to rsync, which only became the default
			# in rsnapshot 1.2.0 (primarily for this feature). basically, rsnapshot dynamically constructs an exclude
			# path to avoid backing up the snapshot_root. clean and simple. many thanks to bharat mediratta for coming
			# up with this solution!!!
			#
			# we only need to do any of this if the user IS trying to backup the snapshot_root
			if ((is_real_local_abs_path("$src")) && ($config_vars{'snapshot_root'} =~ m/^$src/)) {
				
				# old, less good, backward compatibility method
				if ( defined($config_vars{'rsync_long_args'}) && ($config_vars{'rsync_long_args'} !~ m/--relative/) ) {
					# remove trailing slashes from source and dest, since we will be using our own
					$src    = remove_trailing_slash($src);
					$dest   = remove_trailing_slash($dest);
					
					opendir(SRC, "$src") or bail("Could not open $src");
					
					while (my $node = readdir(SRC)) {
						next if ($node =~ m/^\.\.?$/o); # skip '.' and '..'
						
						# avoid double slashes from root filesystem
						if ($src eq '/') {
							$src = '';
						}
						
						# if this directory is in the snapshot_root, skip it
						# otherwise, back it up
						#
						if ("$config_vars{'snapshot_root'}" !~ m/^$src\/$node/) {
							my %hash;
							
							$hash{'src'}    = "$src/$node";
							$hash{'dest'}   = "$dest/$node";
							
							if (defined($opts_ref)) {
								$hash{'opts'} = $opts_ref;
							}
							push(@backup_points, \%hash);
						}
					}
					closedir(SRC);
					
				# new, shiny, preferred method. the way of the future.
				} else {
					my %hash;
					my $exclude_path;
					
					$hash{'src'}	= $src;
					$hash{'dest'}	= $dest;
					if (defined($opts_ref)) {
						$hash{'opts'} = $opts_ref;
					}
					
					# dynamically generate an exclude path to avoid backing up the snapshot root.
					# depending on the backup point and the snapshot_root location, this could be
					# almost anything. it's tempting to think that just using the snapshot_root as
					# the exclude path will work, but it doesn't. instead, this an exclude path that
					# starts relative to the backup point. for example, if snapshot_root is set to
					# /backup/private/snapshots/, and the backup point is /backup/, the exclude path
					# will be private/snapshots/. the trailing slash does not appear to matter.
					#
					# it's also worth noting that this doesn't work at all without the --relative
					# flag being passed to rsync (which is now the default).
					#
					# this method was added by bharat mediratta, and replaces my older, less elegant
					# attempt to run multiple invocations of rsync instead.
					#
					$exclude_path = $config_vars{'snapshot_root'};
					$exclude_path =~ s/^$src//;
					
					# pass it to rsync on this backup point only
					$hash{'opts'}{'extra_rsync_long_args'} .= sprintf(' --exclude=%s', $exclude_path);
					
					push(@backup_points, \%hash);
				}
				
			# the user is NOT trying to backup the snapshot_root. no workarounds required at all.
			} else {
				my %hash;
				$hash{'src'}	= $src;
				$hash{'dest'}	= $dest;
				if (defined($opts_ref)) {
					$hash{'opts'} = $opts_ref;
				}
				push(@backup_points, \%hash);
			}
			
			next;
		}
		
		# BACKUP SCRIPTS
		if ($var eq 'backup_script') {
			my $full_script	= $value;	# backup script to run (including args)
			my $dest		= $value2;	# dest directory
			my %hash;					# tmp hash to stick in the backup points array
			my $script;					# script file (no args)
			my @script_argv;			# tmp array to help us separate the script from the args
			
			if ( !defined($config_vars{'snapshot_root'}) ) {
				config_err($file_line_num, "$line - snapshot_root needs to be defined before backup scripts");
				next;
			}
			
			if (!defined($dest)) {
				config_err($file_line_num, "$line - no destination path specified");
				next;
			}
			
			# get the base name of the script, not counting any arguments to it
			@script_argv = split(/\s+/, $full_script);
			$script = $script_argv[0];
			
			# make sure the destination is a full path
			if (1 == is_valid_local_abs_path($dest)) {
				config_err($file_line_num, "$line - Backup destination $dest must be a local, relative path");
				next;
			}
			
			# make sure we aren't traversing directories (exactly 2 dots can't be next to each other)
			if (1 == is_directory_traversal($dest)) {
				config_err($file_line_num, "$line - Directory traversal attempted in $dest");
				next;
			}
			
			# make sure script exists and is executable
			if (((! -f "$script") or (! -x "$script")) or !is_real_local_abs_path($script)) {
				config_err($file_line_num, "$line - \"$script\" is not executable or can't be found.".($script !~ m{^/} ? " Please use an absolute path.":""));
				next;
			}
			
			$hash{'script'}	= $full_script;
			$hash{'dest'}	= $dest;
			
			$line_syntax_ok = 1;
			
			push(@backup_points, \%hash);
			
			next;
		}
		
		# GLOBAL OPTIONS from the config file
		# ALL ARE OPTIONAL
		#
		# LINK_DEST
		if ($var eq 'link_dest') {
			if (!defined($value)) {
				config_err($file_line_num, "$line - link_dest can not be blank");
				next;
			}
			if (!is_boolean($value)) {
				config_err(
					$file_line_num, "$line - \"$value\" is not a legal value for link_dest, must be 0 or 1 only"
				);
				next;
			}
			
			$link_dest = $value;
			$line_syntax_ok = 1;
			next;
		}
		# ONE_FS
		if ($var eq 'one_fs') {
			if (!defined($value)) {
				config_err($file_line_num, "$line - one_fs can not be blank");
				next;
			}
			if (!is_boolean($value)) {
				config_err(
					$file_line_num, "$line - \"$value\" is not a legal value for one_fs, must be 0 or 1 only"
				);
				next;
			}
			
			$one_fs = $value;
			$line_syntax_ok = 1;
			next;
		}
		# LOCKFILE
		if ($var eq 'lockfile') {
			if (!defined($value)) { config_err($file_line_num, "$line - lockfile can not be blank"); }
			if (0 == is_valid_local_abs_path("$value")) {
				config_err($file_line_num, "$line - lockfile must be a full path");
				next;
			}
			$config_vars{'lockfile'} = $value;
			$line_syntax_ok = 1;
			next;
		}
		#STOP_ON_STALE_LOCKFILE
		if ($var eq 'stop_on_stale_lockfile') {
			if (!defined($value)) {
				config_err($file_line_num, "$line - stop_on_stale_lockfile can not be blank");
				next;
			}
			if (!is_boolean($value)) {
				config_err(
					$file_line_num, "$line - \"$value\" is not a legal value for stop_on_stale_lockfile, must be 0 or 1 only"
				);
				next;
			}

			$stop_on_stale_lockfile = $value;
			$line_syntax_ok = 1;
			next;
		}
		# INCLUDE
		if ($var eq 'include') {
			if (!defined($rsync_include_args)) {
				$rsync_include_args = "--include=$value";
			} else {
				$rsync_include_args .= " --include=$value";
			}
			$line_syntax_ok = 1;
			next;
		}
		# EXCLUDE
		if ($var eq 'exclude') {
			if (!defined($rsync_include_args)) {
				$rsync_include_args = "--exclude=$value";
			} else {
				$rsync_include_args .= " --exclude=$value";
			}
			$line_syntax_ok = 1;
			next;
		}
		# INCLUDE FILE
		if ($var eq 'include_file') {
			if (0 == is_real_local_abs_path($value)) {
				config_err($file_line_num, "$line - include_file $value must be a valid absolute path");
				next;
			} elsif (1 == is_directory_traversal($value)) {
				config_err($file_line_num, "$line - Directory traversal attempted in $value");
				next;
			} elsif (( -e "$value" ) && ( ! -f "$value" )) {
				config_err($file_line_num, "$line - include_file $value exists, but is not a file");
				next;
			} elsif ( ! -r "$value" ) {
				config_err($file_line_num, "$line - include_file $value exists, but is not readable");
				next;
			} else {
				if (!defined($rsync_include_file_args)) {
					$rsync_include_file_args = "--include-from=$value";
				} else {
					$rsync_include_file_args .= " --include-from=$value";
				}
				$line_syntax_ok = 1;
				next;
			}
		}
		# EXCLUDE FILE
		if ($var eq 'exclude_file') {
			if (0 == is_real_local_abs_path($value)) {
				config_err($file_line_num, "$line - exclude_file $value must be a valid absolute path");
				next;
			} elsif (1 == is_directory_traversal($value)) {
				config_err($file_line_num, "$line - Directory traversal attempted in $value");
				next;
			} elsif (( -e "$value" ) && ( ! -f "$value" )) {
				config_err($file_line_num, "$line - exclude_file $value exists, but is not a file");
				next;
			} elsif ( ! -r "$value" ) {
				config_err($file_line_num, "$line - exclude_file $value exists, but is not readable");
				next;
			} else {
				if (!defined($rsync_include_file_args)) {
					$rsync_include_file_args = "--exclude-from=$value";
				} else {
					$rsync_include_file_args .= " --exclude-from=$value";
				}
				$line_syntax_ok = 1;
				next;
			}
		}
		# RSYNC SHORT ARGS
		if ($var eq 'rsync_short_args') {
			# must be in the format '-abcde'
			if (0 == is_valid_rsync_short_args($value)) {
				config_err($file_line_num, "$line - rsync_short_args \"$value\" not in correct format");
				next;
			} else {
				$config_vars{'rsync_short_args'} = $value;
				$line_syntax_ok = 1;
				next;
			}
		}
		# RSYNC LONG ARGS
		if ($var eq 'rsync_long_args') {
			$config_vars{'rsync_long_args'} = $value;
			$line_syntax_ok = 1;
			next;
		}
		# SSH ARGS
		if ($var eq 'ssh_args') {
			if (!defined($default_ssh_args) && defined($config_vars{'ssh_args'})) {
				config_err($file_line_num, "$line - global ssh_args can only be set once, but is already set.  Perhaps you wanted to use a per-backup-point ssh_args instead.");
				next;
			} else {
				$config_vars{'ssh_args'} = $value;
				$line_syntax_ok = 1;
				next;
			}
		}
		# DU ARGS
		if ($var eq 'du_args') {
			$config_vars{'du_args'} = $value;
			$line_syntax_ok = 1;
			next;
		}
		# LVM CMDS
		if ($var =~ m/^linux_lvm_cmd_(lvcreate|mount)$/) {
			$config_vars{$var} = $value;
			$line_syntax_ok = 1;
			next;
		}
		# LVM ARGS
		if ($var =~ m/^linux_lvm_(vgpath|snapshotname|snapshotsize|mountpath)$/) {
			$config_vars{$var} = $value;
			$line_syntax_ok = 1;
			next;
		}
		# LOGFILE
		if ($var eq 'logfile') {
			if (0 == is_valid_local_abs_path($value)) {
				config_err($file_line_num, "$line - logfile must be a valid absolute path");
				next;
			} elsif (1 == is_directory_traversal($value)) {
				config_err($file_line_num, "$line - Directory traversal attempted in $value");
				next;
			} elsif (( -e "$value" ) && ( ! -f "$value" ) && ( ! -p "$value" ) ) {
				config_err($file_line_num, "$line - logfile $value exists, but is not a file");
				next;
			} else {
				$config_vars{'logfile'} = $value;
				$line_syntax_ok = 1;
				next;
			}
		}
		# VERBOSE
		if ($var eq 'verbose') {
			if (1 == is_valid_loglevel($value)) {
				if (!defined($verbose)) {
					$verbose = $value;
				}
				
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - verbose must be a value between 1 and 5");
				next;
			}
		}
		# LOGLEVEL
		if ($var eq 'loglevel') {
			if (1 == is_valid_loglevel($value)) {
				if (!defined($loglevel)) {
					$loglevel = $value;
				}
				
				$line_syntax_ok = 1;
				next;
			} else {
				config_err($file_line_num, "$line - loglevel must be a value between 1 and 5");
				next;
			}
		}
		# USE LAZY DELETES
		if ($var eq 'use_lazy_deletes') {
			if (!defined($value)) {
				config_err($file_line_num, "$line - use_lazy_deletes can not be blank");
				next;
			}
			if (!is_boolean($value)) {
				config_err(
					$file_line_num, "$line - \"$value\" is not a legal value for use_lazy_deletes, must be 0 or 1 only"
				);
				next;
			}
			
			if (1 == $value) { $use_lazy_deletes = 1; }
			$line_syntax_ok = 1;
			next;
		}
		# RSYNC NUMBER OF TRIES
		if ($var eq 'rsync_numtries') {
			if (!defined($value)) {
				config_err($file_line_num, "$line - rsync_numtries can not be blank");
				next;
			}
			if (!is_valid_rsync_numtries($value)) {
				config_err(
					$file_line_num, "$line - \"$value\" is not a legal value for rsync_numtries, must be greater than or equal to 0"
				);
				next;
			}
		
			$rsync_numtries = int($value);
			$line_syntax_ok = 1;
			next;
               }
				
		# make sure we understood this line
		# if not, warn the user, and prevent the program from executing
		# however, don't bother if the user has already been notified
		if (1 == $config_perfect) {
			if (0 == $line_syntax_ok) {
				config_err($file_line_num, $line);
				next;
			}
		}
	}
}
	
sub validate_config_file {
	####################################################################
	# SET SOME SENSIBLE DEFAULTS FOR VALUES THAT MAY NOT HAVE BEEN SET #
	####################################################################
	
	# if we didn't manage to get a verbose level yet, either through the config file
	# or the command line, use the default
	if (!defined($verbose)) {
		$verbose = $default_verbose;
	}
	# same for loglevel
	if (!defined($loglevel)) {
		$loglevel = $default_loglevel;
	}
	# assemble rsync include/exclude args
	if (defined($rsync_include_args)) {
		if (!defined($config_vars{'rsync_long_args'})) {
			$config_vars{'rsync_long_args'} = $default_rsync_long_args;
		}
		$config_vars{'rsync_long_args'} .= " $rsync_include_args";
	}
	# assemble rsync include/exclude file args
	if (defined($rsync_include_file_args)) {
		if (!defined($config_vars{'rsync_long_args'})) {
			$config_vars{'rsync_long_args'} = $default_rsync_long_args;
		}
		$config_vars{'rsync_long_args'} .= " $rsync_include_file_args";
	}
	
	###############################################
	# NOW THAT THE CONFIG FILE HAS BEEN READ IN,  #
	# DO A SANITY CHECK ON THE DATA WE PULLED OUT #
	###############################################
	
	# SINS OF COMMISSION
	# (incorrect entries in config file)
	if (0 == $config_perfect) {
		print_err("---------------------------------------------------------------------", 1);
		print_err("Errors were found in $config_file,", 1);
		print_err("rsnapshot can not continue. If you think an entry looks right, make", 1);
		print_err("sure you don't have spaces where only tabs should be.", 1);
		
		# if this wasn't a test, report the error to syslog
		if (0 == $do_configtest) {
			syslog_err("Errors were found in $config_file, rsnapshot can not continue.");
		}
		
		# exit showing an error
		exit(1);
	}
	
	# SINS OF OMISSION
	# (things that should be in the config file that aren't)
	#
	# make sure config_version was set
	if (!defined($config_vars{'config_version'})) {
		print_err ("config_version was not defined. rsnapshot can not continue.", 1);
		syslog_err("config_version was not defined. rsnapshot can not continue.");
		exit(1);
	}
	# make sure rsync was defined
	if (!defined($config_vars{'cmd_rsync'})) {
		print_err ("cmd_rsync was not defined.", 1);
		syslog_err("cmd_rsync was not defined.", 1);
		exit(1);
	}
	# make sure we got a snapshot_root
	if (!defined($config_vars{'snapshot_root'})) {
		print_err ("snapshot_root was not defined. rsnapshot can not continue.", 1);
		syslog_err("snapshot_root was not defined. rsnapshot can not continue.");
		exit(1);
	}
	# make sure we have at least one interval
	if (0 == scalar(@intervals)) {
		print_err ("At least one backup level must be set. rsnapshot can not continue.", 1);
		syslog_err("At least one backup level must be set. rsnapshot can not continue.");
		exit(1);
	}
	# make sure we have at least one backup point
	if (0 == scalar(@backup_points)) {
		print_err ("At least one backup point must be set. rsnapshot can not continue.", 1);
		syslog_err("At least one backup point must be set. rsnapshot can not continue.");
		exit(1);
	}

	# SINS OF CONFUSION
	# (various, specific, undesirable interactions)
	#
	# make sure that we don't have only one copy of the first interval,
	# yet expect rotations on the second interval
	if (scalar(@intervals) > 1) {
		if (defined($intervals[0]->{'number'})) {
			if (1 == $intervals[0]->{'number'}) {
				print_err ("Can not have first backup level's retention count set to 1, and have a second backup level", 1);
				syslog_err("Can not have first backup level's retention count set to 1, and have a second backup level");
				exit(1);
			}
		}
	}
	# make sure that the snapshot_root exists if no_create_root is set to 1
	if (defined($config_vars{'no_create_root'})) {
		if (1 == $config_vars{'no_create_root'}) {
			if ( ! -d "$config_vars{'snapshot_root'}" ) {
				if ( -e "$config_vars{'snapshot_root'}" ) {
					print_err ("$config_vars{'snapshot_root'} is not a directory.", 1);
				} else {
					print_err ("$config_vars{'snapshot_root'} does not exist.", 1);
				}
				print_err ("rsnapshot refuses to create snapshot_root when no_create_root is enabled", 1);
				syslog_err("rsnapshot refuses to create snapshot_root when no_create_root is enabled");
				exit(1);
			}
		}
	}
	# make sure that the user didn't call "sync" if sync_first isn't enabled
	if (($cmd eq 'sync') && (! $config_vars{'sync_first'})) {
		print_err ("\"sync_first\" must be enabled for \"sync\" to work", 1);
		syslog_err("\"sync_first\" must be enabled for \"sync\" to work");
		exit(1);
	}
	# make sure that the backup_script destination paths don't nuke data copied over for backup points
	{
		my @backup_dest			= ();
		my @backup_script_dest	= ();
		
		# remember where the destination paths are...
		foreach my $bp_ref (@backup_points) {
			my $tmp_dest_path = $$bp_ref{'dest'};
			
			# normalize multiple slashes, and strip trailing slash
			$tmp_dest_path =~ s/\/+/\//g;
			$tmp_dest_path =~ s/\/$//;
			
			# backup
			if (defined($$bp_ref{'src'})) {
				push(@backup_dest, $tmp_dest_path);
				
			# backup_script
			} elsif (defined($$bp_ref{'script'})) {
				push(@backup_script_dest, $tmp_dest_path);
				
			# something else is wrong
			} else {
				print_err ("logic error in parse_config_file(): a backup point has no src and no script", 1);
				syslog_err("logic error in parse_config_file(): a backup point has no src and no script");
				exit(1);
			}
		}
		
		# loop through and check for conflicts between backup and backup_script destination paths
		foreach my $b_dest (@backup_dest) {
			foreach my $bs_dest (@backup_script_dest) {
				if (defined($b_dest) && defined($bs_dest)) {
					my $tmp_b  = $b_dest;
					my $tmp_bs = $bs_dest;
					
					# add trailing slashes back in so similarly named directories don't match
					# e.g., localhost/abc/ and localhost/ab/
					$tmp_b  .= '/';
					$tmp_bs .= '/';
					
					if ("$b_dest" =~ m/^$bs_dest/) {
						# duplicate entries, stop here
						print_err (
							"destination conflict between \"$tmp_b\" and \"$tmp_bs\" in backup / backup_script entries",
							1
						);
						syslog_err(
							"destination conflict between \"$tmp_b\" and \"$tmp_bs\" in backup / backup_script entries"
						);
						exit(1);
					}
				} else {
					print_err ("logic error in parse_config_file(): unique destination check failed unexpectedly", 1);
					syslog_err("logic error in parse_config_file(): unique destination check failed unexpectedly");
					exit(1);
				}
			}
		}
		# loop through and check for conflicts between different backup_scripts
		for (my $i=0; $i<scalar(@backup_script_dest); $i++) {
			for (my $j=0; $j<scalar(@backup_script_dest); $j++) {
				if ($i != $j) {
					my $path1 = $backup_script_dest[$i];
					my $path2 = $backup_script_dest[$j];
					
					# add trailing slashes back in so similarly named directories don't match
					# e.g., localhost/abc/ and localhost/ab/
					$path1 .= '/';
					$path2 .= '/';
					
					if (("$path1" =~ m/$path2/) or ("$path2" =~ m/$path1/)) {
						print_err (
							"destination conflict between \"$path1\" and \"$path2\" in multiple backup_script entries", 1
						);
						syslog_err(
							"destination conflict between \"$path1\" and \"$path2\" in multiple backup_script entries"
						);
						exit(1);
					}
				}
			}
		}
	}
}

# accepts a string of options
# returns an array_ref of parsed options
# returns undef if there is an invalid option
#
# this is for individual backup points only
sub parse_backup_opts {
	my $opts_str = shift(@_);
	my @pairs;
	my %parsed_opts;
	
	# pre-buffer extra rsync arguments
	my $rsync_include_args		= undef;
	my $rsync_include_file_args	= undef;
	
	# make sure we got something (it's quite likely that we didn't)
	if (!defined($opts_str))	{ return (undef); }
	if (!$opts_str)				{ return (undef); }
	
	# split on commas first
	@pairs = split(/,/, $opts_str);
	
	# then loop through and split on equals
	foreach my $pair (@pairs) {
		my $additive;
		if ($pair =~ /^\+/) {
			$additive = 1;
			$pair =~ s/^.//;
		} else {
			$additive = 0;
		}
		
		my ($name, $value) = split(/=/, $pair, 2);
		if ( !defined($name) or !defined($value) ) {
			return (undef);
		}
		
		# parameters can't have spaces in them
		$name =~ s/\s+//go;
		
		# strip whitespace from both ends
		$value =~ s/^\s{0,}//o;
		$value =~ s/\s{0,}$//o;
		
		# ok, it's a name/value pair and it's ready for more validation
		if ($additive) {
			$parsed_opts{'extra_' . $name} = $value;
		} else {
			$parsed_opts{$name} = $value;
		}
		
		# VALIDATE ARGS
		# one_fs
		if ( $name eq 'one_fs' ) {
			if (!is_boolean($parsed_opts{'one_fs'})) {
				return (undef);
			}
		# rsync_short_args
		} elsif ( $name eq 'rsync_short_args' ) {
			# must be in the format '-abcde'
			if (0 == is_valid_rsync_short_args($value)) {
				print_err("rsync_short_args \"$value\" not in correct format", 2);
				return (undef);
			}
			
		# rsync_long_args
		} elsif ( $name eq 'rsync_long_args' ) {
			# pass unchecked
			
		# ssh_args
		} elsif ( $name eq 'ssh_args' ) {
			# pass unchecked
			
		# lvm args
		} elsif ( $name =~ m/^linux_lvm_(vgpath|snapshotname|snapshotsize|mountpath)$/ ) {
			# pass unchecked
			
		# include
		} elsif ( $name eq 'include' ) {
			# don't validate contents
			# coerce into rsync_include_args
			# then remove the "include" key/value pair
			if (!defined($rsync_include_args)) {
				$rsync_include_args = "--include=$parsed_opts{'include'}";
			} else {
				$rsync_include_args .= " --include=$parsed_opts{'include'}";
			}
			
			delete($parsed_opts{'include'});
			
		# exclude
		} elsif ( $name eq 'exclude' ) {
			# don't validate contents
			# coerce into rsync_include_args
			# then remove the "include" key/value pair
			if (!defined($rsync_include_args)) {
				$rsync_include_args = "--exclude=$parsed_opts{'exclude'}";
			} else {
				$rsync_include_args .= " --exclude=$parsed_opts{'exclude'}";
			}
			
			delete($parsed_opts{'exclude'});
			
		# include_file
		} elsif ( $name eq 'include_file' ) {
			# verify that this file exists and is readable
			if (0 == is_real_local_abs_path($value)) {
				print_err("include_file $value must be a valid absolute path", 2);
				return (undef);
			} elsif (1 == is_directory_traversal($value)) {
				print_err("Directory traversal attempted in $value", 2);
				return (undef);
			} elsif (( -e "$value" ) && ( ! -f "$value" )) {
				print_err("include_file $value exists, but is not a file", 2);
				return (undef);
			} elsif ( ! -r "$value" ) {
				print_err("include_file $value exists, but is not readable", 2);
				return (undef);
			}
			
			# coerce into rsync_include_file_args
			# then remove the "include_file" key/value pair
			if (!defined($rsync_include_file_args)) {
				$rsync_include_file_args = "--include-from=$parsed_opts{'include_file'}";
			} else {
				$rsync_include_file_args .= " --include-from=$parsed_opts{'include_file'}";
			}
			
			delete($parsed_opts{'include_file'});
			
		# exclude_file
		} elsif ( $name eq 'exclude_file' ) {
			# verify that this file exists and is readable
			if (0 == is_real_local_abs_path($value)) {
				print_err("exclude_file $value must be a valid absolute path", 2);
				return (undef);
			} elsif (1 == is_directory_traversal($value)) {
				print_err("Directory traversal attempted in $value", 2);
				return (undef);
			} elsif (( -e "$value" ) && ( ! -f "$value" )) {
				print_err("exclude_file $value exists, but is not a file", 2);
				return (undef);
			} elsif ( ! -r "$value" ) {
				print_err("exclude_file $value exists, but is not readable", 2);
				return (undef);
			}
			
			# coerce into rsync_include_file_args
			# then remove the "exclude_file" key/value pair
			if (!defined($rsync_include_file_args)) {
				$rsync_include_file_args = "--exclude-from=$parsed_opts{'exclude_file'}";
			} else {
				$rsync_include_file_args .= " --exclude-from=$parsed_opts{'exclude_file'}";
			}
			
			delete($parsed_opts{'exclude_file'});

		# Not (yet?) implemented as per-backup-point options
		} elsif ( $name eq 'cmd_preexec' || $name eq 'cmd_postexec' 
			|| $name eq 'cmd_ssh' || $name eq 'cmd_rsync'
			|| $name eq 'verbose' || $name eq 'loglevel') {
			print_err("$name is not implemented as a per-backup-point option in this version of rsnapshot", 2);
			return (undef);

		# if we don't know about it, it doesn't exist
		} else {
			return (undef);
		}
	}
	
	# merge rsync_include_args and rsync_file_include_args in with either $default_rsync_long_args
	# or $parsed_opts{'rsync_long_args'}
	if (defined($rsync_include_args) or defined($rsync_include_file_args)) {
		# if we never defined rsync_long_args, populate it with the global default
		if (!defined($parsed_opts{'rsync_long_args'})) {
			if (defined($config_vars{'rsync_long_args'})) {
				$parsed_opts{'rsync_long_args'} = $config_vars{'rsync_long_args'};
			} else {
				$parsed_opts{'rsync_long_args'} = $default_rsync_long_args;
			}
		}
		
		# now we have something in our local rsync_long_args
		# let's concatenate the include/exclude/file stuff to it
		if (defined($rsync_include_args)) {
			$parsed_opts{'rsync_long_args'} .= " $rsync_include_args";
		}
		if (defined($rsync_include_file_args)) {
			$parsed_opts{'rsync_long_args'} .= " $rsync_include_file_args";
		}
	}
	
	# if we got anything, return it as an array_ref
	if (%parsed_opts) {
		return (\%parsed_opts);
	}
	
	return (undef);
}

# accepts line number, errstr
# prints a config file error
# also sets global $config_perfect var off
sub config_err {
	my $line_num	= shift(@_);
	my $errstr		= shift(@_);
	
	if (!defined($line_num))	{ $line_num = -1; }
	if (!defined($errstr))		{ $errstr = 'config_err() called without an error string!'; }
	
	# show the user the file and line number
	print_err("$config_file on line $line_num:", 1);
	
	# print out the offending line
	# don't print past 69 columns (because they all start with 'ERROR: ')
	# similarly, indent subsequent lines 9 spaces to get past the 'ERROR: ' message
	print_err( wrap_cmd($errstr, 69, 9), 1 );
	
	# invalidate entire config file
	$config_perfect = 0;
}

# accepts an error string
# prints to STDERR and maybe syslog. removes the lockfile if it exists.
# exits the program safely and consistently
sub bail {
	my $str = shift(@_);
	
	# print out error
	if ($str) {
		print_err($str, 1);
	}
	
	# write to syslog if we're running for real (and we have a message)
	if ((0 == $do_configtest) && (0 == $test) && defined($str) && ('' ne $str)) {
		syslog_err($str);
	}
	
	# get rid of the lockfile, if it exists
	if(0 == $stop_on_stale_lockfile) {
	        remove_lockfile();
	}
	
	# exit showing an error
	exit(1);
}

# accepts a string (or an array)
# prints the string, but separates it across multiple lines with backslashes if necessary
# also logs the command, but on a single line
sub print_cmd {
	# take all arguments and make them into one string
	my $str = join(' ', @_);
	
	if (!defined($str)) { return (undef); }
	
	# remove newline and consolidate spaces
	chomp($str);
	$str =~ s/\s+/ /g;
	
	# write to log (level 3 is where we start showing commands)
	log_msg($str, 3);
	
	if (!defined($verbose) or ($verbose >= 3)) {
		print wrap_cmd($str), "\n";
	}
}

# accepts a string
# wraps the text to fit in 80 columns with backslashes at the end of each wrapping line
# returns the wrapped string
sub wrap_cmd {
	my $str		= shift(@_);
	my $colmax	= shift(@_);
	my $indent	= shift(@_);
	
	my @tokens;
	my $chars = 0;		# character tally
	my $outstr = '';	# string to return
	
	# max chars before wrap (default to 80 column terminal)
	if (!defined($colmax)) {
		$colmax = 76;
	}
	
	# number of spaces to indent subsequent lines
	if (!defined($indent)) {
		$indent = 4;
	}
	
	# break up string into individual pieces
	@tokens = split(/\s+/, $str);
	
	# stop here if we don't have anything
	if (0 == scalar(@tokens)) { return (''); }
	
	# print the first token as a special exception, since we should never start out by line wrapping
	if (defined($tokens[0])) {
		$chars = (length($tokens[0]) + 1);
		$outstr .= $tokens[0];
		
		# don't forget to put the space back in
		if (scalar(@tokens) > 1) {
			$outstr .= ' ';
		}
	}
	
	# loop through the rest of the tokens and print them out, wrapping when necessary
	for (my $i=1; $i<scalar(@tokens); $i++) {
		# keep track of where we are (plus a space)
		$chars += (length($tokens[$i]) + 1);
		
		# wrap if we're at the edge
		if ($chars > $colmax) {
			$outstr .= "\\\n";
			$outstr .= (' ' x $indent);
			
			# 4 spaces + string length
			$chars = $indent + length($tokens[$i]);
		}
		
		# print out this token
		$outstr .= $tokens[$i];
		
		# print out a space unless this is the last one
		if ($i < scalar(@tokens)) {
			$outstr .= ' ';
		}
	}
	
	return ($outstr);
}

# accepts string, and level
# prints string if level is as high as verbose
# logs string if level is as high as loglevel
sub print_msg {
	my $str		= shift(@_);
	my $level	= shift(@_);
	
	if (!defined($str))		{ return (undef); }
	if (!defined($level))	{ $level = 0; }
	
	chomp($str);
	
	# print to STDOUT
	if ((!defined($verbose)) or ($verbose >= $level)) {
		print $str, "\n";
	}
	
	# write to log
	log_msg($str, $level);
}

# accepts string, and level
# prints string if level is as high as verbose
# logs string if level is as high as loglevel
# also raises a warning for the exit code
sub print_warn {
	my $str		= shift(@_);
	my $level	= shift(@_);
	
	if (!defined($str))		{ return (undef); }
	if (!defined($level))	{ $level = 0; }
	
	# we can no longer say the execution of the program has been error free
	raise_warning();
	
	chomp($str);
	
	# print to STDERR
	if ((!defined($verbose)) or ($level <= $verbose)) {
		print STDERR 'WARNING: ', $str, "\n";
	}
	
	# write to log
	log_msg($str, $level);
}

# accepts string, and level
# prints string if level is as high as verbose
# logs string if level is as high as loglevel
# also raises an error for the exit code
sub print_err {
	my $str		= shift(@_);
	my $level	= shift(@_);
	
	if (!defined($str))		{ return (undef); }
	if (!defined($level))	{ $level = 0; }
	
	# we can no longer say the execution of the program has been error free
	raise_error();
	
	chomp($str);
	
	# print the run string once
	# this way we know where the message came from if it's in an e-mail
	# but we can still read messages at the console
	if (0 == $have_printed_run_string) {
		if ((!defined($verbose)) or ($level <= $verbose)) {
			print STDERR "----------------------------------------------------------------------------\n";
			print STDERR "rsnapshot encountered an error! The program was invoked with these options:\n";
			print STDERR wrap_cmd($run_string), "\n";
			print STDERR "----------------------------------------------------------------------------\n";
		}
		
		$have_printed_run_string = 1;
	}
	
	# print to STDERR
	if ((!defined($verbose)) or ($level <= $verbose)) {
		#print STDERR $run_string, ": ERROR: ", $str, "\n";
		print STDERR "ERROR: ", $str, "\n";
	}
	
	# write to log
	log_err($str, $level);
}

# accepts string, and level
# logs string if level is as high as loglevel
sub log_msg {
	my $str		= shift(@_);
	my $level	= shift(@_);
	my $result	= undef;
	
	if (!defined($str))		{ return (undef); }
	if (!defined($level))	{ return (undef); }
	
	chomp($str);
	
	# if this is just noise, don't log it
	if (defined($loglevel) && ($level > $loglevel)) {
		return (undef);
	}
	
	# open logfile, write to it, close it back up
	# if we fail, don't use the usual print_* functions, since they just call this again
	if ((0 == $test) && (0 == $do_configtest)) {
		if (defined($config_vars{'logfile'})) {
			$result = open (LOG, ">> $config_vars{'logfile'}");
			if (!defined($result)) {
				print STDERR "Could not open logfile $config_vars{'logfile'} for writing\n";
				print STDERR "Do you have write permission for this file?\n";
				exit(1);
			}
			
			print LOG '[', get_current_date(), '] ', $str, "\n";
			
			$result = close(LOG);
			if (!defined($result)) {
				print STDERR "Could not close logfile $config_vars{'logfile'}\n";
			}
		}
	}
}

# accepts string, and level
# logs string if level is as high as loglevel
# also raises a warning for the exit code
sub log_warn {
	my $str		= shift(@_);
	my $level	= shift(@_);
	
	if (!defined($str))		{ return (undef); }
	if (!defined($level))	{ return (undef); }
	
	# this run is no longer perfect since we have an error
	raise_warning();
	
	chomp($str);
	
	$str = 'WARNING: ' . $str;
	log_msg($str, $level);
}

# accepts string, and level
# logs string if level is as high as loglevel
# also raises an error for the exit code
sub log_err {
	my $str		= shift(@_);
	my $level	= shift(@_);
	
	if (!defined($str))		{ return (undef); }
	if (!defined($level))	{ return (undef); }
	
	# this run is no longer perfect since we have an error
	raise_error();
	
	chomp($str);
	
	$str = "$run_string: ERROR: " . $str;
	log_msg($str, $level);
}

# log messages to syslog
# accepts message, facility, level
# only message is required
# return 1 on success, undef on failure
sub syslog_msg {
	my $msg			= shift(@_);
	my $facility	= shift(@_);
	my $level		= shift(@_);
	my $result		= undef;
	
	if (!defined($msg))			{ return (undef); }
	if (!defined($facility))	{ $facility	= 'user'; }
	if (!defined($level))		{ $level	= 'info'; }
	
	if (defined($config_vars{'cmd_logger'})) {
		# print out our call to syslog
		if (defined($verbose) && ($verbose >= 4)) {
			print_cmd("$config_vars{'cmd_logger'} -i -p $facility.$level -t rsnapshot $msg");
		}
		
		# log to syslog
		if (0 == $test) {
			$result = system($config_vars{'cmd_logger'}, '-i', '-p', "$facility.$level", '-t', 'rsnapshot', $msg);
			if (0 != $result) {
				print_warn("Could not log to syslog:", 2);
				print_warn("$config_vars{'cmd_logger'} -i -p $facility.$level -t rsnapshot $msg", 2);
			}
		}
	}
	
	return (1);
}

# log warnings to syslog
# accepts warning message
# returns 1 on success, undef on failure
# also raises a warning for the exit code
sub syslog_warn {
	my $msg = shift(@_);
	
	# this run is no longer perfect since we have an error
	raise_warning();
	
	return syslog_msg("WARNING: $msg", 'user', 'err');
}

# log errors to syslog
# accepts error message
# returns 1 on success, undef on failure
# also raises an error for the exit code
sub syslog_err {
	my $msg = shift(@_);
	
	# this run is no longer perfect since we have an error
	raise_error();
	
	return syslog_msg("$run_string: ERROR: $msg", 'user', 'err');
}

# sets exit code for at least a warning
sub raise_warning {
	if ($exit_code != 1) {
		$exit_code = 2;
	}
}

# sets exit code for error
sub raise_error {
	$exit_code = 1;
}

# accepts no arguments
# returns the current date (for the logfile)
#
# there's probably a wonderful module that can do this all for me,
# but unless it comes standard with perl 5.004 and later, i'd rather do it this way :)
#
sub get_current_date {
	# localtime() gives us an array with these elements:
	# 0 = seconds
	# 1 = minutes
	# 2 = hours
	# 3 = day of month
	# 4 = month + 1
	# 5 = year + 1900
	
	# example date format (just like Apache logs)
	# 28/Feb/2004:23:45:59
	
	my @months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	
	my @fields = localtime(time());
	
	my $datestr =
					# day of month
					sprintf("%02i", $fields[3]) .
					'/' .
					# name of month
					$months[$fields[4]] .
					'/' .
					# year
					($fields[5]+1900) .
					':' .
					# hours (24 hour clock)
					sprintf("%02i", $fields[2]) .
					':' .
					# minutes
					sprintf("%02i", $fields[1]) .
					':' .
					# seconds
					sprintf("%02i", $fields[0]);
	
	return ($datestr);
}

# accepts no arguments
# returns nothing
# simply prints out a startup message to the logs and STDOUT
sub log_startup {
	log_msg("$run_string: started", 2);
}

# accepts no arguments
# returns undef if lockfile isn't defined in the config file, and 1 upon success
# also, it can make the program exit with 1 as the return value if it can't create the lockfile
#
# we don't use bail() to exit on error, because that would remove the
# lockfile that may exist from another invocation
#
# if a lockfile exists, we try to read it (and stop if we can't) to get a PID,
# then see if that PID exists.  If it does, we stop, otherwise we assume it's
# a stale lock and remove it first.
sub add_lockfile {
	# if we don't have a lockfile defined, just return undef
	if (!defined($config_vars{'lockfile'})) {
		return (undef);
	}
	
	my $lockfile = $config_vars{'lockfile'};
	
	# valid?
	if (0 == is_valid_local_abs_path($lockfile)) {
		print_err ("Lockfile $lockfile is not a valid file name", 1);
		syslog_err("Lockfile $lockfile is not a valid file name");
		exit(1);
	}
	
	# does a lockfile already exist?
        if (1 == is_real_local_abs_path($lockfile)) {
            if(!open(LOCKFILE, $lockfile)) {
                print_err ("Lockfile $lockfile exists and can't be read, can not continue!", 1);
                syslog_err("Lockfile $lockfile exists and can't be read, can not continue");
                exit(1);
            }
            my $pid = <LOCKFILE>;
            chomp($pid);
            close(LOCKFILE);
            if(kill(0, $pid)) {
                print_err ("Lockfile $lockfile exists and so does its process, can not continue");
                syslog_err("Lockfile $lockfile exists and so does its process, can not continue");
                exit(1);
            } else {
		if(1 == $stop_on_stale_lockfile) {
		    print_err ("Stale lockfile $lockfile detected. You need to remove it manually to continue", 1);
		    syslog_err("Stale lockfile $lockfile detected. Exiting.");
		    exit(1);
	        } else {
	            print_warn("Removing stale lockfile $lockfile", 1);
		    syslog_warn("Removing stale lockfile $lockfile");
		    remove_lockfile();
	        }
            }
        }

	
	# create the lockfile
	print_cmd("echo $$ > $lockfile");
	
	if (0 == $test) {
		# sysopen() can do exclusive opens, whereas perl open() can not
		my $result = sysopen(LOCKFILE, $lockfile, O_WRONLY | O_EXCL | O_CREAT, 0644);
		if (!defined($result) || 0 == $result) {
			print_err ("Could not write lockfile $lockfile: $!", 1);
			syslog_err("Could not write lockfile $lockfile");
			exit(1);
		}
		
		# print PID to lockfile
		print LOCKFILE $$;
		
		$result = close(LOCKFILE);
		if (!defined($result) || 0 == $result) {
			print_warn("Could not close lockfile $lockfile: $!", 2);
		}
	}
	
	return (1);
}

# accepts no arguments
# accepts the path to a lockfile and tries to remove it
# returns undef if lockfile isn't defined in the config file, and 1 upon success
# also, it can exit the program with a value of 1 if it can't remove the lockfile
#
# we don't use bail() to exit on error, because that would call
# this subroutine twice in the event of a failure
sub remove_lockfile {
	# if we don't have a lockfile defined, return undef
	if (!defined($config_vars{'lockfile'})) {
		return (undef);
	}
	
	my $lockfile = $config_vars{'lockfile'};
	my $result = undef;
	
	if ( -e "$lockfile" ) {
		print_cmd("rm -f $lockfile");
		if (0 == $test) {
			$result = unlink($lockfile);
			if (0 == $result) {
				print_err ("Could not remove lockfile $lockfile", 1);
				syslog_err("Error! Could not remove lockfile $lockfile");
				exit(1);
			}
		}
	} else {
		print_msg("No need to remove non-existent lock $lockfile", 5);
	}
	
	return (1);
}

# accepts no arguments
# returns nothing
# sets the locale to POSIX (C) to mitigate some problems with the rmtree() command
#
sub set_posix_locale {
	# set POSIX locale
	# this may fix some potential problems with rmtree()
	# another solution is to enable "cmd_rm" in rsnapshot.conf
	print_msg("Setting locale to POSIX \"C\"", 4);
	setlocale(POSIX::LC_ALL, 'C');
}

# accepts no arguments
# returns nothing
# creates the snapshot_root directory (chmod 0700), if it doesn't exist and no_create_root == 0
sub create_snapshot_root {
	# attempt to create the directory if it doesn't exist
	if ( ! -d "$config_vars{'snapshot_root'}" ) {
		
		# make sure no_create_root == 0
		if (defined($config_vars{'no_create_root'})) {
			if (1 == $config_vars{'no_create_root'}) {
				print_err ("rsnapshot refuses to create snapshot_root when no_create_root is enabled", 1);
				syslog_err("rsnapshot refuses to create snapshot_root when no_create_root is enabled");
				bail();
			}
		}
		
		# actually create the directory
		print_cmd("mkdir -m 0700 -p $config_vars{'snapshot_root'}/");
		if (0 == $test) {
			eval {
				# don't pass a trailing slash to mkpath
				mkpath( "$config_vars{'snapshot_root'}", 0, 0700 );
			};
			if ($@) {
				bail(
					"Unable to create $config_vars{'snapshot_root'}/,\nPlease make sure you have the right permissions."
				);
			}
		}
	}
}

# accepts current interval
# returns a hash_ref containing information about the intervals
# exits the program if we don't have good data to work with
sub get_interval_data {
	my $cur_interval = shift(@_);
	
	# make sure we were passed an interval
	if (!defined($cur_interval)) { bail("cur_interval not specified in get_interval_data()\n"); }
	
	# the hash to return
	my %hash;
	
	# which of the intervals are we operating on?
	# if we defined hourly, daily, weekly ... hourly = 0, daily = 1, weekly = 2
	my $interval_num;
	
	# the highest possible number for the current interval context
	# if we are working on hourly, and hourly is set to 6, this would be
	# equal to 5 (since we start at 0)
	my $interval_max;
	
	# this is the name of the previous interval, in relation to the one we're
	# working on. e.g., if we're operating on weekly, this should be "daily"
	my $prev_interval;
	
	# same as $interval_max, except for the previous interval.
	# this is used to determine which of the previous snapshots to pull from
	# e.g., cp -al hourly.$prev_interval_max/ daily.0/
	my $prev_interval_max;
	
	# FIGURE OUT WHICH INTERVAL WE'RE RUNNING, AND HOW IT RELATES TO THE OTHERS
	# THEN RUN THE ACTION FOR THE CHOSEN INTERVAL
	# remember, in each hashref in this loop:
	#   "interval" is something like "daily", "weekly", etc.
	#   "number" is the number of these intervals to keep on the filesystem
	
	my $i = 0;
	foreach my $i_ref (@intervals) {
		
		# this is the interval we're set to run
		if ($$i_ref{'interval'} eq $cur_interval) {
			$interval_num = $i;
			
			# how many of these intervals should we keep?
			# we start counting from 0, so subtract one
			# e.g., 6 intervals == interval.0 .. interval.5
			$interval_max = $$i_ref{'number'} - 1;
			
			# we found our interval, exit the foreach loop
			last;
		}
		
		# since the "last" command above breaks from this entire block,
		# and since we loop through the intervals in order, if we got this
		# far in the first place it means that we're looking at an interval
		# which isn't selected to run, and that there will be more intervals in the loop.
		# therefore, this WILL be the previous interval's information, the next time through.
		#
		$prev_interval = $$i_ref{'interval'};
		
		# which of the previous interval's numbered directories should we pull from
		# for the interval we're currently set to run?
		# e.g., daily.0/ might get pulled from hourly.6/
		#
		$prev_interval_max = $$i_ref{'number'} - 1;
		
		$i++;
	}
	
	# make sure we got something that makes sense
	if ($cur_interval ne 'sync') {
		if (!defined($interval_num)) { bail("Interval \"$cur_interval\" unknown, check $config_file"); }
	}
	
	# populate our hash
	$hash{'interval'}			= $cur_interval;
	$hash{'interval_num'}		= $interval_num;
	$hash{'interval_max'}		= $interval_max;
	$hash{'prev_interval'}		= $prev_interval;
	$hash{'prev_interval_max'}	= $prev_interval_max;
	
	# and return the values
	return (\%hash);
}

# accepts no arguments
# prints the most recent snapshot directory and exits
# this is for use with the get-latest-snapshot command line argument
sub show_latest_snapshot {
	# this should only be called after parse_config_file(), but just in case...
	if (! @intervals)	{ bail("Error! intervals not defined in show_latest_snapshot()"); }
	if (! %config_vars) { bail("Error! config_vars not defined in show_latest_snapshot()"); }
	
	# regardless of .sync, this is the latest "real" snapshot
	print $config_vars{'snapshot_root'} . '/' . $intervals[0]->{'interval'} . '.0/' . "\n";
	
	exit(0);
}

# accepts no args
# prints out status to the logs, then exits the program with the current exit code
sub exit_with_status {
	if (0 == $exit_code) {
		syslog_msg("$run_string: completed successfully");
		log_msg   ("$run_string: completed successfully", 2);
		exit ($exit_code);
		
	} elsif (1 == $exit_code) {
		syslog_err("$run_string: completed, but with some errors");
		log_err   ("$run_string: completed, but with some errors", 2);
		exit ($exit_code);
		
	} elsif (2 == $exit_code) {
		syslog_warn("$run_string: completed, but with some warnings");
		log_warn   ("$run_string: completed, but with some warnings", 2);
		exit ($exit_code);
		
	# this should never happen
	} else {
		syslog_err("$run_string: completed, but with no definite status");
		log_err   ("$run_string: completed, but with no definite status", 2);
		exit (1);
	}
}

# accepts no arguments
# returns nothing
#
# exits the program with the status of the config file (e.g., Syntax OK).
# the exit code is 0 for success, 1 for failure (although failure should never happen)
sub exit_configtest {
	# if we're just doing a configtest, exit here with the results
	if (1 == $do_configtest) {
		if (1 == $config_perfect) {
			print "Syntax OK\n";
			exit(0);
			
		# this should never happen, because any errors should have killed the program before now
		} else {
			print "Syntax Error\n";
			exit(1);
		}
	}
}

# accepts no arguments
# prints out error messages since we can't find the config file
# exits with a return code of 1
sub exit_no_config_file {
	# warn that the config file could not be found
	print STDERR "Config file \"$config_file\" does not exist or is not readable.\n";
	if (0 == $do_configtest) {
		syslog_err("Config file \"$config_file\" does not exist or is not readable.");
	}
	
	# if we have the default config from the install, remind the user to create the real config
	if ((-e "$config_file.default") && (! -e "$config_file")) {
		print STDERR "Did you copy $config_file.default to $config_file yet?\n";
	}
	
	# exit showing an error
	exit(1);
}

# accepts a loglevel
# returns 1 if it's valid, 0 otherwise
sub is_valid_loglevel {
	my $value	= shift(@_);
	
	if (!defined($value)) { return (0); }
	
	if ($value =~ m/^\d$/) {
		if (($value >= 1) && ($value <= 5)) {
			return (1);
		}
	}
	
	return (0);
}

# accepts a positive number formatted as string
# returns 1 if it's valid, 0 otherwise
sub is_valid_rsync_numtries {
	my $value   = shift(@_);
	if (!defined($value)) { return (0); }

	if ($value =~ m/^\d+$/) {
		if (($value >= 0)) {
			return (1);
		}
	}
}

# accepts one argument
# checks to see if that argument is set to 1 or 0
# returns 1 on success, 0 on failure
sub is_boolean {
	my $var = shift(@_);
	
	if (!defined($var))		{ return (0); }
	if ($var !~ m/^\d+$/)	{ return (0); }
	
	if (1 == $var)	{ return (1); }
	if (0 == $var)	{ return (1); }
	
	return (0);
}

# accepts string
# returns 1 if it is a comment line (beginning with #)
# returns 0 otherwise
sub is_comment {
	my $str = shift(@_);
	
	if (!defined($str))	{ return (undef); }
	if ($str =~ m/^#/)	{ return (1); }
	return (0);
}

# accepts string
# returns 1 if it is blank, or just pure white space
# returns 0 otherwise
sub is_blank {
	my $str = shift(@_);
	
	if (!defined($str))	{ return (undef); }
	if ($str !~ m/\S/)	{ return (1); }
	return (0);
}

# accepts path
# returns 1 if it's a valid ssh absolute path
# returns 0 otherwise
sub is_ssh_path {
	my $path = shift(@_);
	
	if (!defined($path))				{ return (undef); }
	
	# make sure we don't have leading/trailing spaces
	if ($path =~ m/^\s/)				{ return (undef); }
	if ($path =~ m/\s$/)				{ return (undef); }
	
	# must have user@host:[~]/path syntax for ssh
	if ($path =~ m/^.*?\@.*?:~?\/.*$/)	{ return (1); }
	
	return (0);
}

# accepts path
# returns 1 if it's a valid cwrsync server path (user@host::sharename)
# return 0 otherwise
sub is_cwrsync_path {
	my $path = shift(@_);
	if (!defined($path))		{ return (undef); }
	if ($path =~ m/^[^\/]+::/)	{ return (1); }
	
	return (0);
}

# accepts path
# returns 1 if it's a syntactically valid anonymous rsync path
# returns 0 otherwise
sub is_anon_rsync_path {
	my $path = shift(@_);
	
	if (!defined($path))			{ return (undef); }
	if ($path =~ m/^rsync:\/\/.*$/)	{ return (1); }
	
	return (0);
}

# accepts path
# returns 1 if it's a syntactically valid LVM path
# returns 0 otherwise
sub is_linux_lvm_path {
	my $path = shift(@_);
	
	if (!defined($path))		{ return (undef); }
	if ($path =~ m|^lvm://.*$|)	{ return (1); }
	
	return (0);
}

# accepts proposed list for rsync_short_args
# makes sure that rsync_short_args is in the format '-abcde'
# (not '-a -b' or '-ab c', etc)
# returns 1 if it's OK, or 0 otherwise
sub is_valid_rsync_short_args {
	my $rsync_short_args = shift(@_);
	
	if (!defined($rsync_short_args))			{ return (0); }
	
	# no blank space allowed
	if ($rsync_short_args =~ m/\s/)				{ return (0); }
	
	# first character must be a dash, followed by alphanumeric characters
	if ($rsync_short_args !~ m/^\-{1,1}\w+$/)	{ return (0); }
	
	return (1);
}

# accepts path
# returns 1 if it's a real absolute path that currently exists
# returns 0 otherwise
sub is_real_local_abs_path {
	my $path	= shift(@_);
	
	if (!defined($path)) { return (undef); }
	if (1 == is_valid_local_abs_path($path)) {
		# check for symlinks first, since they might not link to a real file
		if ((-l "$path") or (-e "$path")) {
			return (1);
		}
	}
	
	return (0);
}

# accepts path
# returns 1 if it's a syntactically valid absolute path
# returns 0 otherwise
sub is_valid_local_abs_path {
	my $path	= shift(@_);
	
	if (!defined($path)) { return (undef); }
	if ($path =~ m/^\//) {
		if (0 == is_directory_traversal($path)) {
			 return (1);
		}
	}
	
	return (0);
}

# accepts path
# returns 1 if it's a directory traversal attempt
# returns 0 if it's safe
sub is_directory_traversal {
	my $path = shift(@_);
	
	if (!defined($path)) { return (undef); }
	
	# /..
	if ($path =~ m/\/\.\./) { return (1); }
	
	# ../
	if ($path =~ m/\.\.\//) { return (1); }
	return (0);
}

# accepts path
# returns 1 if it's a file (doesn't have a trailing slash)
# returns 0 otherwise
sub is_file {
	my $path = shift(@_);
	
	if (!defined($path)) { return (undef); }
	
	if ($path !~ m/\/$/o) {
		return (1);
	}
	
	return (0);
}

# accepts path
# returns 1 if it's a directory (has a trailing slash)
# returns 0 otherwise
sub is_directory {
	my $path = shift(@_);
	
	if (!defined($path)) { return (undef); }
	
	if ($path =~ m/\/$/o) {
		return (1);
	}
	
	return (0);
}

# accepts a string with a script file and optional arguments
# returns 1 if it the script file exists, is executable and has absolute path.
# returns 0 otherwise
sub is_valid_script {
	my $full_script	= shift(@_);	# script to run (including args)
	my $script_ref	= shift(@_);	# reference to script file name
	my $script;			# script file (no args)
	my @script_argv;		# all script arguments
	
	# get the base name of the script, not counting any arguments to it
	@script_argv = split(/\s+/, $full_script);
	$script = $script_argv[0];
	$$script_ref = $script;		# Output $script in case caller wants it
	
	# make sure script exists and is executable
	if ( -f "$script" && -x "$script" && is_real_local_abs_path($script)) {
		return 1;
	}
	return 0;
}

# accepts string
# removes trailing slash, returns the string
sub remove_trailing_slash {
	my $str = shift(@_);
	
	# it's not a trailing slash if it's the root filesystem
	if ($str eq '/') { return ($str); }
	# it's not a trailing slash if it's a remote root filesystem
	if ($str =~ m%:/$% ) { return ($str); }
	
	$str =~ s/\/+$//;
	
	return ($str);
}

# accepts string
# returns /. if passed /, returns input otherwise
# this is to work around a bug in some versions of rsync
sub add_slashdot_if_root {
	my $str = shift(@_);
	
	if ($str eq '/') {
		return '/.';
	}
	
	return ($str);
}

# accepts the interval (cmd) to run against
# returns nothing
# calls the appropriate subroutine, depending on whether this is the lowest interval or a higher one
# also calls preexec/postexec scripts if we're working on the lowest interval
#
sub handle_interval {
	my $cmd = shift(@_);
	
	if (!defined($cmd)) { bail('cmd not defined in handle_interval()'); }
	
	my $id_ref = get_interval_data( $cmd );
	
	my $result = 0;
	
	# here we used to check for interval.delete directories.  This was
	# removed when we switched to using _delete.$$ directories.  This
	# was done so that you can run another (eg) rsnapshot hourly, while
	# the .delete directory from the previous hourly backup was still
	# going.  Potentially you may have several parallel deletes going on
	# with the new scheme, but I'm pretty sure that you'll catch up
	# eventually and not hopelessly wedge the machine -- DRC
	
	# handle toggling between sync_first being enabled and disabled
	
	# link_dest is enabled
	if (1 == $link_dest) {
		
		# sync_first is enabled
		if ($config_vars{'sync_first'}) {
			
			# create the sync root if it doesn't exist (and we need it right now)
			if ($cmd eq 'sync') {
				# don't create the .sync directory, it gets created later on
			}
				
		# sync_first is disabled
		} else {
			# if the sync directory is still here after sync_first is disabled, delete it
			if ( -d "$config_vars{'snapshot_root'}/.sync" ) {
				
				display_rm_rf("$config_vars{'snapshot_root'}/.sync/");
				if (0 == $test) {
					$result = rm_rf( "$config_vars{'snapshot_root'}/.sync/" );
					if (0 == $result) {
						bail("Error! rm_rf(\"$config_vars{'snapshot_root'}/.sync/\")");
					}
				}
			}
		}
		
	# link_dest is disabled
	} else {
		
		# sync_first is enabled
		if ($config_vars{'sync_first'}) {
			# create the sync root if it doesn't exist
			if ( ! -d "$config_vars{'snapshot_root'}/.sync" ) {
				
				# If .sync does not exist but lowest.0 does, then copy that.
				
				# call generic cp_al() subroutine
				my $interval_0	= "$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".0";
				my $sync_dir	= "$config_vars{'snapshot_root'}/.sync";
				
				if ( -d $interval_0 ) {
					display_cp_al( "$interval_0", "$sync_dir" );
					if (0 == $test) {
						$result = cp_al( "$interval_0", "$sync_dir" );
						if (! $result) {
							bail("Error! cp_al(\"$interval_0\", \"$sync_dir\")");
						}
					}
				}
			}
			
		# sync_first is disabled
		} else {
			# if the sync directory still exists, delete it
			if ( -d "$config_vars{'snapshot_root'}/.sync" ) {
				display_rm_rf("$config_vars{'snapshot_root'}/.sync/");
				if (0 == $test) {
					$result = rm_rf( "$config_vars{'snapshot_root'}/.sync/" );
					if (0 == $result) {
						bail("Error! rm_rf(\"$config_vars{'snapshot_root'}/.sync/\")");
					}
				}
			}
		}
	}
	
	#
	# now that the preliminaries are out of the way, the main backups happen here
	#
	
	# backup the lowest interval (or sync content to staging area)
	# we're not sure yet going in whether we'll be doing an actual backup, or just rotating snapshots for the lowest interval
	if ((defined($$id_ref{'interval_num'}) && (0 == $$id_ref{'interval_num'})) or ($cmd eq 'sync')) {
		# if we're doing a sync, run the pre/post exec scripts, and do the backup
		if ($cmd eq 'sync') {
			exec_cmd_preexec();
			backup_lowest_interval( $id_ref );
			exec_cmd_postexec();
			
		# if we're working on the lowest interval, either run the backup and rotate the snapshots, or just rotate them
		# (depending on whether sync_first is enabled
		} else {
			if ($config_vars{'sync_first'}) {
				rotate_lowest_snapshots( $$id_ref{'interval'} );
			} else {
				exec_cmd_preexec();
				rotate_lowest_snapshots( $$id_ref{'interval'} );
				backup_lowest_interval( $id_ref );
				exec_cmd_postexec();
			}
		}
		
	# just rotate the higher intervals
	} else {
		# this is not the most frequent unit, just rotate
		rotate_higher_interval( $id_ref );
	}
	
	# if use_lazy_delete is on, delete the _delete.$$ directory
	# we just check for the directory, it will have been created or not depending on the value of use_lazy_delete
	if ( -d "$config_vars{'snapshot_root'}/_delete.$$" ) {
		# this is the last thing to do here, and it can take quite a while.
		# we remove the lockfile here since this delete shouldn't block other rsnapshot jobs from running
		remove_lockfile();
		
		# start the delete
		display_rm_rf("$config_vars{'snapshot_root'}/_delete.$$");
		if (0 == $test) {
			my $result = rm_rf( "$config_vars{'snapshot_root'}/_delete.$$" );
			if (0 == $result) {
				bail("Error! rm_rf(\"$config_vars{'snapshot_root'}/_delete.$$\")\n");
			}
		}
	} else {
		print_msg("No directory to delete: $config_vars{'snapshot_root'}/_delete.$$", 5);
	}
}

# accepts an interval_data_ref
# acts on the interval defined as $$id_ref{'interval'} (e.g., hourly)
# this should be the smallest interval (e.g., hourly, not daily)
#
# rotates older dirs within this interval, hard links .0 to .1,
# and rsync data over to .0
#
# does not return a value, it bails instantly if there's a problem
sub backup_lowest_interval {
	my $id_ref = shift(@_);
	
	# this should never happen
	if (!defined($id_ref))				{ bail('backup_lowest_interval() expects an argument'); }
	if (!defined($$id_ref{'interval'}))	{ bail('backup_lowest_interval() expects an interval'); }
	
	# this also should never happen
	if ($$id_ref{'interval'} ne 'sync') {
		if (!defined($$id_ref{'interval_num'}) or (0 != $$id_ref{'interval_num'})) {
			bail('backup_lowest_interval() can only operate on the lowest interval');
		}
	}
	
	my $sync_dest_matches	= 0;
	my $sync_dest_dir		= undef;
	
	# if we're trying to sync only certain directories, remember the path to match
	if ($ARGV[1]) {
		$sync_dest_dir = $ARGV[1];
	}
	
	# sync live filesystem data and backup script output to $interval.0
	# loop through each backup point and backup script
	foreach my $bp_ref (@backup_points) {
		
		# rsync the given backup point into the snapshot root
		if ( defined($$bp_ref{'dest'}) && (defined($$bp_ref{'src'}) or defined($$bp_ref{'script'})) ) {
			
			# if we're doing a sync and we specified an parameter on the command line (for the destination path),
			# only sync directories matching the destination path
			if (($$id_ref{'interval'} eq 'sync') && (defined($sync_dest_dir))) {
				my $avail_path	= remove_trailing_slash( $$bp_ref{'dest'} );
				my $req_path	= remove_trailing_slash( $sync_dest_dir );
				
				# if we have a match, sync this entry
				if ($avail_path eq $req_path) {
					# rsync
					if ($$bp_ref{'src'}) {
						rsync_backup_point( $$id_ref{'interval'}, $bp_ref );
						
					# backup_script
					} elsif ($$bp_ref{'script'}) {
						exec_backup_script( $$id_ref{'interval'}, $bp_ref );
					}
					
					# ok, we got at least one dest match
					$sync_dest_matches++;
				}
				
			# this is a normal operation, either a sync or a lowest interval sync/rotate
			} else {
				# rsync
				if ($$bp_ref{'src'}) {
					rsync_backup_point( $$id_ref{'interval'}, $bp_ref );
					
				# backup_script
				} elsif ($$bp_ref{'script'}) {
					exec_backup_script( $$id_ref{'interval'}, $bp_ref );
				}
			}
			
		# this should never happen
		} else {
			bail('invalid backup point data in backup_lowest_interval()');
		}
	}
	
	if ($$id_ref{'interval'} eq 'sync') {
		if (defined($sync_dest_dir) && (0 == $sync_dest_matches)) {
			bail ("No matches found for \"$sync_dest_dir\"");
		}
	}
	
	# rollback failed backups
	rollback_failed_backups( $$id_ref{'interval'} );
	
	# update mtime on $interval.0/ to show when the snapshot completed
	touch_interval_dir( $$id_ref{'interval'} );
}

# accepts $interval
# returns nothing
#
# operates on directories in the given interval (it should be the lowest one)
# deletes the highest numbered directory in the interval, and rotates the ones below it
# if link_dest is enabled, .0 gets moved to .1
# otherwise, we do cp -al .0 .1
#
# if we encounter an error, this script will terminate the program with an error condition
#
sub rotate_lowest_snapshots {
	my $interval = shift(@_);
	
	if (!defined($interval)) { bail('interval not defined in rotate_lowest_snapshots()'); }
	
	my $id_ref = get_interval_data($interval);
	my $interval_num = $$id_ref{'interval_num'};
	my $interval_max = $$id_ref{'interval_max'};
	my $prev_interval = $$id_ref{'prev_interval'};
	my $prev_interval_max = $$id_ref{'prev_interval_max'};
	
	my $result;
	
	# remove oldest directory
	if ( (-d "$config_vars{'snapshot_root'}/$interval.$interval_max") && ($interval_max > 0) ) {
		# if use_lazy_deletes is set move the oldest directory to _delete.$$
		if (1 == $use_lazy_deletes) {
			print_cmd("mv",
				"$config_vars{'snapshot_root'}/$interval.$interval_max/",
				"$config_vars{'snapshot_root'}/_delete.$$/"
			);
			
			if (0 == $test) {
				my $result = safe_rename(
					"$config_vars{'snapshot_root'}/$interval.$interval_max",
					"$config_vars{'snapshot_root'}/_delete.$$"
				);
				if (0 == $result) {
					my $errstr = '';
					$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$interval.$interval_max/\", \"";
					$errstr .= "$config_vars{'snapshot_root'}/_delete.$$/\")";
					bail($errstr);
				}				
			}				
			
		# otherwise the default is to delete the oldest directory for this interval
		} else {
			display_rm_rf("$config_vars{'snapshot_root'}/$interval.$interval_max/");
			
			if (0 == $test) {
				my $result = rm_rf( "$config_vars{'snapshot_root'}/$interval.$interval_max/" );
				if (0 == $result) {
					bail("Error! rm_rf(\"$config_vars{'snapshot_root'}/$interval.$interval_max/\")\n");
				}
			}
		}
	}
	
	# rotate the middle ones
	if ($interval_max > 0) {
		# Have we rotated a directory for this interval?
		my $dir_rotated = 0;
		for (my $i=($interval_max-1); $i>0; $i--) {
			if ( -d "$config_vars{'snapshot_root'}/$interval.$i" ) {
				print_cmd("mv",
					"$config_vars{'snapshot_root'}/$interval.$i/ ",
					"$config_vars{'snapshot_root'}/$interval." . ($i+1) . "/"
				);
				
				if (0 == $test) {
					my $result = safe_rename(
						"$config_vars{'snapshot_root'}/$interval.$i",
						("$config_vars{'snapshot_root'}/$interval." . ($i+1))
					);
					if (0 == $result) {
						my $errstr = '';
						$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$interval.$i/\", \"";
						$errstr .= "$config_vars{'snapshot_root'}/$interval." . ($i+1) . '/' . "\")";
						bail($errstr);
					}
				}
				$dir_rotated = 1;
			} elsif ($dir_rotated) {
				# We have rotated a directory for this interval, but $i
				# does not exist - that probably means a hole.
				print_msg("Note: $config_vars{'snapshot_root'}/$interval.$i missing, cannot rotate it", 4);
			}
		}
	}
	
	# .0 and .1 require more attention, especially now with link_dest and sync_first
	
	# sync_first enabled
	if ($config_vars{'sync_first'}) {
		# we move .0 to .1 no matter what (assuming it exists)
		
		if ( -d "$config_vars{'snapshot_root'}/$interval.0/" ) {
			print_cmd("mv",
				"$config_vars{'snapshot_root'}/$interval.0/",
				"$config_vars{'snapshot_root'}/$interval.1/"
			);
			
			if (0 == $test) {
				my $result = safe_rename(
					"$config_vars{'snapshot_root'}/$interval.0",
					"$config_vars{'snapshot_root'}/$interval.1"
				);
				if (0 == $result) {
					my $errstr = '';
					$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$interval.0/\", \"";
					$errstr .= "$config_vars{'snapshot_root'}/$interval.1/\")";
					bail($errstr);
				}				
			}				
		}				
			
		# if we're using rsync --link-dest, we need to mv sync to .0 now
		if (1 == $link_dest) {
			# mv sync .0
			
			if ( -d "$config_vars{'snapshot_root'}/.sync" ) {
				print_cmd("mv",
					"$config_vars{'snapshot_root'}/.sync/",
					"$config_vars{'snapshot_root'}/$interval.0/"
				);
				
				if (0 == $test) {
					my $result = safe_rename(
						"$config_vars{'snapshot_root'}/.sync",
						"$config_vars{'snapshot_root'}/$interval.0"
					);
					if (0 == $result) {
						my $errstr = '';
						$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/.sync/\", \"";
						$errstr .= "$config_vars{'snapshot_root'}/$interval.0/\")";
						bail($errstr);
					}				
				}				
			}	
			
		# otherwise, we hard link (except for directories, symlinks, and special files) sync to .0
		} else {
			# cp -al .sync .0
			
			if ( -d "$config_vars{'snapshot_root'}/.sync/" ) {
				display_cp_al( "$config_vars{'snapshot_root'}/.sync/", "$config_vars{'snapshot_root'}/$interval.0/" );
				if (0 == $test) {
					$result = cp_al( "$config_vars{'snapshot_root'}/.sync", "$config_vars{'snapshot_root'}/$interval.0" );
					if (! $result) {
						bail("Error! cp_al(\"$config_vars{'snapshot_root'}/.sync\", \"$config_vars{'snapshot_root'}/$interval.0\")");
					}
				}
			}
		}
		
	# sync_first disabled (make sure we have a .0 directory and someplace to put it)
	} elsif ( (-d "$config_vars{'snapshot_root'}/$interval.0") && ($interval_max > 0) ) {
		
		# if we're using rsync --link-dest, we need to mv .0 to .1 now
		if (1 == $link_dest) {
			# move .0 to .1
			
			if ( -d "$config_vars{'snapshot_root'}/$interval.0/" ) {
				print_cmd("mv $config_vars{'snapshot_root'}/$interval.0/ $config_vars{'snapshot_root'}/$interval.1/");
				
				if (0 == $test) {
					my $result = safe_rename(
						"$config_vars{'snapshot_root'}/$interval.0",
						"$config_vars{'snapshot_root'}/$interval.1"
					);
					if (0 == $result) {
						my $errstr = '';
						$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$interval.0/\", ";
						$errstr .= "\"$config_vars{'snapshot_root'}/$interval.1/\")";
						bail($errstr);
					}
				}
			}
		# otherwise, we hard link (except for directories, symlinks, and special files) .0 over to .1
		} else {
			# call generic cp_al() subroutine
			if ( -d "$config_vars{'snapshot_root'}/$interval.0/" ) {
				display_cp_al( "$config_vars{'snapshot_root'}/$interval.0", "$config_vars{'snapshot_root'}/$interval.1" );
				if (0 == $test) {
					$result = cp_al(
						"$config_vars{'snapshot_root'}/$interval.0/",
						"$config_vars{'snapshot_root'}/$interval.1/"
					);
					if (! $result) {
						my $errstr = '';
						$errstr .= "Error! cp_al(\"$config_vars{'snapshot_root'}/$interval.0/\", ";
						$errstr .= "\"$config_vars{'snapshot_root'}/$interval.1/\")";
						bail($errstr);
					}
				}
			}
		}
	}
}

# accepts interval, backup_point_ref, ssh_rsync_args_ref
# returns no args
# runs rsync on the given backup point
# this is only run on the lowest points, not for rotations
sub rsync_backup_point {
	my $interval	= shift(@_);
	my $bp_ref		= shift(@_);
	
	# validate subroutine args
	if (!defined($interval))		{ bail('interval not defined in rsync_backup_point()'); }
	if (!defined($bp_ref))			{ bail('bp_ref not defined in rsync_backup_point()'); }
	if (!defined($$bp_ref{'src'}))	{ bail('src not defined in rsync_backup_point()'); }
	if (!defined($$bp_ref{'dest'}))	{ bail('dest not defined in rsync_backup_point()'); }
	
	# set up default args for rsync and ssh
	my $ssh_args			= $default_ssh_args;
	my $rsync_short_args	= $default_rsync_short_args;
	my $rsync_long_args		= $default_rsync_long_args;
	
	# other misc variables
	my @cmd_stack				= undef;
	my $src						= undef;
	my $result					= undef;
	my $using_relative			= 0;
	
	my $linux_lvm                     = 0;
	my $linux_lvm_oldpwd              = undef;
	my $linux_lvm_snapshotname        = undef;

	if (defined($$bp_ref{'src'})) {
		$src = remove_trailing_slash( "$$bp_ref{'src'}" );
		$src = add_slashdot_if_root( "$src" );
	}
	
	# if we're using link-dest later, that target depends on whether we're doing a 'sync' or a regular interval
	# if we're doing a "sync", then look at [lowest-interval].0 instead of [cur-interval].1
	my $interval_link_dest;
	my $interval_num_link_dest;
	
	# start looking for link_dest targets at interval.$start_num
	my $start_num = 1;
	
	my $sync_dir_was_present = 0;
	
	# if we're doing a sync, we'll start looking at [lowest-interval].0 for a link_dest target
	if ($interval eq 'sync') {
		$start_num = 0;
		
		# remember now if the .sync directory exists
		if ( -d "$config_vars{'snapshot_root'}/.sync" ) {
			$sync_dir_was_present = 1;
		}
	}
	
	# look for the most recent link_dest target directory
	# loop through all snapshots until we find the first match
	foreach my $i_ref (@intervals) {
		if (defined($$i_ref{'number'})) {
			for (my $i = $start_num; $i < $$i_ref{'number'}; $i++) {
				
				# once we find a valid link_dest target, the search is over
				if ( -e "$config_vars{'snapshot_root'}/$$i_ref{'interval'}.$i/$$bp_ref{'dest'}" ) {
					if (!defined($interval_link_dest) && !defined($interval_num_link_dest)) {
						$interval_link_dest		= $$i_ref{'interval'};
						$interval_num_link_dest = $i;
					}
					
					# we'll still loop through the outer loop a few more times, but the defined() check above
					# will make sure the first match wins
					last;
				}
			}
		}
	}
	
	# check to see if this destination path has already failed
	# if it's set to be rolled back, skip out now
	foreach my $rollback_point (@rollback_points) {
		if (defined($rollback_point)) {
			my $tmp_dest			= $$bp_ref{'dest'};
			my $tmp_rollback_point	= $rollback_point;
			
			# don't compare the slashes at the end
			$tmp_dest			= remove_trailing_slash($tmp_dest);
			$tmp_rollback_point	= remove_trailing_slash($tmp_rollback_point);
			
			if ("$tmp_dest" eq "$tmp_rollback_point") {
				print_warn ("$$bp_ref{'src'} skipped due to rollback plan", 2);
				syslog_warn("$$bp_ref{'src'} skipped due to rollback plan");
				return (undef);
			}
		}
	}
	
	# if the config file specified rsync or ssh args, use those instead of the hard-coded defaults in the program
	if (defined($config_vars{'rsync_short_args'})) {
		$rsync_short_args = $config_vars{'rsync_short_args'};
	}
	if (defined($config_vars{'rsync_long_args'})) {
		$rsync_long_args = $config_vars{'rsync_long_args'};
	}
	if (defined($config_vars{'ssh_args'})) {
		$ssh_args = $config_vars{'ssh_args'};
	}
	
	# extra verbose?
	if ($verbose > 3) { $rsync_short_args .= 'v'; }
	
	# split up rsync long args into an array, paying attention to
	# quoting - ideally we'd use Text::Balanced or similar, but that's
	# only relatively recently gone into core
    my @rsync_long_args_stack = split_long_args_with_quotes('rsync_long_args', $rsync_long_args);

    # create $interval.0/$$bp_ref{'dest'} or .sync/$$bp_ref{'dest'} directory if it doesn't exist
	# (this may create the .sync dir, which is why we had to check for it above)
	#
	create_backup_point_dir($interval, $bp_ref);
	
	# check opts, first unique to this backup point, and then global
	#
	# with all these checks, we try the local option first, and if
	# that isn't specified, we attempt to use the global setting as
	# a fallback plan
	#
	# we do the rsync args first since they overwrite the rsync_* variables,
	# whereas the subsequent options append to them
	#
	# RSYNC SHORT ARGS
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'rsync_short_args'}) ) {
		$rsync_short_args = $$bp_ref{'opts'}->{'rsync_short_args'};
	}
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'extra_rsync_short_args'}) ) {
		$rsync_short_args .= ' ' if ($rsync_short_args);
		$rsync_short_args .= $$bp_ref{'opts'}->{'extra_rsync_short_args'};
	}
	# RSYNC LONG ARGS
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'rsync_long_args'}) ) {
		@rsync_long_args_stack = split_long_args_with_quotes('rsync_long_args (for a backup point)', $$bp_ref{'opts'}->{'rsync_long_args'});
	}
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'extra_rsync_long_args'}) ) {
		push(@rsync_long_args_stack, split_long_args_with_quotes('extra_rsync_long_args (for a backup point)', $$bp_ref{'opts'}->{'extra_rsync_long_args'}));
	}
	# SSH ARGS
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'ssh_args'}) ) {
		$ssh_args = $$bp_ref{'opts'}->{'ssh_args'};
	}
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'extra_ssh_args'}) ) {
		$ssh_args .= ' ' . $$bp_ref{'opts'}->{'extra_ssh_args'};
	}
	# ONE_FS
	if ( defined($$bp_ref{'opts'}) && defined($$bp_ref{'opts'}->{'one_fs'}) ) {
		if (1 == $$bp_ref{'opts'}->{'one_fs'}) {
			$rsync_short_args .= 'x';
		}
	} elsif ($one_fs) {
		$rsync_short_args .= 'x';
	}
	
	# SEE WHAT KIND OF SOURCE WE'RE DEALING WITH
	#
	# local filesystem
	if ( is_real_local_abs_path($$bp_ref{'src'}) ) {
		# no change
		
	# if this is a user@host:/path, use ssh
	} elsif ( is_ssh_path($$bp_ref{'src'}) ) {
		
		# if we have any args for SSH, add them
		if ( defined($ssh_args) ) {
			push( @rsync_long_args_stack, "--rsh=\"$config_vars{'cmd_ssh'} $ssh_args\"" );
			
		# no arguments is the default
		} else {
			push( @rsync_long_args_stack, "--rsh=$config_vars{'cmd_ssh'}" );
		}
		
	# anonymous rsync
	} elsif ( is_anon_rsync_path($$bp_ref{'src'}) ) {
		# make rsync quiet if we're running in quiet mode
		if ($verbose < 2) { $rsync_short_args .= 'q'; }
		
	# cwrsync path
	} elsif ( is_cwrsync_path($$bp_ref{'src'}) ) {
		# make rsync quiet if we're running in quiet mode
		if ($verbose < 2) { $rsync_short_args .= 'q'; }
		
	# LVM path
	} elsif ( is_linux_lvm_path($$bp_ref{'src'}) ) {
		# take LVM snapshot and mount, reformat src into local path

        unless (defined($config_vars{'linux_lvm_snapshotsize'})) {
            bail("Missing required argument for LVM source: linux_lvm_snapshotsize");
        }
        unless (defined($config_vars{'linux_lvm_snapshotname'})) {
            bail("Missing required argument for LVM source: linux_lvm_snapshotname");
        }
        unless (defined($config_vars{'linux_lvm_vgpath'})) {
            bail("Missing required argument for LVM source: linux_lvm_vgpath");
        }
        unless (defined($config_vars{'linux_lvm_mountpath'})) {
            bail("Missing required argument for LVM source: linux_lvm_mountpath");
        }

        # parse LVM src ('lvm://vgname/volname/path')
        my ($linux_lvmvgname,$linux_lvmvolname, $linux_lvmpath) = ($$bp_ref{'src'} =~ m|^lvm://([^/]+)/([^/]+)/(.*)$|);
        # lvmvolname and/or path could be the string "0", so test for 'defined':
        unless (defined($linux_lvmvgname) and defined($linux_lvmvolname) and defined($linux_lvmpath)) {
            bail("Could not understand LVM source \"$$bp_ref{'src'}\" in backup_lowest_interval()");
        }
        
        # assemble and execute LVM snapshot command
        @cmd_stack = ();
        push(@cmd_stack, $config_vars{'linux_lvm_cmd_lvcreate'});
        push(@cmd_stack, '--snapshot');

        push(@cmd_stack, '--size');
        push(@cmd_stack, $config_vars{'linux_lvm_snapshotsize'});
        push(@cmd_stack, '--name');
        push(@cmd_stack, $config_vars{'linux_lvm_snapshotname'});

        push(@cmd_stack, join('/', $config_vars{'linux_lvm_vgpath'}, $linux_lvmvgname, $linux_lvmvolname));
        
        print_cmd(@cmd_stack);
        if (0 == $test) {
            # silence gratuitous lvcreate output
            #$result = system(@cmd_stack);
            $result = system(join " ", @cmd_stack, ">/dev/null");
            
            if ($result != 0) {
                bail("Create LVM snapshot failed: $result");
            }
        }
        
        # mount the snapshot
        @cmd_stack = ();
        push(@cmd_stack, $config_vars{'linux_lvm_cmd_mount'});

        $linux_lvm_snapshotname = join('/', $config_vars{'linux_lvm_vgpath'}, $linux_lvmvgname, $config_vars{'linux_lvm_snapshotname'});
        push(@cmd_stack, $linux_lvm_snapshotname);
        push(@cmd_stack, $config_vars{'linux_lvm_mountpath'});
        
        print_cmd(@cmd_stack);
        if (0 == $test) {
            $result = system(@cmd_stack);
            
            if ($result != 0) {
                bail("Mount LVM snapshot failed: $result");
            }
        }
        
        
        # rewrite src to point to mount path
        # - to avoid including the mountpath in the snapshot, change the working directory and use a relative source
        $linux_lvm_oldpwd = $ENV{PWD};
        print_cmd("chdir($config_vars{'linux_lvm_mountpath'})");
        if (0 == $test) {
            $result = chdir($config_vars{'linux_lvm_mountpath'});
            if (0 == $result) {
            bail("Could not change directory to \"$config_vars{'linux_lvm_mountpath'}\"");
            }
        }

        $$bp_ref{'src'} = './' .  $linux_lvmpath;
        $linux_lvm = 1;
		
	# this should have already been validated once, but better safe than sorry
	} else {
		bail("Could not understand source \"$$bp_ref{'src'}\" in backup_lowest_interval()");
	}
	
	# if we're using --link-dest, we'll need to specify the link-dest directory target
	# this varies depending on whether we're operating on the lowest interval or doing a 'sync'
	if (1 == $link_dest) {
		# bp_ref{'dest'} and snapshot_root have already been validated, but these might be blank
		if (defined($interval_link_dest) && defined($interval_num_link_dest)) {
			
			# make sure the directory exists
			if ( -d "$config_vars{'snapshot_root'}/$interval_link_dest.$interval_num_link_dest/$$bp_ref{'dest'}" ) {
				
				# we don't use link_dest if we already synced once to this directory
				if (0 && $sync_dir_was_present) { # always false
					
					# skip --link-dest, this is the second time the sync has been run, because the .sync directory already exists
					
				# default: push link_dest arguments onto cmd stack
				} else {
					push(
						@rsync_long_args_stack,
						"--link-dest=$config_vars{'snapshot_root'}/$interval_link_dest.$interval_num_link_dest/$$bp_ref{'dest'}"
					);
				}
			}
		}
	}
	
	# SPECIAL EXCEPTION:
	#   If we're using --link-dest AND the source is a file AND we have a copy from the last time,
	#   manually link interval.1/foo to interval.0/foo
	#
	#   This is necessary because --link-dest only works on directories
	#
	if (
		(1 == $link_dest) &&
		(is_file($$bp_ref{'src'})) &&
		defined($interval_link_dest) &&
		defined($interval_num_link_dest) &&
		(-f "$config_vars{'snapshot_root'}/$interval_link_dest.$interval_num_link_dest/$$bp_ref{'dest'}")
	) {
		
		# these are both "destination" paths, but we're moving from .1 to .0
		my $srcpath;
		my $destpath;
		
		$srcpath = "$config_vars{'snapshot_root'}/$interval_link_dest.$interval_num_link_dest/$$bp_ref{'dest'}";
		
		if ($interval eq 'sync') {
			$destpath = "$config_vars{'snapshot_root'}/.sync/$$bp_ref{'dest'}";
		} else {
			$destpath = "$config_vars{'snapshot_root'}/$interval.0/$$bp_ref{'dest'}";
		}
		
		print_cmd("ln $srcpath $destpath");
		
		if (0 == $test) {
			$result = link( "$srcpath", "$destpath" );
			
			if (!defined($result) or (0 == $result)) {
				print_err ("link(\"$srcpath\", \"$destpath\") failed", 2);
				syslog_err("link(\"$srcpath\", \"$destpath\") failed");
			}
		}
	}
	
	# figure out if we're using the --relative flag to rsync.
	# this influences how the source paths are constructed below.
	foreach my $rsync_long_arg (@rsync_long_args_stack) {
		if (defined($rsync_long_arg)) {
			if ('--relative' eq $rsync_long_arg) {
				$using_relative = 1;
			}
		}
	}
	
	if (defined($$bp_ref{'src'})) {
		# make sure that the source path doesn't have a trailing slash if we're using the --relative flag
		# this is to work around a bug in most versions of rsync that don't properly delete entries
		# when the --relative flag is set.
		#
		if (1 == $using_relative) {
			$src = remove_trailing_slash( "$$bp_ref{'src'}" );
			$src = add_slashdot_if_root( "$src" );
			
		# no matter what, we need a source path
		} else {
			# put a trailing slash on it if we know it's a directory and it doesn't have one
			if ((-d "$$bp_ref{'src'}") && ($$bp_ref{'src'} !~ /\/$/)) {
				$src = $$bp_ref{'src'} . '/';
				
			# just use it as-is
			} else {
				$src = $$bp_ref{'src'};
			}
		}
	}
	
	# BEGIN RSYNC COMMAND ASSEMBLY
	#   take care not to introduce blank elements into the array,
	#   since it can confuse rsync, which in turn causes strange errors
	#
	@cmd_stack = ();
	#
	# rsync command
	push(@cmd_stack, $config_vars{'cmd_rsync'});
	#
	# rsync short args
	if (defined($rsync_short_args) && ($rsync_short_args ne '')) {
		push(@cmd_stack, $rsync_short_args);
	}
	#
	# rsync long args
	if (@rsync_long_args_stack && (scalar(@rsync_long_args_stack) > 0)) {
		foreach my $tmp_long_arg (@rsync_long_args_stack) {
			if (defined($tmp_long_arg) && ($tmp_long_arg ne '')) {
				push(@cmd_stack, $tmp_long_arg);
			}
		}
	}
	#
	# src
	push(@cmd_stack, "$src");
	#
	# dest
	if ($interval eq 'sync') {
		push(@cmd_stack, "$config_vars{'snapshot_root'}/.sync/$$bp_ref{'dest'}");
	} else {
		push(@cmd_stack, "$config_vars{'snapshot_root'}/$interval.0/$$bp_ref{'dest'}");
	}
	#
	# END RSYNC COMMAND ASSEMBLY
	
	
	# RUN THE RSYNC COMMAND FOR THIS BACKUP POINT BASED ON THE @cmd_stack VARS
	print_cmd(@cmd_stack);
	

	my $tryCount = 0;
	$result = 1;
	if (0 == $test) {
		while ($tryCount < $rsync_numtries && $result !=0) {
			# join is Michael Ashley's fix for some filter/space problems		
			$result = system(join(' ', @cmd_stack));
			$tryCount += 1;
		}

		# now we see if rsync ran successfully, and what to do about it
		if ($result != 0) {
			# bitmask return value
			my $retval = get_retval($result);
			
			# print warnings, and set this backup point to rollback if we're using --link-dest
			#
			handle_rsync_error($retval, $bp_ref);
		} else {
			print_msg("rsync succeeded", 5);
		}
	}
	
	# unmount and drop snapshot if required
	if ($linux_lvm) {
	
        print_cmd("chdir($linux_lvm_oldpwd)");
        if (0 == $test) {
            $result = chdir($linux_lvm_oldpwd);
            if (0 == $result) {
            bail("Could not change directory to \"$linux_lvm_oldpwd\"");
            }
        }

        @cmd_stack = ();
        push(@cmd_stack, $config_vars{'linux_lvm_cmd_umount'});

        push(@cmd_stack, $config_vars{'linux_lvm_mountpath'});
        
        print_cmd(@cmd_stack);
        if (0 == $test) {
            # silence gratuitous lvremove output
            #$result = system(@cmd_stack);
            $result = system(join " ", @cmd_stack, ">/dev/null");
            
            if ($result != 0) {
                bail("Unmount LVM snapshot failed: $result");
            }
        }

        @cmd_stack = ();
        push(@cmd_stack, $config_vars{'linux_lvm_cmd_lvremove'});

        push(@cmd_stack, '--force');
        push(@cmd_stack, $linux_lvm_snapshotname);
        
        print_cmd(@cmd_stack);
        if (0 == $test) {
            $result = system(@cmd_stack);
            
            if ($result != 0) {
                bail("Removal of LVM snapshot failed: $result");
            }
        }
    }
}

# accepts the name of the argument to split, and its value
# the name is used for spitting out error messages
#
# returns a list
sub split_long_args_with_quotes {
    my($argname, $argvalue) = @_;
    my $inquotes = '';
	my @stack = ('');
	for(my $i = 0; $i < length($argvalue); $i++) {
        my $thischar = substr($argvalue, $i, 1);
	    # got whitespace and not in quotes? end this argument, start next
	    if($thischar =~ /\s/ && !$inquotes) {
		$#stack++;
	        next;
            # not in quotes and got a quote? remember that we're in quotes
            } elsif($thischar =~ /['"]/ && !$inquotes) {
	        $inquotes = $thischar;
            # in quotes and got a different quote? no nesting allowed
            } elsif($thischar =~ /['"]/ && $inquotes ne $thischar) {
	        print_err("Nested quotes not allowed in $argname", 1);
	        syslog_err("Nested quotes not allowed in $argname");
		exit(1);
        # in quotes and got a close quote
	    } elsif($thischar eq $inquotes) {
	        $inquotes = '';
            }
	    $stack[-1] .= $thischar;
	}
	if($inquotes) {
	    print_err("Unbalanced quotes in $argname", 1);
	    syslog_err("Unbalanced quotes in $argname");
	    exit(1);
	}
	return @stack;
}

# accepts rsync exit code, backup_point_ref
# prints out an appropriate error message (and logs it)
# also adds destination path to the rollback queue if link_dest is enabled
sub handle_rsync_error {
	my $retval	= shift(@_);
	my $bp_ref	= shift(@_);
	
	# shouldn't ever happen
	if (!defined($retval)) { bail('retval undefined in handle_rsync_error()'); }
	if (0 == $retval) { bail('retval == 0 in handle_rsync_error()'); }
	if (!defined($bp_ref)) { bail('bp_ref undefined in handle_rsync_error()'); }
	
	# a partial list of rsync exit values (from the rsync 2.6.0 man page)
	#
	# 0		Success
	# 1		Syntax or usage error
	# 23	Partial transfer due to error
	# 24	Partial transfer due to vanished source files
	#
	# if we got error 1 and we were attempting --link-dest, there's
	# a very good chance that this version of rsync is too old.
	#
	if ((1 == $link_dest) && (1 == $retval)) {
		print_err ("$config_vars{'cmd_rsync'} syntax or usage error. Does this version of rsync support --link-dest?", 2);
		syslog_err("$config_vars{'cmd_rsync'} syntax or usage error. Does this version of rsync support --link-dest?");
		
	# 23 and 24 are treated as warnings because users might be using the filesystem during the backup
	# if you want perfect backups, don't allow the source to be modified while the backups are running :)
	} elsif (23 == $retval) {
		print_warn ("Some files and/or directories in $$bp_ref{'src'} only transferred partially during rsync operation", 4);
		syslog_warn("Some files and/or directories in $$bp_ref{'src'} only transferred partially during rsync operation");
		
	} elsif (24 == $retval) {
		print_warn ("Some files and/or directories in $$bp_ref{'src'} vanished during rsync operation", 4);
		syslog_warn("Some files and/or directories in $$bp_ref{'src'} vanished during rsync operation");
		
	# other error
	} else {
		print_err ("$config_vars{'cmd_rsync'} returned $retval while processing $$bp_ref{'src'}", 2);
		syslog_err("$config_vars{'cmd_rsync'} returned $retval while processing $$bp_ref{'src'}");
		
		# set this directory to rollback if we're using link_dest
		# (since $interval.0/ will have been moved to $interval.1/ by now)
		if (1 == $link_dest) {
			push(@rollback_points, $$bp_ref{'dest'});
		}
	}
}

# accepts interval, backup_point_ref, ssh_rsync_args_ref
# returns no args
# runs rsync on the given backup point
sub exec_backup_script {
	my $interval	= shift(@_);
	my $bp_ref		= shift(@_);
	
	# validate subroutine args
	if (!defined($interval))	{ bail('interval not defined in exec_backup_script()'); }
	if (!defined($bp_ref))		{ bail('bp_ref not defined in exec_backup_script()'); }
	
	# other misc variables
	my $script	= undef;
	my $tmpdir	= undef;
	my $result	= undef;
	
	# remember what directory we started in
	my $cwd = cwd();
	
	# create $interval.0/$$bp_ref{'dest'} directory if it doesn't exist
	#
	create_backup_point_dir($interval, $bp_ref);
	
	# work in a temp dir, and make this the source for the rsync operation later
	# not having a trailing slash is a subtle distinction. it allows us to use
	# the same path if it's NOT a directory when we try to delete it.
	$tmpdir = "$config_vars{'snapshot_root'}/tmp";
	
	# remove the tmp directory if it's still there for some reason
	# (this shouldn't happen unless the program was killed prematurely, etc)
	if ( -e "$tmpdir" ) {
		display_rm_rf("$tmpdir/");
		
		if (0 == $test) {
			$result = rm_rf("$tmpdir/");
			if (0 == $result) {
				bail("Could not rm_rf(\"$tmpdir/\");");
			}
		}
	}
	
	# create the tmp directory
	print_cmd("mkdir -m 0755 -p $tmpdir/");
	
	if (0 == $test) {
		eval {
			# don't ever pass a trailing slash to mkpath
			mkpath( "$tmpdir", 0, 0755 );
		};
		if ($@) {
			bail("Unable to create \"$tmpdir/\",\nPlease make sure you have the right permissions.");
		}
	}
	
	# no more calls to mkpath here. the tmp dir needs a trailing slash
	$tmpdir .= '/';
	
	# change to the tmp directory
	print_cmd("cd $tmpdir");
	
	if (0 == $test) {
		$result = chdir("$tmpdir");
		if (0 == $result) {
			bail("Could not change directory to \"$tmpdir\"");
		}
	}
	
	# run the backup script
	#
	# the assumption here is that the backup script is written in such a way
	# that it creates files in its current working directory.
	#
	# the backup script should return 0 on success, anything else is
	# considered a failure.
	#
	print_cmd($$bp_ref{'script'});
	
	if (0 == $test) {
		$result = system( $$bp_ref{'script'} );
		if ($result != 0) {
			# bitmask return value
			my $retval = get_retval($result);
			
			print_err ("backup_script $$bp_ref{'script'} returned $retval", 2);
			syslog_err("backup_script $$bp_ref{'script'} returned $retval");
			
			# if the backup script failed, roll back to the last good data
			push(@rollback_points, $$bp_ref{'dest'} );
		}
	}
	
	# change back to the previous directory
	# (/ is a special case)
	if ('/' eq $cwd) {
		print_cmd("cd $cwd");
	} else {
		print_cmd("cd $cwd/");
	}
	
	if (0 == $test) {
		chdir($cwd);
	}
	
	# if we're using link_dest, pull back the previous files (as links) that were moved up if any.
	# this is because in this situation, .0 will always be empty, so we'll pull select things
	# from .1 back to .0 if possible. these will be used as a baseline for diff comparisons by
	# sync_if_different() down below.
	if (1 == $link_dest) {
		my $lastdir;
		my $curdir;
		
		if ($interval eq 'sync') {
			$lastdir	= "$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".0/$$bp_ref{'dest'}";
			$curdir		= "$config_vars{'snapshot_root'}/.sync/$$bp_ref{'dest'}";
		} else {
			$lastdir	= "$config_vars{'snapshot_root'}/$interval.1/$$bp_ref{'dest'}";
			$curdir		= "$config_vars{'snapshot_root'}/$interval.0/$$bp_ref{'dest'}";
		}
		
		# make sure we have a slash at the end
		if ($lastdir !~ m/\/$/) {
			$lastdir .= '/';
		}
		if ($curdir !~ m/\/$/) {
			$curdir .= '/';
		}
		
		# if we even have files from last time
		if ( -e "$lastdir" ) {
			
			# and we're not somehow clobbering an existing directory (shouldn't happen)
			if ( ! -e "$curdir" ) {
				
				# call generic cp_al() subroutine
				display_cp_al( "$lastdir", "$curdir" );
				if (0 == $test) {
					$result = cp_al( "$lastdir", "$curdir" );
					if (! $result) {
						print_err("Warning! cp_al(\"$lastdir\", \"$curdir/\")", 2);
					}
				}
			}
		}
	}
	
	# sync the output of the backup script into this snapshot interval
	# this is using a native function since rsync doesn't quite do what we want
	#
	# rsync doesn't work here because it sees that the timestamps are different, and
	# insists on changing things even if the files are bit for bit identical on content.
	#
	# check to see where we're syncing to
	my $target_dir;
	if ($interval eq 'sync') {
		$target_dir = "$config_vars{'snapshot_root'}/.sync/$$bp_ref{'dest'}";
	} else {
		$target_dir = "$config_vars{'snapshot_root'}/$interval.0/$$bp_ref{'dest'}";
	}
	
	print_cmd("sync_if_different(\"$tmpdir\", \"$target_dir\")");
	
	if (0 == $test) {
		$result = sync_if_different("$tmpdir", "$target_dir");
		if (!defined($result)) {
			print_err("Warning! sync_if_different(\"$tmpdir\", \"$$bp_ref{'dest'}\") returned undef", 2);
		}
	}
	
	# remove the tmp directory
	if ( -e "$tmpdir" ) {
		display_rm_rf("$tmpdir");
		
		if (0 == $test) {
			$result = rm_rf("$tmpdir");
			if (0 == $result) {
				bail("Could not rm_rf(\"$tmpdir\");");
			}
		}
	}
}

# accepts and runs an arbitrary command string
# returns the exit value of the command
sub exec_cmd {
	my $cmd = shift(@_);
	
	my $return = 0;
	my $retval = 0;
	
	if (!defined($cmd) or ('' eq $cmd)) {
		print_err("Warning! Command \"$cmd\" not found", 2);
		return (undef);
	}
	
	print_cmd($cmd);
	if (0 == $test) {
		$return = system($cmd);
		if (!defined($return)) {
			print_err("Warning! exec_cmd(\"$cmd\") returned undef", 2);
		}
		
		# bitmask to get the real return value
		$retval = get_retval($return);
	}
	
	return ($retval);
}

# accepts no arguments
# returns the exit code of the defined preexec script, or undef if the command is not found
sub exec_cmd_preexec {
	my $retval = 0;
	
	# exec_cmd will only run if we're not in test mode
	if (defined($config_vars{'cmd_preexec'})) {
		$retval = exec_cmd( "$config_vars{'cmd_preexec'}" );
	}
	
	if (!defined($retval)) {
		print_err("$config_vars{'cmd_preexec'} not found", 2);
	}
	
	if (0 != $retval) {
		print_warn("cmd_preexec \"$config_vars{'cmd_preexec'}\" returned $retval", 2);
	}
	
	return ($retval);
}

# accepts no arguments
# returns the exit code of the defined preexec script, or undef if the command is not found
sub exec_cmd_postexec {
	my $retval = 0;
	
	# exec_cmd will only run if we're not in test mode
	if (defined($config_vars{'cmd_postexec'})) {
		$retval = exec_cmd( "$config_vars{'cmd_postexec'}" );
	}
	
	if (!defined($retval)) {
		print_err("$config_vars{'cmd_postexec'} not found", 2);
	}
	
	if (0 != $retval) {
		print_warn("cmd_postexec \"$config_vars{'cmd_postexec'}\" returned $retval", 2);
	}
	
	return ($retval);
}

# accepts interval, backup_point_ref
# returns nothing
# exits the program if it encounters a fatal error
sub create_backup_point_dir {
	my $interval	= shift(@_);
	my $bp_ref		= shift(@_);
	
	# validate subroutine args
	if (!defined($interval))	{ bail('interval not defined in create_interval_0()'); }
	if (!defined($bp_ref))		{ bail('bp_ref not defined in create_interval_0()'); }
	
	# create missing parent directories inside the $interval.x directory
	my @dirs = split(/\//, $$bp_ref{'dest'});
	pop(@dirs);
	
	# don't mkdir for dest unless we have to
	my $destpath;
	if ($interval eq 'sync') {
		$destpath = "$config_vars{'snapshot_root'}/.sync/" . join('/', @dirs);
	} else {
		$destpath = "$config_vars{'snapshot_root'}/$interval.0/" . join('/', @dirs);
	}
	
	# make sure we DON'T have a trailing slash (for mkpath)
	if ($destpath =~ m/\/$/) {
		$destpath = remove_trailing_slash($destpath);
	}

        # remove any backslash escaping spaces, leave mkpath do the job
        $destpath =~ s/\\ +//;

	# create the directory if it doesn't exist
	if ( ! -e "$destpath" ) {
		print_cmd("mkdir -m 0755 -p $destpath/");
		
		if (0 == $test) {
			eval {
				mkpath( "$destpath", 0, 0755 );
			};
			if ($@) {
				bail("Could not mkpath(\"$destpath/\", 0, 0755);");
			}
		}
	}
}

# accepts interval we're operating on
# returns nothing important
# rolls back failed backups, as defined in the @rollback_points array
# this is necessary if we're using link_dest, since it moves the .0 to .1 directory,
# instead of recursively copying links to the files. it also helps with failed
# backup scripts.
#
sub rollback_failed_backups {
	my $interval = shift(@_);
	
	if (!defined($interval)) { bail('interval not defined in rollback_failed_backups()'); }
	
	my $result;
	my $rsync_short_args	= $default_rsync_short_args;
	
	# handle 'sync' case
	my $interval_src;
	my $interval_dest;
	
	if ($interval eq 'sync') {
		$interval_src	= $intervals[0]->{'interval'} . '.0';
		$interval_dest	= '.sync';
	} else {
		$interval_src	= "$interval.1";
		$interval_dest	= "$interval.0";
	}
	
	# extra verbose?
	if ($verbose > 3) { $rsync_short_args .= 'v'; }
	
	# rollback failed backups (if we're using link_dest)
	foreach my $rollback_point (@rollback_points) {
		# make sure there's something to rollback from
		if ( ! -e "$config_vars{'snapshot_root'}/$interval_src/$rollback_point" ) {
			next;
		}
	
		print_warn ("Rolling back \"$rollback_point\"", 2);
		syslog_warn("Rolling back \"$rollback_point\"");
		
		# using link_dest, this probably won't happen
		# just in case, we may have to delete the old backup point from interval.0 / .sync
		if ( -e "$config_vars{'snapshot_root'}/$interval_dest/$rollback_point" ) {
			display_rm_rf("$config_vars{'snapshot_root'}/$interval_dest/$rollback_point");
			if (0 == $test) {
				$result = rm_rf( "$config_vars{'snapshot_root'}/$interval_dest/$rollback_point" );
				if (0 == $result) {
					bail("Error! rm_rf(\"$config_vars{'snapshot_root'}/$interval_dest/$rollback_point\")\n");
				}
			}
		}
		
		# copy hard links back from .1 to .0
		# this will re-populate the .0 directory without taking up (much) additional space
		#
		# if we're doing a 'sync', then instead of .1 and .0, it's lowest.0 and .sync
		display_cp_al(
			"$config_vars{'snapshot_root'}/$interval_src/$rollback_point",
			"$config_vars{'snapshot_root'}/$interval_dest/$rollback_point"
		);
		if (0 == $test) {
			$result = cp_al(
				"$config_vars{'snapshot_root'}/$interval_src/$rollback_point",
				"$config_vars{'snapshot_root'}/$interval_dest/$rollback_point"
			);
			if (! $result) {
				my $errstr = '';
				$errstr .= "Error! cp_al(\"$config_vars{'snapshot_root'}/$interval_src/$rollback_point\", ";
				$errstr .= "\"$config_vars{'snapshot_root'}/$interval_dest/$rollback_point\")";
				bail($errstr);
			}
		}
	}
}

# accepts interval
# returns nothing
# updates mtime on $interval.0
sub touch_interval_dir {
	my $interval = shift(@_);
	
	if (!defined($interval)) { bail('interval not defined in touch_interval()'); }
	
	my $interval_dir;
	
	if ($interval eq 'sync') {
		$interval_dir = '.sync';
	} else {
		$interval_dir = $interval . '.0';
	}
	
	# update mtime of $interval.0 to reflect the time this snapshot was taken
	print_cmd("touch $config_vars{'snapshot_root'}/$interval_dir/");
	
	if (0 == $test) {
		my $result = utime(time(), time(), "$config_vars{'snapshot_root'}/$interval_dir/");
		if (0 == $result) {
			bail("Could not utime(time(), time(), \"$config_vars{'snapshot_root'}/$interval_dir/\");");
		}
	}
}

# accepts an interval_data_ref
# looks at $$id_ref{'interval'} as the interval to act on,
# and the previous interval $$id_ref{'prev_interval'} to pull up the directory from (e.g., daily, hourly)
# the interval being acted upon should not be the lowest one.
#
# rotates older dirs within this interval, and hard links
# the previous interval's highest numbered dir to this interval's .0,
#
# does not return a value, it bails instantly if there's a problem
sub rotate_higher_interval {
	my $id_ref = shift(@_);
	
	# this should never happen
	if (!defined($id_ref)) { bail('rotate_higher_interval() expects an interval_data_ref'); }
	
	# this also should never happen
	if (!defined($$id_ref{'interval_num'}) or (0 == $$id_ref{'interval_num'})) {
		bail('rotate_higher_interval() can only operate on the higher intervals');
	}
	
	# set up variables for convenience since we refer to them extensively
	my $interval			= $$id_ref{'interval'};
	my $interval_num		= $$id_ref{'interval_num'};
	my $interval_max		= $$id_ref{'interval_max'};
	my $prev_interval		= $$id_ref{'prev_interval'};
	my $prev_interval_max	= $$id_ref{'prev_interval_max'};
	
	# ROTATE DIRECTORIES
	#
	# delete the oldest one (if we're keeping more than one)
	if ( -d "$config_vars{'snapshot_root'}/$interval.$interval_max" ) {
		# if use_lazy_deletes is set move the oldest directory to _delete.$$
		# otherwise preform the default behavior
		if (1 == $use_lazy_deletes) {
			print_cmd("mv ",
				"$config_vars{'snapshot_root'}/$interval.$interval_max/ ",
				"$config_vars{'snapshot_root'}/_delete.$$/"
			);
			
			if (0 == $test) {
				my $result = safe_rename(
					"$config_vars{'snapshot_root'}/$interval.$interval_max",
					("$config_vars{'snapshot_root'}/_delete.$$")
				);
				if (0 == $result) {
					my $errstr = '';
					$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$interval.$interval_max/\", \"";
					$errstr .= "$config_vars{'snapshot_root'}/_delete.$$/\")";
					bail($errstr);
				}				
			}				
		} else {
			display_rm_rf("$config_vars{'snapshot_root'}/$interval.$interval_max/");
			
			if (0 == $test) {
				my $result = rm_rf( "$config_vars{'snapshot_root'}/$interval.$interval_max/" );
				if (0 == $result) {
					bail("Could not rm_rf(\"$config_vars{'snapshot_root'}/$interval.$interval_max/\");");
				}
			}
		}

	} else {
		print_msg("$config_vars{'snapshot_root'}/$interval.$interval_max not present (yet), nothing to delete", 4);
	}
	
	# rotate the middle ones
	for (my $i=($interval_max-1); $i>=0; $i--) {
		if ( -d "$config_vars{'snapshot_root'}/$interval.$i" ) {
			print_cmd(
				"mv $config_vars{'snapshot_root'}/$interval.$i/ ",
				"$config_vars{'snapshot_root'}/$interval." . ($i+1) . "/"
			);
			
			if (0 == $test) {
				my $result = safe_rename(
					"$config_vars{'snapshot_root'}/$interval.$i",
					("$config_vars{'snapshot_root'}/$interval." . ($i+1))
				);
				if (0 == $result) {
					my $errstr = '';
					$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$interval.$i/\", \"";
					$errstr .= "$config_vars{'snapshot_root'}/$interval." . ($i+1) . '/' . "\")";
					bail($errstr);
				}
			}
		} else {
			print_msg("$config_vars{'snapshot_root'}/$interval.$i not present (yet), nothing to rotate", 4);
		}
	}
	
	# prev.max and interval.0 require more attention
	if ( -d "$config_vars{'snapshot_root'}/$prev_interval.$prev_interval_max" ) {
		my $result;
		
		# if the previous interval has at least 2 snapshots,
		# or if the previous interval isn't the smallest one,
		# move the last one up a level
		if (($prev_interval_max >= 1) or ($interval_num >= 2)) {
			# mv hourly.5 to daily.0 (or whatever intervals we're using)
			print_cmd(
				"mv $config_vars{'snapshot_root'}/$prev_interval.$prev_interval_max/ ",
				"$config_vars{'snapshot_root'}/$interval.0/"
			);
			
			if (0 == $test) {
				$result = safe_rename(
					"$config_vars{'snapshot_root'}/$prev_interval.$prev_interval_max",
					"$config_vars{'snapshot_root'}/$interval.0"
				);
				if (0 == $result) {
					my $errstr = '';
					$errstr .= "Error! safe_rename(\"$config_vars{'snapshot_root'}/$prev_interval.$prev_interval_max/\", ";
					$errstr .= "\"$config_vars{'snapshot_root'}/$interval.0/\")";
					bail($errstr);
				}
			}
		} else {
			print_err("$prev_interval must be above 1 to keep snapshots at the $interval level", 1);
			exit(1);
		}
	} else {
		print_msg("$config_vars{'snapshot_root'}/$prev_interval.$prev_interval_max not present (yet), nothing to copy", 3);
	}
}

# accepts src, dest
# prints out the cp -al command that would be run, based on config file data
sub display_cp_al {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	
	# remove trailing slashes (for newer versions of GNU cp)
	$src  = remove_trailing_slash($src);
	$dest = remove_trailing_slash($dest);
	
	if (!defined($src))		{ bail('src not defined in display_cp_al()'); }
	if (!defined($dest))	{ bail('dest not defined in display_cp_al()'); }
	
	if (defined($config_vars{'cmd_cp'})) {
		print_cmd("$config_vars{'cmd_cp'} -al $src $dest");
	} else {
		print_cmd("native_cp_al(\"$src\", \"$dest\")");
	}
}

# stub subroutine
# calls either gnu_cp_al() or native_cp_al()
# returns the value directly from whichever subroutine it calls
# also prints out what's happening to the screen, if appropriate
sub cp_al {
	my $src  = shift(@_);
	my $dest = shift(@_);
	my $result = 0;
	
	# use gnu cp if we have it
	if (defined($config_vars{'cmd_cp'})) {
		$result = gnu_cp_al("$src", "$dest");
		
	# fall back to the built-in native perl replacement, followed by an rsync clean-up step
	} else {
		# native cp -al
		$result = native_cp_al("$src", "$dest");
		if (1 != $result) {
			return ($result);
		}
		
		# rsync clean-up
		$result = rsync_cleanup_after_native_cp_al("$src", "$dest");
	}
	
	return ($result);
}

# this is a wrapper to call the GNU version of "cp"
# it might fail in mysterious ways if you have a different version of "cp"
#
sub gnu_cp_al {
	my $src    = shift(@_);
	my $dest   = shift(@_);
	my $result = 0;
	my $status;
	
	# make sure we were passed two arguments
	if (!defined($src))  { return(0); }
	if (!defined($dest)) { return(0); }
	
	# remove trailing slashes (for newer versions of GNU cp)
	$src  = remove_trailing_slash($src);
	$dest = remove_trailing_slash($dest);
	
	if ( ! -d "$src" ) {
		print_err("gnu_cp_al() needs a valid directory as an argument", 2);
		return (0);
	}
	
	# make the system call to GNU cp
	$result = system( $config_vars{'cmd_cp'}, '-al', "$src", "$dest" );
	if ($result != 0) {
		$status = $result >> 8;
		print_err("$config_vars{'cmd_cp'} -al $src $dest failed (result $result, exit status $status).  Perhaps your cp does not support -al options?", 2);
		return (0);
	}
	
	return (1);
}

# This is a purpose built, native perl replacement for GNU "cp -al".
# However, it is not quite as good. it does not copy "special" files:
# block, char, fifo, or sockets.
# Never the less, it does do regular files, directories, and symlinks
# which should be enough for 95% of the normal cases.
# If you absolutely have to have snapshots of FIFOs, etc, just get GNU
# cp on your system, and specify it in the config file.
#
# Please note that more recently, this subroutine is followed up by
# an rsync clean-up step. This combination effectively removes most of
# the limitations of this technique.
#
# In the great perl tradition, this returns 1 on success, 0 on failure.
#
sub native_cp_al {
	my $src    = shift(@_);
	my $dest   = shift(@_);
	my $dh     = undef;
	my $result = 0;
	
	# make sure we were passed two arguments
	if (!defined($src))  { return(0); }
	if (!defined($dest)) { return(0); }
	
	# make sure we have a source directory
	if ( ! -d "$src" ) {
		print_err("native_cp_al() needs a valid source directory as an argument", 2);
		return (0);
	}
	
	# strip trailing slashes off the directories,
	# since we'll add them back on later
	$src  = remove_trailing_slash($src);
	$dest = remove_trailing_slash($dest);
	
	# LSTAT SRC
	my $st = lstat("$src");
	if (!defined($st)) {
		print_err("Warning! Could not lstat source dir (\"$src\") : $!", 2);
		return(0);
	}
	
	# MKDIR DEST (AND SET MODE)
	if ( ! -d "$dest" ) {
		# print and/or log this if necessary
		if (($verbose > 4) or ($loglevel > 4)) {
			my $cmd_string = "mkdir(\"$dest\", " . get_perms($st->mode) . ")";
		
			if ($verbose > 4) {
				print_cmd($cmd_string);
			} elsif ($loglevel > 4) {
				log_msg($cmd_string, 4);
			}
		}
		
		$result = mkdir("$dest", $st->mode);
		if ( ! $result ) {
			print_err("Warning! Could not mkdir(\"$dest\", $st->mode) : $!", 2);
			return(0);
		}
	}
	
	# CHOWN DEST (if root)
	if (0 == $<) {
		# make sure destination is not a symlink
		if ( ! -l "$dest" ) {
			# print and/or log this if necessary
			if (($verbose > 4) or ($loglevel > 4)) {
				my $cmd_string = "safe_chown(" . $st->uid . ", " . $st->gid . ", \"$dest\")";
			
				if ($verbose > 4) {
					print_cmd($cmd_string);
				} elsif ($loglevel > 4) {
					log_msg($cmd_string, 4);
				}
			}
			
			$result = safe_chown($st->uid, $st->gid, "$dest");
			if (! $result) {
				print_err("Warning! Could not safe_chown(" . $st->uid . ", " . $st->gid . ", \"$dest\");", 2);
				return(0);
			}
		}
	}
	
	# READ DIR CONTENTS
	$dh = new DirHandle( "$src" );
	if (defined($dh)) {
		my @nodes = $dh->read();
		
		# loop through all nodes in this dir
		foreach my $node (@nodes) {
			
			# skip '.' and '..'
			next if ($node =~ m/^\.\.?$/o);
			
			# make sure the node we just got is valid (this is highly unlikely to fail)
			my $st = lstat("$src/$node");
			if (!defined($st)) {
				print_err("Warning! Could not lstat source node (\"$src/$node\") : $!", 2);
				next;
			}
			
			# SYMLINK (must be tested for first, because it will also pass the file and dir tests)
			if ( -l "$src/$node" ) {
				# print and/or log this if necessary
				if (($verbose > 4) or ($loglevel > 4)) {
					my $cmd_string = "copy_symlink(\"$src/$node\", \"$dest/$node\")";
				
					if ($verbose > 4) {
						print_cmd($cmd_string);
					} elsif ($loglevel > 4) {
						log_msg($cmd_string, 4);
					}
				}
				
				$result = copy_symlink("$src/$node", "$dest/$node");
				if (0 == $result) {
					print_err("Warning! copy_symlink(\"$src/$node\", \"$dest/$node\")", 2);
					next;
				}
				
			# FILE
			} elsif ( -f "$src/$node" ) {
				# print and/or log this if necessary
				if (($verbose > 4) or ($loglevel > 4)) {
					my $cmd_string = "link(\"$src/$node\", \"$dest/$node\");";
				
					if ($verbose > 4) {
						print_cmd($cmd_string);
					} elsif ($loglevel > 4) {
						log_msg($cmd_string, 4);
					}
				}
				
				# make a hard link
				$result = link("$src/$node", "$dest/$node");
				if (! $result) {
					print_err("Warning! Could not link(\"$src/$node\", \"$dest/$node\") : $!", 2);
					next;
				}
				
			# DIRECTORY
			} elsif ( -d "$src/$node" ) {
				# print and/or log this if necessary
				if (($verbose > 4) or ($loglevel > 4)) {
					my $cmd_string = "native_cp_al(\"$src/$node\", \"$dest/$node\")";
				
					if ($verbose > 4) {
						print_cmd($cmd_string);
					} elsif ($loglevel > 4) {
						log_msg($cmd_string, 4);
					}
				}
				
				# call this subroutine recursively, to create the directory
				$result = native_cp_al("$src/$node", "$dest/$node");
				if (! $result) {
					print_err("Warning! Recursion error in native_cp_al(\"$src/$node\", \"$dest/$node\")", 2);
					next;
				}
			}
			
			## rsync_cleanup_after_native_cp_al() will take care of the files we can't handle here
			#
			## FIFO
			#} elsif ( -p "$src/$node" ) {
			#	# print_err("Warning! Ignoring FIFO $src/$node", 2);
			#	
			## SOCKET
			#} elsif ( -S "$src/$node" ) {
			#	# print_err("Warning! Ignoring socket: $src/$node", 2);
			#	
			## BLOCK DEVICE
			#} elsif ( -b "$src/$node" ) {
			#	# print_err("Warning! Ignoring special block file: $src/$node", 2);
			#	
			## CHAR DEVICE
			#} elsif ( -c "$src/$node" ) {
			#	# print_err("Warning! Ignoring special character file: $src/$node", 2);
			#}
		}
		
	} else {
		print_err("Could not open \"$src\". Do you have adequate permissions?", 2);
		return(0);
	}
	
	# close open dir handle
	if (defined($dh)) { $dh->close(); }
	undef( $dh );
	
	# UTIME DEST
	# print and/or log this if necessary
	if (($verbose > 4) or ($loglevel > 4)) {
		my $cmd_string = "utime(" . $st->atime . ", " . $st->mtime . ", \"$dest\");";
	
		if ($verbose > 4) {
			print_cmd($cmd_string);
		} elsif ($loglevel > 4) {
			log_msg($cmd_string, 4);
		}
	}
	$result = utime($st->atime, $st->mtime, "$dest");
	if (! $result) {
		print_err("Warning! Could not set utime(" . $st->atime . ", " . $st->mtime . ", \"$dest\") : $!", 2);
		return(0);
	}
	
	return (1);
}

# If we're using native_cp_al(), it can't transfer special files.
# So, to make sure no one misses out, this subroutine gets called every time directly
# after native_cp_al(), with the same source and destinations paths.
#
# Essentially it is running between two almost identical hard linked directory trees.
# However, it will transfer over the few (if any) special files that were otherwise
# missed.
#
# This subroutine specifies its own parameters for rsync's arguments. This is to make
# sure that nothing goes wrong, since there is not much here that should be left to
# interpretation.
#
sub rsync_cleanup_after_native_cp_al {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	
	my $local_rsync_short_args = '-a';
        # if the user asked for -E, we should use it here too.
        # should we check for OS X?  Dunno, but for now that extra
        # check is in here as we know we need it there, and so
        # this is the smallest change for the smallest number of
        # people
        $local_rsync_short_args .= 'E' if(
             defined($config_vars{'rsync_short_args'}) &&
             $config_vars{'rsync_short_args'} =~ /E/ &&
             $^O eq 'darwin'
        );

	my @cmd_stack = ();
	
	# make sure we were passed two arguments
	if (!defined($src))  { return(0); }
	if (!defined($dest)) { return(0); }
	
	# make sure this is directory to directory
	if (($src !~ m/\/$/o) or ($dest !~ m/\/$/o)) {
		print_err("rsync_cleanup_after_native_cp_al() only works on directories", 2);
		return (0);
	}
	
	# make sure we have a source directory
	if ( ! -d "$src" ) {
		print_err("rsync_cleanup_after_native_cp_al() needs a valid source directory as an argument", 2);
		return (0);
	}
	# make sure we have a destination directory
	if ( ! -d "$dest" ) {
		print_err("rsync_cleanup_after_native_cp_al() needs a valid destination directory as an argument", 2);
		return (0);
	}
	
	# check verbose settings and modify rsync's short args accordingly
	if ($verbose > 3) { $local_rsync_short_args .= 'v'; }
	
	# setup rsync command
	#
	# rsync
	push(@cmd_stack, $config_vars{'cmd_rsync'});
	#
	# short args
	push(@cmd_stack, $local_rsync_short_args);
	#
	# long args (not the defaults)
	push(@cmd_stack, '--delete');
	push(@cmd_stack, '--numeric-ids');
	#
	# src
	push(@cmd_stack, "$src");
	#
	# dest
	push(@cmd_stack, "$dest");
	
	print_cmd(@cmd_stack);
	
	if (0 == $test) {
                # join is Michael Ashley's fix for some filter/space problems
		my $result = system(join(' ', @cmd_stack));
		
		if ($result != 0) {
			# bitmask return value
			my $retval = get_retval($result);
			
			# a partial list of rsync exit values
			# 0		Success
			# 23	Partial transfer due to error
			# 24	Partial transfer due to vanished source files
	
			if (23 == $retval) {
				print_warn ("Some files and/or directories in $src only transferred partially during rsync_cleanup_after_native_cp_al operation", 2);
				syslog_warn("Some files and/or directories in $src only transferred partially during rsync_cleanup_after_native_cp_al operation");
			} elsif (24 == $retval) {
				print_warn ("Some files and/or directories in $src vanished during rsync_cleanup_after_native_cp_al operation", 2);
				syslog_warn("Some files and/or directories in $src vanished during rsync_cleanup_after_native_cp_al operation");

			} else {
				# other error
				bail("rsync returned error $retval in rsync_cleanup_after_native_cp_al()");
			}
		}
	}
	
	return (1);
}

# accepts a path
# displays the rm command according to the config file
sub display_rm_rf {
	my $path = shift(@_);
	
	if (!defined($path)) { bail('display_rm_rf() requires an argument'); }
	
	if (defined($config_vars{'cmd_rm'})) {
		print_cmd("$config_vars{'cmd_rm'} -rf $path");
	} else {
		print_cmd("rm -rf $path");
	}
}

# stub subroutine
# calls either cmd_rm_rf() or the native perl rmtree()
# returns 1 on success, 0 on failure
sub rm_rf {
	my $path = shift(@_);
	my $result = 0;
	
	# make sure we were passed an argument
	if (!defined($path)) { return(0); }
	
	# extra bonus safety feature!
	# confirm that whatever we're deleting must be inside the snapshot_root
	if ("$path" !~ m/^$config_vars{'snapshot_root'}/o) {
		bail("rm_rf() tried to delete something outside of $config_vars{'snapshot_root'}! Quitting now!");
	}
	
	# use the rm command if we have it
	if (defined($config_vars{'cmd_rm'})) {
		$result = cmd_rm_rf("$path");
		
	# fall back on rmtree()
	} else {
		# remove trailing slash just in case
		$path =~ s/\/$//;
		$result = rmtree("$path", 0, 0);
	}
	
	return ($result);
}

# this is a wrapper to the "rm" program, called with the "-rf" flags.
sub cmd_rm_rf {
	my $path = shift(@_);
	my $result = 0;
	
	# make sure we were passed an argument
	if (!defined($path)) { return(0); }
	
	if ( ! -e "$path" ) {
		print_err("cmd_rm_rf() needs a valid file path as an argument", 2);
		return (0);
	}
	
	# make the system call to /bin/rm
	$result = system( $config_vars{'cmd_rm'}, '-rf', "$path" );
	if ($result != 0) {
		print_err("Warning! $config_vars{'cmd_rm'} failed.", 2);
		return (0);
	}
	
	return (1);
}

# accepts no arguments
# calls the 'du' command to show rsnapshot's disk usage
# exits the program with 0 for success, 1 for failure
#
# this subroutine isn't like a lot of the "real" ones that write to logfiles, etc.
# that's why the print_* subroutines aren't used here.
#
sub show_disk_usage {
	my $intervals_str = '';
	my $cmd_du	= 'du';
	my $du_args	= '-csh';
	my $dest_path = '';
	my $retval;
	
	# first, make sure we have permission to see the snapshot root
	if ( ! -r "$config_vars{'snapshot_root'}" ) {
		print STDERR ("ERROR: Permission denied\n");
		exit(1);
	}
	
	# check for 'du' program
	if ( defined($config_vars{'cmd_du'}) ) {
		# it was specified in the config file, use that version
		$cmd_du = $config_vars{'cmd_du'};
	}
	
	# check for du args
	if ( defined($config_vars{'du_args'}) ) {
		# it this was specified in the config file, use that version
		$du_args = $config_vars{'du_args'};
	}
	
	# are we looking in subdirectories or at files?
	if (defined($ARGV[1])) {
		$dest_path = $ARGV[1];
		
		# consolidate multiple slashes
		$dest_path =~ s/\/+/\//o;
		
		if (is_directory_traversal($dest_path)) {
			print STDERR "ERROR: Directory traversal is not allowed\n";
			exit(1);
		}
		if (is_valid_local_abs_path($dest_path)) {
			print STDERR "ERROR: Full paths are not allowed\n";
			exit(1);
		}
	}
	
	# find the directories to look through, in order
	# only add them to the list if we have read permissions
	if (-r "$config_vars{'snapshot_root'}/") {
		# if we have a .sync directory, that will have the most recent files, and should be first
		if (-d "$config_vars{'snapshot_root'}/.sync") {
			if (-r "$config_vars{'snapshot_root'}/.sync") {
				$intervals_str .= "$config_vars{'snapshot_root'}/.sync ";
			}
		}
		
		# loop through the intervals, most recent to oldest
		foreach my $interval_ref (@intervals) {
			my $interval			= $$interval_ref{'interval'};
			my $max_interval_num	= $$interval_ref{'number'};
			
			for (my $i=0; $i < $max_interval_num; $i++) {
				if (-r "$config_vars{'snapshot_root'}/$interval.$i/$dest_path") {
					$intervals_str .= "$config_vars{'snapshot_root'}/$interval.$i/$dest_path ";
				}
			}
		}
	}
	chop($intervals_str);
	
	# if we can see any of the intervals, find out how much space they're taking up
	# most likely we can either see all of them or none at all
	if ('' ne $intervals_str) {
		if (defined($verbose) && ($verbose >= 3)) {
			print wrap_cmd("$cmd_du $du_args $intervals_str"), "\n\n";
		}
		
		if (0 == $test) {
			$retval = system("$cmd_du $du_args $intervals_str");
			if (0 == $retval) {
				# exit showing success
				exit(0);
			} else {
				# exit showing error
				print STDERR "Error while calling $cmd_du.\n";
				print STDERR "Please make sure this version of du supports the \"$du_args\" flags.\n";
				print STDERR "GNU du is recommended.\n";
				exit(1);
			}
		} else {
			# test was successful
			exit(0);
		}
	} else {
		print STDERR ("No files or directories found\n");
		exit(1);
	}
	
	# shouldn't happen
	exit(1);
}

# accept two args from $ARGV[1] and [2], like "daily.0" "daily.1" etc.
# stick the full snapshot_root path on the beginning, and call rsnapshot-diff with these args
# NOTE: since this is a read-only operation, we're not concerned with directory traversals and relative paths
sub show_rsnapshot_diff {
	my $cmd_rsnapshot_diff = 'rsnapshot-diff';
	
	my $retval;
	
	# this will only hold two entries, no more no less
	# paths_in holds the incoming arguments
	# args will be assigned the arguments that rsnapshot-diff will use
	#
	my @paths_in	= ();
	my @cmd_args	= ();
	
	# first, make sure we have permission to see the snapshot root
	if ( ! -r "$config_vars{'snapshot_root'}" ) {
		print STDERR ("ERROR: Permission denied\n");
		exit(1);
	}
	
	# check for rsnapshot-diff program (falling back on $PATH)
	if (defined($config_vars{'cmd_rsnapshot_diff'})) {
		$cmd_rsnapshot_diff = $config_vars{'cmd_rsnapshot_diff'};
	}
	
	# see if we even got the right number of arguments (none is OK, but 1 isn't. 2 is also OK)
	if (defined($ARGV[1]) && !defined($ARGV[2])) {
		print STDERR "Usage: rsnapshot diff [backup level|dir] [backup level|dir]\n";
		exit(1);
	}
	
	# make this automatically pick the two lowest intervals (or .sync dir) for comparison, as the default
	# we actually want to specify the older directory first, since rsnapshot-diff will flip them around
	# anyway based on mod times. doing it this way should make both programs consistent, and cause less
	# surprises.
	if (!defined($ARGV[1]) && !defined($ARGV[2])) {
		# sync_first is enabled, and .sync exists
		if ($config_vars{'sync_first'} && (-d "$config_vars{'snapshot_root'}/.sync/")) {
			# interval.0
			if ( -d ("$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".0" ) ) {
				$cmd_args[0] = "$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".0";
			}
			
			# .sync
			$cmd_args[1] = "$config_vars{'snapshot_root'}/.sync";
			
		# sync_first is not enabled, or .sync doesn't exist
		} else {
			# interval.1
			if ( -d ("$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".1" ) ) {
				$cmd_args[0] = "$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".1";
			}
			# interval.0
			if ( -d ("$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".0" ) ) {
				$cmd_args[1] = "$config_vars{'snapshot_root'}/" . $intervals[0]->{'interval'} . ".0";
			}
		}
			
	# if we got some command line arguments, loop through twice and figure out what they mean
	} else {
		$paths_in[0] = $ARGV[1];	# the 1st path is the 2nd cmd line argument
		$paths_in[1] = $ARGV[2];	# the 2nd path is the 3rd cmd line argument
	
		for (my $i=0; $i<2; $i++) {
			# no interval would start with ../
			if (is_directory_traversal( "$paths_in[$i]" )) {
				$cmd_args[$i] = $paths_in[$i];
				
			# if this directory exists locally, it must be local
			} elsif ( -e "$paths_in[$i]" ) {
				$cmd_args[$i] = $paths_in[$i];
				
			# absolute path
			} elsif (is_valid_local_abs_path( "$paths_in[$i]" )) {
				$cmd_args[$i] = $paths_in[$i];
				
			# we didn't find it locally, but it's in the snapshot root
			} elsif ( -e "$config_vars{'snapshot_root'}/$paths_in[$i]" ) {
				$cmd_args[$i] = "$config_vars{'snapshot_root'}/$paths_in[$i]";
			}
		}
	}
	
	# double check to make sure the directories exists (and are directories)
	if ( (!defined($cmd_args[0]) or (!defined($cmd_args[1]))) or ((! -d "$cmd_args[0]") or (! -d "$cmd_args[1]")) ) {
		print STDERR "ERROR: Arguments must be valid backup levels or directories\n";
		exit(1);
	}
	
	# remove trailing slashes from directories
	$cmd_args[0] = remove_trailing_slash($cmd_args[0]);
	$cmd_args[1] = remove_trailing_slash($cmd_args[1]);
	
	# increase verbosity (by possibly sticking a verbose flag in as the first argument)
	#
	# debug
	if ($verbose >= 5) {
		unshift(@cmd_args, '-V');
		
	} elsif ($verbose >= 4) {
		unshift(@cmd_args, '-v');
		
	# verbose
	} elsif ($verbose >= 3) {
		unshift(@cmd_args, '-vi');
	}
	
	# run rsnapshot-diff
	if (defined($verbose) && ($verbose >= 3)) {
		print wrap_cmd(("$cmd_rsnapshot_diff " . join(' ', @cmd_args))), "\n\n";
	}
	if (0 == $test) {
		$retval = system($cmd_rsnapshot_diff, @cmd_args);
		if (0 == $retval) {
			exit(0);
		} else {
			# exit showing error
			print STDERR "Error while calling $cmd_rsnapshot_diff\n";
			exit(1);
		}
	} else {
		# test was successful
		exit(0);
	}
	
	# shouldn't happen
	exit(1);
}

# This subroutine works the way I hoped rsync would under certain conditions.
# This is no fault of rsync, I just had something slightly different in mind :)
#
# This subroutine accepts two arguments, a source path and a destination path.
# It traverses both recursively.
#   If a file is in the source, but not the destination, it is hard linked into dest
#   If a file is in the destination, but not the source, it is deleted
#   If a file is in both locations and is different, dest is unlinked and src is linked to dest
#   If a file is in both locations and is the same, nothing happens
#
# What makes this different than rsync is that it looks only at the file contents to
# see if the files are different, not at the metadata such as timestamps.
# I was unable to make rsync work recursively on identical files without unlinking
# at the destination and using another inode for a new file with the exact same content.
#
# If anyone knows of a better way (that doesn't add dependencies) i'd love to hear it!
#
sub sync_if_different {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	my $result	= 0;
	
	# make sure we were passed two arguments
	if (!defined($src))  { return(0); }
	if (!defined($dest)) { return(0); }
	
	# make sure we have a source directory
	if ( ! -d "$src" ) {
		print_err("sync_if_different() needs a valid source directory as its first argument", 2);
		return (0);
	}
	
	# strip trailing slashes off the directories,
	# since we'll add them back on later
	$src  = remove_trailing_slash($src);
	$dest = remove_trailing_slash($dest);
	
	# copy everything from src to dest
	# print and/or log this if necessary
	if (($verbose > 4) or ($loglevel > 4)) {
		my $cmd_string = "sync_cp_src_dest(\"$src\", \"$dest\")";
	
		if ($verbose > 4) {
			print_cmd($cmd_string);
		} elsif ($loglevel > 4) {
			log_msg($cmd_string, 4);
		}
	}
	$result = sync_cp_src_dest("$src", "$dest");
	if ( ! $result ) {
		print_err("Warning! sync_cp_src_dest(\"$src\", \"$dest\")", 2);
		return (0);
	}
	
	# delete everything from dest that isn't in src
	# print and/or log this if necessary
	if (($verbose > 4) or ($loglevel > 4)) {
		my $cmd_string = "sync_rm_dest(\"$src\", \"$dest\")";
	
		if ($verbose > 4) {
			print_cmd($cmd_string);
		} elsif ($loglevel > 4) {
			log_msg($cmd_string, 4);
		}
	}
	$result = sync_rm_dest("$src", "$dest");
	if ( ! $result ) {
		print_err("Warning! sync_rm_dest(\"$src\", \"$dest\")", 2);
		return (0);
	}
	
	return (1);
}

# accepts src, dest
# "copies" everything from src to dest, mainly using hard links
# called only from sync_if_different()
# returns 1 on success, 0 if any failures occur
sub sync_cp_src_dest {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	my $dh		= undef;
	my $result	= 0;
	my $retval	= 1;	# return code for this subroutine
	
	# make sure we were passed two arguments
	if (!defined($src))  { return(0); }
	if (!defined($dest)) { return(0); }
	
	# make sure we have a source directory
	if ( ! -d "$src" ) {
		print_err("sync_if_different() needs a valid source directory as its first argument", 2);
		return (0);
	}
	
	# strip trailing slashes off the directories,
	# since we'll add them back on later
	$src  = remove_trailing_slash($src);
	$dest = remove_trailing_slash($dest);
	
	# LSTAT SRC
	my $st = lstat("$src");
	if (!defined($st)) {
		print_err("Could not lstat(\"$src\")", 2);
		return(0);
	}
	
	# MKDIR DEST (AND SET MODE)
	if ( ! -d "$dest" ) {
		# check to make sure we don't have something here that's not a directory
		if ( -e "$dest" ) {
			$result = unlink("$dest");
			if (0 == $result) {
				print_err("Warning! Could not unlink(\"$dest\")", 2);
				return(0);
			}
		}
		
		# create the directory
		$result = mkdir("$dest", $st->mode);
		if ( ! $result ) {
			print_err("Warning! Could not mkdir(\"$dest\", $st->mode);", 2);
			return(0);
		}
	}
	
	# CHOWN DEST (if root)
	if (0 == $<) {
		# make sure destination is not a symlink (should never happen because of unlink() above)
		if ( ! -l "$dest" ) {
			$result = safe_chown($st->uid, $st->gid, "$dest");
			if (! $result) {
				print_err("Warning! Could not safe_chown(" . $st->uid . ", " . $st->gid . ", \"$dest\");", 2);
				return(0);
			}
		}
	}
	
	# copy anything different from src into dest
	$dh = new DirHandle( "$src" );
	if (defined($dh)) {
		my @nodes = $dh->read();
		
		# loop through all nodes in this dir
		foreach my $node (@nodes) {
			
			# skip '.' and '..'
			next if ($node =~ m/^\.\.?$/o);
			
			# if it's a symlink, create the link
			# this check must be done before dir and file because it will
			# pretend to be a file or a directory as well as a symlink
			if ( -l "$src/$node" ) {
				# nuke whatever is in the destination, since we'd have to recreate the symlink anyway
				# and a real file or directory will be in our way
				# symlinks pretend to be directories, which is why we check it the way that we do
				if ( -e "$dest/$node" ) {
					if ((-l "$dest/$node") or (! -d "$dest/$node")) {
						$result = unlink("$dest/$node");
						if (0 == $result) {
							print_err("Warning! Could not unlink(\"$dest/$node\")", 2);
							next;
						}
						
					# nuke the destination directory
					} else {
						$result = rm_rf("$dest/$node");
						if (0 == $result) {
							print_err("Could not rm_rf(\"$dest/$node\")", 2);
							next;
						}
					}
				}
				
				$result = copy_symlink("$src/$node", "$dest/$node");
				if (0 == $result) {
					print_err("Warning! copy_symlink(\"$src/$node\", \"$dest/$node\") failed", 2);
					return(0);
				}
				
			# if it's a directory, recurse!
			} elsif ( -d "$src/$node" ) {
				# if the destination exists but isn't a directory, delete it
				if (-e "$dest/$node") {
					# a symlink might claim to be a directory, so check for that first
					if ((-l "$dest/$node") or (! -d "$dest/$node")) {
						$result = unlink("$dest/$node");
						if (0 == $result) {
							print_err("Warning! unlink(\"$dest/$node\") failed", 2);
							next;
						}
					}
				}
				
				# ok, dest is a real directory or it isn't there yet, go recurse
				$result = sync_cp_src_dest("$src/$node", "$dest/$node");
				if (! $result) {
					print_err("Warning! Recursion error in sync_cp_src_dest(\"$src/$node\", \"$dest/$node\")", 2);
				}
				
			# if it's a file...
			} elsif ( -f "$src/$node" ) {
				# if dest is a symlink, we need to remove it first
				if ( -l "$dest/$node" ) {
					$result = unlink("$dest/$node");
					if (0 == $result) {
						print_err("Warning! unlink(\"$dest/$node\") failed", 2);
						next;
					}
				}
				
				# if dest is a directory, we need to wipe it out first
				if ( -d "$dest/$node" ) {
					$result = rm_rf("$dest/$node");
					if (0 == $result) {
						print_err("Could not rm_rf(\"$dest/$node\")", 2);
						return(0);
					}
				}
				
				# if dest (still) exists, check for differences
				if ( -e "$dest/$node" ) {
					
					# if they are different, unlink dest and link src to dest
					if (1 == file_diff("$src/$node", "$dest/$node")) {
						$result = unlink("$dest/$node");
						if (0 == $result) {
							print_err("Warning! unlink(\"$dest/$node\") failed", 2);
							next;
						}
						$result = link("$src/$node", "$dest/$node");
						if (0 == $result) {
							print_err("Warning! link(\"$src/$node\", \"$dest/$node\") failed", 2);
							next;
						}
						
					# if they are the same, just leave dest alone
					} else {
						next;
					}
					
				# ok, dest doesn't exist. just link src to dest
				} else {
					$result = link("$src/$node", "$dest/$node");
					if (0 == $result) {
						print_err("Warning! link(\"$src/$node\", \"$dest/$node\") failed", 2);
					}
				}
				
			# FIFO
			} elsif ( -p "$src/$node" ) {
				print_err("Warning! Ignoring FIFO $src/$node", 2);
				
			# SOCKET
			} elsif ( -S "$src/$node" ) {
				print_err("Warning! Ignoring socket: $src/$node", 2);
				
			# BLOCK DEVICE
			} elsif ( -b "$src/$node" ) {
				print_err("Warning! Ignoring special block file: $src/$node", 2);
				
			# CHAR DEVICE
			} elsif ( -c "$src/$node" ) {
				print_err("Warning! Ignoring special character file: $src/$node", 2);
			}
		}
	}
	# close open dir handle
	if (defined($dh)) { $dh->close(); }
	undef( $dh );
	
	return (1);
}

# accepts src, dest
# deletes everything from dest that isn't in src also
# called only from sync_if_different()
sub sync_rm_dest {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	my $dh		= undef;
	my $result	= 0;
	
	# make sure we were passed two arguments
	if (!defined($src))  { return(0); }
	if (!defined($dest)) { return(0); }
	
	# make sure we have a source directory
	if ( ! -d "$src" ) {
		print_err("sync_rm_dest() needs a valid source directory as its first argument", 2);
		return (0);
	}
	
	# make sure we have a destination directory
	if ( ! -d "$dest" ) {
		print_err("sync_rm_dest() needs a valid destination directory as its second argument", 2);
		return (0);
	}
	
	# strip trailing slashes off the directories,
	# since we'll add them back on later
	$src  = remove_trailing_slash($src);
	$dest = remove_trailing_slash($dest);
	
	# delete anything from dest that isn't found in src
	$dh = new DirHandle( "$dest" );
	if (defined($dh)) {
		my @nodes = $dh->read();
		
		# loop through all nodes in this dir
		foreach my $node (@nodes) {
			
			# skip '.' and '..'
			next if ($node =~ m/^\.\.?$/o);
			
			# if this node isn't present in src, delete it
			if ( ! -e "$src/$node" ) {
				# file or symlink
				if ((-l "$dest/$node") or (! -d "$dest/$node")) {
					$result = unlink("$dest/$node");
					if (0 == $result) {
						print_err("Warning! Could not delete \"$dest/$node\"", 2);
						next;
					}
					
				# directory
				} else {
					$result = rm_rf("$dest/$node");
					if (0 == $result) {
						print_err("Warning! Could not delete \"$dest/$node\"", 2);
					}
				}
				next;
			}
			
			# ok, this also exists in src...
			# theoretically, sync_cp_src_dest() should have caught this already, but better safe than sorry
			# also, symlinks can pretend to be directories, so we have to check for those too
			
			# if src is a file but dest is a directory, we need to recursively remove the dest dir
			if ((-l "$src/$node") or (! -d "$src/$node")) {
				if (-d "$dest/$node") {
					$result = rm_rf("$dest/$node");
					if (0 == $result) {
						print_err("Warning! Could not delete \"$dest/$node\"", 2);
					}
				}
				
			# otherwise, if src is a directory, but dest is a file, remove the file in dest
			} elsif (-d "$src/$node") {
				if ((-l "$dest/$node") or (! -d "$dest/$node")) {
					$result = unlink("$dest/$node");
					if (0 == $result) {
						print_err("Warning! Could not delete \"$dest/$node\"", 2);
						next;
					}
				}
			}
			
			# if it's a directory in src, let's recurse into it and compare files there
			if ( -d "$src/$node" ) {
				$result = sync_rm_dest("$src/$node", "$dest/$node");
				if ( ! $result ) {
					print_err("Warning! Recursion error in sync_rm_dest(\"$src/$node\", \"$dest/$node\")", 2);
				}
			}
		}
	}
	# close open dir handle
	if (defined($dh)) { $dh->close(); }
	undef( $dh );
	
	return (1);
	
}

# accepts src, dest
# "copies" a symlink from src by recreating it in dest
# returns 1 on success, 0 on failure
sub copy_symlink {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	my $st		= undef;
	my $result	= undef;
	
	my $link_deref_path	= undef;
	
	# make sure it's actually a symlink
	if ( ! -l "$src" ) {
		print_err("Warning! \"$src\" not a symlink in copy_symlink()", 2);
		return (0);
	}
	
	# make sure we aren't clobbering the destination
	if ( -e "$dest" ) {
		print_err("Warning! \"$dest\" exists!", 2);
		return (0);
	}
	
	# LSTAT
	$st = lstat("$src");
	if (!defined($st)) {
		print_err("Warning! lstat(\"$src\") failed", 2);
		return (0);
	}
	
	# CREATE THE SYMLINK
	# This is done in two steps:
	# Reading/dereferencing the link, and creating a new one
	#
	# Step 1: READ THE LINK
	if (($verbose > 4) or ($loglevel > 4)) {
		my $cmd_string = "readlink(\"$src\")\n";
		
		if ($verbose > 4) {
			print_cmd($cmd_string);
		} elsif ($loglevel > 4) {
			log_msg($cmd_string, 4);
		}
	}
	$link_deref_path = readlink("$src");
	if (!defined($link_deref_path)) {
		print_err("Warning! Could not readlink(\"$src\")", 2);
		return (0);
	}
	#
	# Step 2: RECREATE THE LINK
	if (($verbose > 4) or ($loglevel > 4)) {
		my $cmd_string = "symlink(\"$link_deref_path\", \"$dest\")\n";
		
		if ($verbose > 4) {
			print_cmd($cmd_string);
		} elsif ($loglevel > 4) {
			log_msg($cmd_string, 4);
		}
	}
	$result = symlink("$link_deref_path", "$dest");
	if (0 == $result) {
		print_err("Warning! Could not symlink(\"$link_deref_path\"), \"$dest\")", 2);
		return (0);
	}
	
	# CHOWN DEST (if root)
	if (0 == $<) {
		# make sure the symlink even exists
		if ( -e "$dest" ) {
			
			# print and/or log this if necessary
			if (($verbose > 4) or ($loglevel > 4)) {
				my $cmd_string = "safe_chown(" . $st->uid . ", " . $st->gid . ", \"$dest\");";
			
				if ($verbose > 4) {
					print_cmd($cmd_string);
				} elsif ($loglevel > 4) {
					log_msg($cmd_string, 4);
				}
			}
			
			$result = safe_chown($st->uid, $st->gid, "$dest");
			
			if (0 == $result) {
				print_err("Warning! Could not safe_chown(" . $st->uid . ", " . $st->gid . ", \"$dest\")", 2);
				return (0);
			}
		}
	}
	
	return (1);
}

# accepts a file permission number from $st->mode (e.g., 33188)
# returns a "normal" file permission number (e.g., 644)
# do the appropriate bit shifting to get a "normal" UNIX file permission mode
sub get_perms {
	my $raw_mode = shift(@_);
	
	if (!defined($raw_mode)) { return (undef); }
	
	# a lot of voodoo for just one line
	# http://www.perlmonks.org/index.pl?node_id=159906
	my $mode = sprintf("%04o", ($raw_mode & 07777));
	
	return ($mode);
}

# accepts return value from the system() command
# bitmasks it, and returns the same thing "echo $?" would from the shell
sub get_retval {
	my $retval = shift(@_);
	
	if (!defined($retval)) {
		bail('get_retval() was not passed a value');
	}
	if ($retval !~ m/^\d+$/) {
		bail("get_retval() was passed $retval, a number is required");
	}
	
	return ($retval / 256);
}

# accepts two file paths
# returns 0 if they're the same, 1 if they're different
# returns undef if one or both of the files can't be found, opened, or closed
sub file_diff   {
	my $file1	= shift(@_);
	my $file2	= shift(@_);
	my $st1		= undef;
	my $st2		= undef;
	my $buf1	= undef;
	my $buf2	= undef;
	my $result	= undef;
	
	# number of bytes to read at once
	my $BUFSIZE = 16384;
	
	# boolean file comparison flag. assume they're the same.
	my $is_different = 0;
	
	if (! -r "$file1")	{ return (undef); }
	if (! -r "$file2")	{ return (undef); }
	
	# CHECK FILE SIZES FIRST
	$st1 = lstat("$file1");
	$st2 = lstat("$file2");
	
	if (!defined($st1))	{ return (undef); }
	if (!defined($st2))	{ return (undef); }
	
	# if the files aren't even the same size, they can't possibly be the same.
	# don't waste time comparing them more intensively
	if ($st1->size != $st2->size) {
		return (1);
	}
	
	# ok, we're still here.
	# that means we have to compare files one chunk at a time
	
	# open both files
	$result = open(FILE1, "$file1");
	if (!defined($result)) {
		return (undef);
	}
	$result = open(FILE2, "$file2");
	if (!defined($result)) {
		close(FILE1);
		return (undef);
	}
	
	# compare files
	while (read(FILE1, $buf1, $BUFSIZE) && read(FILE2, $buf2, $BUFSIZE)) {
		# exit this loop as soon as possible
		if ($buf1 ne $buf2)	 {
			$is_different = 1;
			last;
		}
	}
	
	# close both files
	$result = close(FILE2);
	if (!defined($result)) {
		close(FILE1);
		return (undef);
	}
	$result = close(FILE1);
	if (!defined($result)) {
		return (undef);
	}
	
	# return our findings
	return ($is_different);
}

# accepts src, dest (file paths)
# calls rename(), forcing the mtime to be correct (to work around a bug in rare versions of the Linux 2.4 kernel)
# returns 1 on success, 0 on failure, just like the real rename() command
sub safe_rename {
	my $src		= shift(@_);
	my $dest	= shift(@_);
	
	my $st;
	my $retval;
	my $result;
	
	# validate src and dest paths
	if (!defined($src)) {
		print_err("safe_rename() needs a valid source file path as an argument", 2);
		return (0);
	}
	if (!defined($dest)) {
		print_err("safe_rename() needs a valid destination file path as an argument", 2);
		return (0);
	}
	
	# stat file before rename
	$st = stat($src);
	if (!defined($st)) {
		print_err("Could not stat() \"$src\"", 2);
		return (0);
	}
	
	# rename the file
	$retval = rename( "$src", "$dest" );
	if (1 != $retval) {
		print_err("Could not rename(\"$src\", \"$dest\")", 2);
		return (0);
	}
	
	# give it back the old mtime and atime values
	$result = utime( $st->atime, $st->mtime, "$dest" );
	if (!defined($result)) {
		print_err("Could not utime( $st->atime, $st->mtime, \"$dest\")", 2);
		return (0);
	}
	
	# if we made it this far, it must have worked
	return (1);
}

# accepts no args
# checks the config file for version number
# prints the config version to stdout
# exits the program, 0 on success, 1 on failure
# this feature is "undocumented", for use with scripts, etc
sub check_config_version {
	my $version = get_config_version();
	
	if (!defined($version)) {
		print "error\n";
		exit(1);
	}
	
	print $version, "\n";
	exit(0);
}

# accepts no args
# scans the config file for the config_version parameter
# returns the config version, or undef
sub get_config_version {
	my $result;
	my $version;
	
	# make sure the config file exists and we can read it
	if (!defined($config_file)) {
		return (undef);
	}
	if (! -r "$config_file") {
		return (undef);
	}
	
	# open the config file
	$result = open(CONFIG, "$config_file");
	if (!defined($result)) {
		return (undef);
	}
	
	# scan the config file looking for the config_version parameter
	# if we find it, exit the loop
	while (my $line = <CONFIG>) {
		chomp($line);
		
		if ($line =~ m/^config_version/o) {
			if ($line =~ m/^config_version\t+([\d\.\-\w]+)$/o) {
				$version = $1;
				last;
			} else {
				$version = 'undefined';
			}
		}
	}
	
	$result = close(CONFIG);
	if (!defined($result)) {
		return (undef);
	}
	
	if (!defined($version)) {
		$version = 'unknown';
	}
	
	return ($version);
}

# accepts no args
# exits the program, 0 on success, 1 on failure
# attempts to upgrade the rsnapshot.conf file for compatibility with this version
sub upgrade_config_file {
	my $result;
	my @lines;
	my $config_version;
	
	# check if rsync_long_args is already enabled
	my $rsync_long_args_enabled	= 0;
	
	# first, see if the file isn't already up to date
	$config_version = get_config_version();
	if (!defined($config_version)) {
		print STDERR "ERROR: Could not read config file during version check.\n";
		exit(1);
	}
	# right now 1.2 is the only valid version
	if ('1.2' eq $config_version) {
		print "$config_file file is already up to date.\n";
		exit(0);
		
	# config_version is set, but not to anything we know about
	} elsif ('unknown' eq $config_version) {
		# this is good, it means the config_version was not already set to anything
		# and is a good candidate for the upgrade
		
	} else {
		print STDERR "ERROR: config_version is set to unknown version: $config_version.\n";
		exit(1);
	}
	
	# make sure config file is present and readable
	if (!defined($config_file)) {
		print STDERR "ERROR: Config file not defined.\n";
		exit(1);
	}
	if (! -r "$config_file") {
		print STDERR "ERROR: $config_file not readable.\n";
		exit(1);
	}
	
	# read in original config file
	$result = open(CONFIG, "$config_file");
	if (!defined($result)) {
		print STDERR "ERROR: Could not open $config_file for reading.\n";
		exit(1);
	}
	@lines = <CONFIG>;
	$result = close(CONFIG);
	if (!defined($result)) {
		print STDERR "ERROR: Could not close $config_file after reading.\n";
		exit(1);
	}
	
	# see if we can find rsync_long_args, either commented out or uncommented
	foreach my $line (@lines) {
		if ($line =~ m/^rsync_long_args/o) {
			$rsync_long_args_enabled = 1;
		}
	}
	
	# back up old config file
	backup_config_file(\@lines);
	
	# found rsync_long_args enabled
	if ($rsync_long_args_enabled) {
		print "Found \"rsync_long_args\" uncommented. Attempting upgrade...\n";
		write_upgraded_config_file(\@lines, 0);
		
	# did not find rsync_long_args enabled
	} else {
		print "Could not find old \"rsync_long_args\" parameter. Attempting upgrade...\n";
		write_upgraded_config_file(\@lines, 1);
	}
	
	print "\"$config_file\" was successfully upgraded.\n";
	
	exit(0);
}

# accepts array_ref of config file lines
# exits 1 on errors
# attempts to backup rsnapshot.conf to rsnapshot.conf.backup.(#)
sub backup_config_file {
	my $lines_ref = shift(@_);
	
	my $result;
	my $backup_config_file;
	my $backup_exists = 0;
	
	if (!defined($lines_ref)) {
		print STDERR "ERROR: backup_config_file() was not passed an argument.\n";
		exit(1);
	}
	
	if (!defined($config_file)) {
		print STDERR "ERROR: Could not find config file.\n";
		exit(1);
	}
	
	$backup_config_file = "$config_file.backup";
	
	print "Backing up \"$config_file\".\n";
	
	# pick a unique name for the backup file
	if ( -e "$backup_config_file" ) {
		$backup_exists = 1;
		for (my $i=0; $i<100; $i++) {
			if ( ! -e "$backup_config_file.$i" ) {
				$backup_config_file = "$backup_config_file.$i";
				$backup_exists = 0;
				last;
			}
		}
		
		# if we couldn't write a backup file, exit with an error
		if (1 == $backup_exists) {
			print STDERR "ERROR: Refusing to overwrite $backup_config_file.\n";
			print STDERR "Please move $backup_config_file out of the way and try again.\n";
			print STDERR "$config_file has NOT been upgraded!\n";
			exit(1);
		}
	}
	
	$result = open(OUTFILE, "> $backup_config_file");
	if (!defined($result) or ($result != 1)) {
	    print STDERR "Error opening $backup_config_file for writing.\n";
	    print STDERR "$config_file has NOT been upgraded!\n";
	    exit(1);
	}
	foreach my $line (@$lines_ref) {
	    print OUTFILE $line;
	}
	$result = close(OUTFILE);
	if (!defined($result) or (1 != $result)) {
	    print STDERR "could not cleanly close $backup_config_file.\n";
	    print STDERR "$config_file has NOT been upgraded!\n";
	    exit(1);
	}
	
	print "Config file was backed up to \"$backup_config_file\".\n";
}

# accepts no args
# exits 1 on errors
# attempts to write an upgraded config file to rsnapshot.conf
sub write_upgraded_config_file {
	my $lines_ref			= shift(@_);
	my $add_rsync_long_args	= shift(@_);
	
	my $result;
	
	my $upgrade_notice = '';
	
	$upgrade_notice .= "#-----------------------------------------------------------------------------\n";
	$upgrade_notice .= "# UPGRADE NOTICE:\n";
	$upgrade_notice .= "#\n";
	$upgrade_notice .= "# This file was upgraded automatically by rsnapshot.\n";
	$upgrade_notice .= "#\n";
	$upgrade_notice .= "# The \"config_version\" parameter was added, since it is now required.\n";
	$upgrade_notice .= "#\n";
	$upgrade_notice .= "# The default value for \"rsync_long_args\" has changed in this release.\n";
	$upgrade_notice .= "# By explicitly setting it to the old default values, rsnapshot will still\n";
	$upgrade_notice .= "# behave like it did in previous versions.\n";
	$upgrade_notice .= "#\n";
	
	if (defined($add_rsync_long_args) && (1 == $add_rsync_long_args)) {
		$upgrade_notice .= "# In this file, \"rsync_long_args\" was not enabled before the upgrade,\n";
		$upgrade_notice .= "# so it has been set to the old default value.\n";
	} else {
		$upgrade_notice .= "# In this file, \"rsync_long_args\" was already enabled before the upgrade,\n";
		$upgrade_notice .= "# so it was not changed.\n";
	}
	
	$upgrade_notice .= "#\n";
	$upgrade_notice .= "# New features and improvements have been added to rsnapshot that can\n";
	$upgrade_notice .= "# only be fully utilized by making some additional changes to\n";
	$upgrade_notice .= "# \"rsync_long_args\" and your \"backup\" points. If you would like to get the\n";
	$upgrade_notice .= "# most out of rsnapshot, please read the INSTALL file that came with this\n";
	$upgrade_notice .= "# program for more information.\n";
	$upgrade_notice .= "#-----------------------------------------------------------------------------\n";
	
	if (!defined($config_file)) {
		print STDERR "ERROR: Config file not found.\n";
		exit(1);
	}
	if (! -w "$config_file") {
		print STDERR "ERROR: \"$config_file\" is not writable.\n";
		exit(1);
	}
	
	$result = open(CONFIG, "> $config_file");
	if (!defined($result)) {
		print "ERROR: Could not open \"$config_file\" for writing.\n";
		exit(1);
	}
	
	print CONFIG $upgrade_notice;
	print CONFIG "\n";
	print CONFIG "config_version\t1.2\n";
	print CONFIG "\n";
	
	if (defined($add_rsync_long_args) && (1 == $add_rsync_long_args)) {
		print CONFIG "rsync_long_args\t--delete --numeric-ids\n";
		print CONFIG "\n";
	}
	
	foreach my $line (@$lines_ref) {
		print CONFIG "$line";
	}
	
	$result = close(CONFIG);
	if (!defined($result)) {
		print STDERR "ERROR: Could not close \"$config_file\" after writing\n.";
		exit(1);
	}
}

# accepts no arguments
# dynamically loads the CPAN Lchown module, if available
# sets the global variable $have_lchown
sub use_lchown {
	if ($verbose >= 5) {
		print_msg('require Lchown', 5);
	}
	eval {
		require Lchown;
	};
	if ($@) {
		$have_lchown = 0;
		
		if ($verbose >= 5) {
			print_msg('Lchown module not found', 5);
		}
		
		return(0);
	}
	
	# if it loaded, see if this OS supports the lchown() system call
	{
		no strict 'subs';
		if (defined(Lchown) && defined(Lchown::LCHOWN_AVAILABLE)) {
			if (1 == Lchown::LCHOWN_AVAILABLE()) {
				$have_lchown = 1;
				
				if ($verbose >= 5) {
					print_msg('Lchown module loaded successfully', 5);
				}
				
				return(1);
			}
		}
	}
	
	if ($verbose >= 5) {
		print_msg("Lchown module loaded, but operating system doesn't support lchown()", 5);
	}
	
	return(0);
}

# accepts uid, gid, filepath
# uses lchown() to change ownership of the file, if possible
# returns 1 upon success (or if lchown() not present)
# returns 0 on failure
sub safe_chown {
	my $uid			= shift(@_);
	my $gid			= shift(@_);
	my $filepath	= shift(@_);
	
	my $result = undef;
	
	if (!defined($uid) or !defined($gid) or !defined($filepath)) {
		print_err("safe_chown() needs uid, gid, and filepath", 2);
		return(0);
	}
	if ( ! -e "$filepath" ) {
		print_err("safe_chown() needs a valid filepath (not \"$filepath\")", 2);
		return(0);
	}
	
	# if it's a symlink, use lchown() or skip it
	if (-l "$filepath") {
		# use Lchown
		if (1 == $have_lchown) {
			$result = Lchown::lchown($uid, $gid, "$filepath");
			if (!defined($result)) {
				return (0);
			}
			
		# we can't safely do anything here, skip it
		} else {
			raise_warning();
			
			if ($verbose > 2) {
				print_warn("Could not lchown() symlink \"$filepath\"", 2);
			} elsif ($loglevel > 2) {
				log_warn("Could not lchown() symlink \"$filepath\"", 2);
			}
			
			# we'll still return 1 at the bottom, because we did as well as we could
			# the warning raised will tell the user what happened
		}
		
	# if it's not a symlink, use chown()
	} else {
		$result = chown($uid, $gid, "$filepath");
		if (! $result) {
			return (0);
		}
	}
	
	return (1);
}

########################################
###          PERLDOC / POD           ###
########################################

=pod

=head1 NAME

rsnapshot - remote filesystem snapshot utility

=head1 SYNOPSIS

B<rsnapshot> [B<-vtxqVD>] [B<-c> cfgfile] [command] [args]

=head1 DESCRIPTION

B<rsnapshot> is a filesystem snapshot utility. It can take incremental
snapshots of local and remote filesystems for any number of machines.

Local filesystem snapshots are handled with B<rsync(1)>. Secure remote
connections are handled with rsync over B<ssh(1)>, while anonymous
rsync connections simply use an rsync server. Both remote and local
transfers depend on rsync.

B<rsnapshot> saves much more disk space than you might imagine. The amount
of space required is roughly the size of one full backup, plus a copy
of each additional file that is changed. B<rsnapshot> makes extensive
use of hard links, so if the file doesn't change, the next snapshot is
simply a hard link to the exact same file.

B<rsnapshot> will typically be invoked as root by a cron job, or series
of cron jobs. It is possible, however, to run as any arbitrary user
with an alternate configuration file.

All important options are specified in a configuration file, which is
located by default at B</etc/rsnapshot.conf>. An alternate file can be
specified on the command line. There are also additional options which
can be passed on the command line.

The command line options are as follows:

=over 4

B<-v> verbose, show shell commands being executed

B<-t> test, show shell commands that would be executed

B<-c> path to alternate config file

B<-x> one filesystem, don't cross partitions within each backup point

B<-q> quiet, suppress non-fatal warnings

B<-V> same as -v, but with more detail

B<-D> a firehose of diagnostic information

=back

=head1 CONFIGURATION

B</etc/rsnapshot.conf> is the default configuration file. All parameters
in this file must be separated by tabs. B</usr/share/doc/rsnapshot/examples/rsnapshot.conf.default.gz>
can be used as a reference.

It is recommended that you copy B</usr/share/doc/rsnapshot/examples/rsnapshot.conf.default.gz> to
B</etc/rsnapshot.conf>, and then modify B</etc/rsnapshot.conf> to suit
your needs.

Long lines may be split over several lines.  "Continuation" lines
B<must> begin with a space or a tab character.  Continuation lines will
have all leading and trailing whitespace stripped off, and then be appended
with an intervening tab character to the previous line when the configuation
file is parsed.

Here is a list of allowed parameters:

=over 4

B<config_version>     Config file version (required). Default is 1.2

B<snapshot_root>      Local filesystem path to save all snapshots

B<include_conf>       Include another file in the configuration at this point.
 
=over 4

This is recursive, but you may need to be careful about paths when specifying
which file to include.  We check to see if the file you have specified is
readable, and will yell an error if it isn't.  We recommend using a full
path.  As a special case, include_conf's value may be enclosed in `backticks`
in which case it will be executed and whatever it spits to STDOUT will
be included in the configuration.  Note that shell meta-characters may be
interpreted.

=back

B<no_create_root>     If set to 1, rsnapshot won't create snapshot_root directory

B<cmd_rsync>          Full path to rsync (required)

B<cmd_ssh>            Full path to ssh (optional)

B<cmd_cp>             Full path to cp  (optional, but must be GNU version)

=over 4

If you are using Linux, you should uncomment cmd_cp. If you are using a
platform which does not have GNU cp, you should leave cmd_cp commented out.

With GNU cp, rsnapshot can take care of both normal files and special
files (such as FIFOs, sockets, and block/character devices) in one pass.

If cmd_cp is disabled, rsnapshot will use its own built-in function,
native_cp_al() to backup up regular files and directories. This will
then be followed up by a separate call to rsync, to move the special
files over (assuming there are any).

=back

B<cmd_rm>             Full path to rm (optional)

B<cmd_logger>         Full path to logger (optional, for syslog support)

B<cmd_du>             Full path to du (optional, for disk usage reports)

B<cmd_rsnapshot_diff> Full path to rsnapshot-diff (optional)

B<cmd_preexec>

=over 4

Full path (plus any arguments) to preexec script (optional).
This script will run immediately before each backup operation (but not any
rotations).

=back

B<cmd_postexec>

=over 4

Full path (plus any arguments) to postexec script (optional).
This script will run immediately after each backup operation (but not any
rotations).

=back

B<linux_lvm_cmd_lvcreate>

B<linux_lvm_cmd_lvremove>

B<linux_lvm_cmd_mount>

B<linux_lvm_cmd_umount>

=over 4

Paths to lvcreate, lvremove, mount and umount commands, for use with Linux
LVMs.  The lvcreate, lvremove, mount and umount commands are required for
managing snapshots of LVM volumes and are otherwise optional.

=back

B<retain>             [name]   [number]

=over 4

"name" refers to the name of this backup level (e.g., hourly, daily,
so also called the 'interval'). "number"
is the number of snapshots for this type of interval that will be retained.
The value of "name" will be the command passed to B<rsnapshot> to perform
this type of backup.

A deprecated alias for 'retain' is 'interval'.

Example: B<retain hourly 6>

[root@localhost]# B<rsnapshot hourly>

For this example, every time this is run, the following will happen:

<snapshot_root>/hourly.5/ will be deleted, if it exists.

<snapshot_root>/hourly.{1,2,3,4} will all be rotated +1, if they exist.

<snapshot_root>/hourly.0/ will be copied to <snapshot_root>/hourly.1/
using hard links.

Each backup point (explained below) will then be rsynced to the
corresponding directories in <snapshot_root>/hourly.0/

Backup levels must be specified in the config file in order, from most
frequent to least frequent. The first entry is the one which will be
synced with the backup points. The subsequent backup levels (e.g., daily,
weekly, etc) simply rotate, with each higher backup level pulling from the
one below it for its .0 directory.

Example:

=over 4

B<retain  hourly 6>

B<retain  daily  7>

B<retain  weekly 4>

=back

daily.0/ will be moved from hourly.5/, and weekly.0/ will be copied from daily.6/

hourly.0/ will be rsynced directly from the filesystem.

=back

B<link_dest           1>

=over 4

If your version of rsync supports --link-dest (2.5.7 or newer), you can enable
this to let rsync handle some things that GNU cp or the built-in subroutines would
otherwise do. Enabling this makes rsnapshot take a slightly more complicated code
branch, but it's the best way to support special files on non-Linux systems.

=back

B<sync_first          1>

=over 4

sync_first changes the behaviour of rsnapshot. When this is enabled, all calls
to rsnapshot with various backup levels simply rotate files. All backups are handled
by calling rsnapshot with the "sync" argument. The synced files are stored in
a ".sync" directory under the snapshot_root.

This allows better recovery in the event that rsnapshot is interrupted in the
middle of a sync operation, since the sync step and rotation steps are
separated. This also means that you can easily run "rsnapshot sync" on the
command line without fear of forcing all the other directories to rotate up.
This benefit comes at the cost of one more snapshot worth of disk space.
The default is 0 (off).

=back

B<verbose             2>

=over 4

The amount of information to print out when the program is run. Allowed values
are 1 through 5. The default is 2.

    1        Quiet            Show fatal errors only
    2        Default          Show warnings and errors
    3        Verbose          Show equivalent shell commands being executed
    4        Extra Verbose    Same as verbose, but with more detail
    5        Debug            All kinds of information

=back

B<loglevel            3>

=over 4

This number means the same thing as B<verbose> above, but it determines how
much data is written to the logfile, if one is being written.

The only thing missing from this at the higher levels is the direct output
from rsync. We hope to add support for this in a future release.

=back

B<logfile             /var/log/rsnapshot>

=over 4

Full filesystem path to the rsnapshot log file. If this is defined, a log file
will be written, with the amount of data being controlled by B<loglevel>. If
this is commented out, no log file will be written.

=back

B<include             [file-name-pattern]>

=over 4

This gets passed directly to rsync using the --include directive. This
parameter can be specified as many times as needed, with one pattern defined
per line. See the rsync(1) man page for the syntax.

=back

B<exclude             [file-name-pattern]>

=over 4

This gets passed directly to rsync using the --exclude directive. This
parameter can be specified as many times as needed, with one pattern defined
per line. See the rsync(1) man page for the syntax.

=back

B<include_file        /path/to/include/file>

=over 4

This gets passed directly to rsync using the --include-from directive. See the
rsync(1) man page for the syntax.

=back

B<exclude_file        /path/to/exclude/file>

=over 4

This gets passed directly to rsync using the --exclude-from directive. See the
rsync(1) man page for the syntax.

=back

B<rsync_short_args    -a>

=over 4

List of short arguments to pass to rsync. If not specified,
"-a" is the default. Please note that these must be all next to each other.
For example, "-az" is valid, while "-a -z" is not.

"-a" is rsync's "archive mode" which tells it to copy as much of the
filesystem metadata as it can for each file.  This specifically does *not*
include information about hard links, as that would greatly increase rsync's
memory usage and slow it down.  If you need to preserve hard links in your
backups, then add "H" to this.

=back

B<rsync_long_args     --delete --numeric-ids --relative --delete-excluded>

=over 4

List of long arguments to pass to rsync. Beginning with rsnapshot 1.2.0, this
default has changed. In previous versions, the default values were

    --delete --numeric-ids

Starting with version 1.2.0, the default values are

    --delete --numeric-ids --relative --delete-excluded

This directly affects how the destination paths in your backup points are
constructed. Depending on what behaviour you want, you can explicitly set
the values to make the program behave like the old version or the current
version. The newer settings are recommended if you're just starting. If
you are upgrading, read the upgrade guide in the INSTALL file in the
source distribution for more information.

Quotes are permitted in rsync_long_args, eg --rsync-path="sudo /usr/bin/rsync".
You may use either single (') or double (") quotes, but nested quotes (including
mixed nested quotes) are not permitted.  Similar quoting is also allowed in
per-backup-point rsync_long_args.

=back

B<ssh_args    -p 22>

=over 4

Arguments to be passed to ssh. If not specified, the default is none.

=back

B<du_args     -csh>

=over 4

Arguments to be passed to du. If not specified, the default is -csh.
GNU du supports -csh, BSD du supports -csk, Solaris du doesn't support
-c at all. The GNU version is recommended, since it offers the most
features.

=back

B<lockfile    /var/run/rsnapshot.pid>

B<stop_on_stale_lockfile	0>

=over 4

Lockfile to use when rsnapshot is run. This prevents a second invocation
from clobbering the first one. If not specified, no lock file is used.
Make sure to use a directory that is not world writeable for security
reasons.  Use of a lock file is strongly recommended.

If a lockfile exists when rsnapshot starts, it will try to read the file
and stop with an error if it can't.  If it *can* read the file, it sees if
a process exists with the PID noted in the file.  If it does, rsnapshot
stops with an error message.  If there is no process with that PID, then
we assume that the lockfile is stale and ignore it *unless*
stop_on_stale_lockfile is set to 1 in which case we stop.

stop_on_stale_lockfile defaults to 0.

=back

B<one_fs    1>

=over 4

Prevents rsync from crossing filesystem partitions. Setting this to a value
of 1 enables this feature. 0 turns it off. This parameter is optional.
The default is 0 (off).

=back

B<use_lazy_deletes    1>

=over 4

Changes default behavior of rsnapshot and does not initially remove the 
oldest snapshot. Instead it moves that directory to _delete.[processid] and
continues as normal. Once the backup has been completed, the lockfile will
be removed before rsnapshot starts deleting the directory.

Enabling this means that snapshots get taken sooner (since the delete doesn't
come first), and any other rsnapshot processes are allowed to start while the
final delete is happening. This benefit comes at the cost of using more
disk space. The default is 0 (off).

The details of how this works have changed in rsnapshot version 1.3.1.
Originally you could only ever have one .delete directory per backup level.
Now you can have many, so if your next (eg) hourly backup kicks off while the
previous one is still doing a lazy delete you may temporarily have extra
_delete directories hanging around.

=back

B<linux_lvm_snapshotsize    2G>

=over 4

LVM snapshot(s) size (lvcreate --size option).

=back

B<linux_lvm_snapshotname  rsnapshot>

=over 4

Name to be used when creating the LVM logical volume snapshot(s) (lvcreate --name option).

=back

B<linux_lvm_vgpath		/dev>

=over 4

Path to the LVM Volume Groups.

=back

B<linux_lvm_mountpath		/mnt/lvm-snapshot>

=over 4

Mount point to use to temporarily mount the snapshot(s). 

=back


B<UPGRADE NOTICE:>

=over 4

If you have used an older version of rsnapshot, you might notice that the
destination paths on the backup points have changed. Please read the INSTALL
file in the source distribution for upgrade options.

=back

B<backup>  /etc/                       localhost/

B<backup>  root@example.com:/etc/      example.com/

B<backup>  rsync://example.com/path2/  example.com/

B<backup>  /var/                       localhost/      one_fs=1

B<backup>  lvm://vg0/home/path2/       lvm-vg0/

B<backup_script>   /usr/local/bin/backup_pgsql.sh    pgsql_backup/

=over 4

Examples:

B<backup   /etc/        localhost/>

=over 4

Backs up /etc/ to <snapshot_root>/<retain>.0/localhost/etc/ using rsync on
the local filesystem

=back

B<backup   /usr/local/  localhost/>

=over 4

Backs up /usr/local/ to <snapshot_root>/<retain>.0/localhost/usr/local/
using rsync on the local filesystem

=back

B<backup   root@example.com:/etc/       example.com/>

=over 4

Backs up root@example.com:/etc/ to <snapshot_root>/<retain>.0/example.com/etc/
using rsync over ssh

=back

B<backup   root@example.com:/usr/local/ example.com/>

=over 4

Backs up root@example.com:/usr/local/ to
<snapshot_root>/<retain>.0/example.com/usr/local/ using rsync over ssh

=back

B<backup   rsync://example.com/pub/      example.com/pub/>

=over 4

Backs up rsync://example.com/pub/ to <snapshot_root>/<retain>.0/example.com/pub/
using an anonymous rsync server. Please note that unlike backing up local paths
and using rsync over ssh, rsync servers have "modules", which are top level
directories that are exported. Therefore, the module should also be specified in
the destination path, as shown in the example above (the pub/ directory at the
end).

=back

B<backup   /var/     localhost/   one_fs=1>

=over 4

This is the same as the other examples, but notice the fourth column.
This is how you specify per-backup-point options to over-ride global
settings.  This extra parameter can take several options, separated
by B<commas>.

It is most useful when specifying per-backup rsync excludes thus:

B<backup  root@somehost:/  somehost   +rsync_long_args=--exclude=/var/spool/>

Note the + sign.  That tells rsnapshot to I<add> to the list of arguments
to pass to rsync instead of replacing the list.

=back

B<backup  lvm://vg0/home/path2/       lvm-vg0/>

=over 4

Backs up the LVM logical volume called home, of volume group vg0, to 
<snapshot_root>/<interval>.0/lvm-vg0/. Will create, mount, backup, unmount and remove an LVM 
snapshot for each lvm:// entry.

=back


B<backup_script      /usr/local/bin/backup_database.sh   db_backup/>

=over 4

In this example, we specify a script or program to run. This script should simply
create files and/or directories in its current working directory. rsnapshot will
then take that output and move it into the directory specified in the third column.

Please note that whatever is in the destination directory will be completely
deleted and recreated. For this reason, rsnapshot prevents you from specifying
a destination directory for a backup_script that will clobber other backups.

So in this example, say the backup_database.sh script simply runs a command like:

=over 4

#!/bin/sh

mysqldump -uusername mydatabase > mydatabase.sql

chmod u=r,go= mydatabase.sql	# r-------- (0400)

=back

rsnapshot will take the generated "mydatabase.sql" file and move it into the
<snapshot_root>/<retain>.0/db_backup/ directory. On subsequent runs,
rsnapshot checks the differences between the files created against the
previous files. If the backup script generates the same output on the next
run, the files will be hard linked against the previous ones, and no
additional disk space will be taken up.

=back

=back

Remember that tabs must separate all elements, and that
there must be a trailing slash on the end of every directory.

A hash mark (#) on the beginning of a line is treated
as a comment.

Putting it all together (an example file):

=over 4

    # THIS IS A COMMENT, REMEMBER TABS MUST SEPARATE ALL ELEMENTS

    config_version  1.2

    snapshot_root   /.snapshots/

    cmd_rsync           /usr/bin/rsync
    cmd_ssh             /usr/bin/ssh
    #cmd_cp             /bin/cp
    cmd_rm              /bin/rm
    cmd_logger          /usr/bin/logger
    cmd_du              /usr/bin/du

    linux_lvm_cmd_lvcreate        /sbin/lvcreate
    linux_lvm_cmd_lvremove        /sbin/lvremove
    linux_lvm_cmd_mount           /bin/mount
    linux_lvm_cmd_umount          /bin/umount

    linux_lvm_snapshotsize    2G
    linux_lvm_snapshotname    rsnapshot
    linux_lvm_vgpath          /dev
    linux_lvm_mountpath       /mnt/lvm-snapshot

    retain              hourly  6
    retain              daily   7
    retain              weekly  7
    retain              monthly 3

    backup              /etc/                     localhost/
    backup              /home/                    localhost/
    backup_script       /usr/local/bin/backup_mysql.sh  mysql_backup/

    backup              root@foo.com:/etc/        foo.com/
    backup              root@foo.com:/home/       foo.com/
    backup              root@mail.foo.com:/home/  mail.foo.com/
    backup              rsync://example.com/pub/  example.com/pub/
    backup              lvm://vg0/xen-home/       lvm-vg0/xen-home/

=back

=back

=head1 USAGE

B<rsnapshot> can be used by any user, but for system-wide backups
you will probably want to run it as root.

Since backups usually get neglected if human intervention is
required, the preferred way is to run it from cron.

When you are first setting up your backups, you will probably
also want to run it from the command line once or twice to get
a feel for what it's doing.

Here is an example crontab entry, assuming that backup levels B<hourly>,
B<daily>, B<weekly> and B<monthly> have been defined in B</etc/rsnapshot.conf>

=over 4

B<0 */4 * * *         /usr/local/bin/rsnapshot hourly>

B<50 23 * * *         /usr/local/bin/rsnapshot daily>

B<40 23 * * 6         /usr/local/bin/rsnapshot weekly>

B<30 23 1 * *         /usr/local/bin/rsnapshot monthly>

=back

This example will do the following:

=over 4

6 hourly backups a day (once every 4 hours, at 0,4,8,12,16,20)

1 daily backup every day, at 11:50PM

1 weekly backup every week, at 11:40PM, on Saturdays (6th day of week)

1 monthly backup every month, at 11:30PM on the 1st day of the month

=back

It is usually a good idea to schedule the larger backup levels to run a bit before the
lower ones. For example, in the crontab above, notice that "daily" runs 10 minutes
before "hourly".  The main reason for this is that the daily rotate will
pull out the oldest hourly and make that the youngest daily (which means
that the next hourly rotate will not need to delete the oldest hourly),
which is more efficient.  A secondary reason is that it is harder to
predict how long the lowest backup level will take, since it needs to actually
do an rsync of the source as well as the rotate that all backups do.

If rsnapshot takes longer than 10 minutes to do the "daily" rotate
(which usually includes deleting the oldest daily snapshot), then you
should increase the time between the backup levels.
Otherwise (assuming you have set the B<lockfile> parameter, as is recommended)
your hourly snapshot will fail sometimes because the daily still has the lock.  

Remember that these are just the times that the program runs.
To set the number of backups stored, set the B<retain> numbers in
B</etc/rsnapshot.conf>

To check the disk space used by rsnapshot, you can call it with the "du" argument.

For example:

=over 4

B<rsnapshot du>

=back

This will show you exactly how much disk space is taken up in the snapshot root. This
feature requires the UNIX B<du> command to be installed on your system, for it to
support the "-csh" command line arguments, and to be in your path. You can also
override your path settings and the flags passed to du using the cmd_du and du_args
parameters.

It is also possible to pass a relative file path as a second argument, to get a report
on a particular file or subdirectory.

=over 4

B<rsnapshot du localhost/home/>

=back

The GNU version of "du" is preferred. The BSD version works well also, but does
not support the -h flag (use -k instead, to see the totals in kilobytes). Other
versions of "du", such as Solaris, may not work at all.

To check the differences between two directories, call rsnapshot with the "diff"
argument, followed by two backup levels or directory paths.

For example:

=over 4

B<rsnapshot diff daily.0 daily.1>

B<rsnapshot diff daily.0/localhost/etc daily.1/localhost/etc>

B<rsnapshot diff /.snapshots/daily.0 /.snapshots/daily.1>

=back

This will call the rsnapshot-diff program, which will scan both directories
looking for differences (based on hard links).

B<rsnapshot sync>

=over 4

When B<sync_first> is enabled, rsnapshot must first be called with the B<sync>
argument, followed by the other usual cron entries. The sync should happen as
the lowest, most frequent backup level, and right before. For example:

=over 4

B<0 */4 * * *         /usr/local/bin/rsnapshot sync && /usr/local/bin/rsnapshot hourly>

B<50 23 * * *         /usr/local/bin/rsnapshot daily>

B<40 23 1,8,15,22 * * /usr/local/bin/rsnapshot weekly>

B<30 23 1 * *         /usr/local/bin/rsnapshot monthly>

=back

The sync operation simply runs rsync and all backup scripts. In this scenario, all
calls simply rotate directories, even the lowest backup level.

=back

B<rsnapshot sync [dest]>

=over 4

When B<sync_first> is enabled, all sync behaviour happens during an additional
sync step (see above). When using the sync argument, it is also possible to specify
a backup point destination as an optional parameter. If this is done, only backup
points sharing that destination path will be synced.

For example, let's say that example.com is a destination path shared by one or more
of your backup points.

=over 4

rsnapshot sync example.com

=back

This command will only sync the files that normally get backed up into example.com.
It will NOT get any other backup points with slightly different values (like
example.com/etc/, for example). In order to sync example.com/etc, you would need to
run rsnapshot again, using example.com/etc as the optional parameter.

=back

=head1 EXIT VALUES

=over 4

B<0>  All operations completed successfully

B<1>  A fatal error occurred

B<2>  Some warnings occurred, but the backup still finished

=back

=head1 FILES

/etc/rsnapshot.conf

=head1 SEE ALSO

rsync(1), ssh(1), logger(1), sshd(1), ssh-keygen(1), perl(1), cp(1), du(1), crontab(1)

=head1 DIAGNOSTICS

Use the B<-t> flag to see what commands would have been executed. This will show
you the commands rsnapshot would try to run. There are a few minor differences
(for example, not showing an attempt to remove the lockfile because it wasn't
really created in the test), but should give you a very good idea what will happen.

Using the B<-v>, B<-V>, and B<-D> flags will print increasingly more information
to STDOUT.

Make sure you don't have spaces in the config file that you think are actually tabs.

Much other weird behavior can probably be attributed to plain old file system
permissions and ssh authentication issues.

=head1 BUGS

Please report bugs (and other comments) to the rsnapshot-discuss mailing list:

B<http://lists.sourceforge.net/lists/listinfo/rsnapshot-discuss>

=head1 NOTES

Make sure your /etc/rsnapshot.conf file has all elements separated by tabs.
See /usr/share/doc/rsnapshot/examples/rsnapshot.conf.default.gz for a working example file.

Make sure you put a trailing slash on the end of all directory references.
If you don't, you may have extra directories created in your snapshots.
For more information on how the trailing slash is handled, see the
B<rsync(1)> manpage.

Make sure to make the snapshot directory chmod 700 and owned by root
(assuming backups are made by the root user). If the snapshot directory
is readable by other users, they will be able to modify the snapshots
containing their files, thus destroying the integrity of the snapshots.

If you would like regular users to be able to restore their own backups,
there are a number of ways this can be accomplished. One such scenario
would be:

Set B<snapshot_root> to B</.private/.snapshots> in B</etc/rsnapshot.conf>

Set the file permissions on these directories as follows:

=over 4

drwx------    /.private

drwxr-xr-x    /.private/.snapshots

=back

Export the /.private/.snapshots directory over read-only NFS, a read-only
Samba share, etc.

See the rsnapshot HOWTO for more information on making backups
accessible to non-privileged users.

For ssh to work unattended through cron, you will probably want to use
public key logins. Create an ssh key with no passphrase for root, and
install the public key on each machine you want to backup. If you are
backing up system files from remote machines, this probably means
unattended root logins. Another possibility is to create a second user
on the machine just for backups. Give the user a different name such
as "rsnapshot", but keep the UID and GID set to 0, to give root
privileges. However, make logins more restrictive, either through ssh
configuration, or using an alternate shell.

BE CAREFUL! If the private key is obtained by an attacker, they will
have free run of all the systems involved. If you are unclear on how
to do this, see B<ssh(1)>, B<sshd(1)>, and B<ssh-keygen(1)>.

Backup scripts are run as the same user that rsnapshot is running as.
Typically this is root. Make sure that all of your backup scripts are
only writable by root, and that they don't call any other programs
that aren't owned by root. If you fail to do this, anyone who can
write to the backup script or any program it calls can fully take
over the machine. Of course, this is not a situation unique to
rsnapshot.

By default, rsync transfers are done using the --numeric-ids option.
This means that user names and group names are ignored during transfers,
but the UID/GID information is kept intact. The assumption is that the
backups will be restored in the same environment they came from. Without
this option, restoring backups for multiple heterogeneous servers would
be unmanageable. If you are archiving snapshots with GNU tar, you may
want to use the --numeric-owner parameter. Also, keep a copy of the
archived system's /etc/passwd and /etc/group files handy for the UID/GID
to name mapping.

If you remove backup points in the config file, the previously archived
files under those points will permanently stay in the snapshots directory
unless you remove the files yourself. If you want to conserve disk space,
you will need to go into the <snapshot_root> directory and manually
remove the files from the smallest backup level's ".0" directory.

For example, if you were previously backing up /home/ with a destination
of localhost/, and hourly is your smallest backup level, you would need to do
the following to reclaim that disk space:

=over 4

rm -rf <snapshot_root>/hourly.0/localhost/home/

=back

Please note that the other snapshots previously made of /home/ will still
be using that disk space, but since the files are flushed out of hourly.0/,
they will no longer be copied to the subsequent directories, and will thus
be removed in due time as the rotations happen.

=head1 AUTHORS

Mike Rubel - B<http://www.mikerubel.org/computers/rsync_snapshots/>

=over 4

=item -
Created the original shell scripts on which this project is based

=back

Nathan Rosenquist (B<nathan@rsnapshot.org>)

=over 4

=item -
Primary author and previous maintainer of rsnapshot.

=back

David Cantrell (B<david@cantrell.org.uk>)

=over 4

=item -
Current co-maintainer of rsnapshot

=item -
Wrote the rsnapshot-diff utility

=item -
Improved how use_lazy_deletes work so slow deletes don't screw up the next
backup at that backup level.

=back

David Keegel <djk@cybersource.com.au>

=over 4

=item -
Co-maintainer, with responsibility for release management since 1.2.9

=item -
Fixed race condition in lock file creation, improved error reporting

=item -
Allowed remote ssh directory paths starting with "~/" as well as "/"

=item -
Fixed a number of other bugs and buglets

=back

Carl Wilhelm Soderstrom B<(chrome@real-time.com)>

=over 4

=item -
Created the RPM .spec file which allowed the RPM package to be built, among
other things.

=back

Ted Zlatanov (B<tzz@lifelogs.com>)

=over 4

=item -
Added the one_fs feature, autoconf support, good advice, and much more.

=back

Ralf van Dooren (B<r.vdooren@snow.nl>)

=over 4

=item -
Added and maintains the rsnapshot entry in the FreeBSD ports tree.

=back

SlapAyoda

=over 4

=item -
Provided access to his computer museum for software testing.

=back

Carl Boe (B<boe@demog.berkeley.edu>)

=over 4

=item -
Found several subtle bugs and provided fixes for them.

=back

Shane Leibling (B<shane@cryptio.net>)

=over 4

=item -
Fixed a compatibility bug in utils/backup_smb_share.sh

=back

Christoph Wegscheider (B<christoph.wegscheider@wegi.net>)

=over 4

=item -
Added (and previously maintained) the Debian rsnapshot package.

=back

Bharat Mediratta (B<bharat@menalto.com>)

=over 4

=item -
Improved the exclusion rules to avoid backing up the snapshot root (among
other things).

=back

Peter Palfrader (B<weasel@debian.org>)

=over 4

=item -
Enhanced error reporting to include command line options.

=back

Nicolas Kaiser (B<nikai@nikai.net>)

=over 4

=item -
Fixed typos in program and man page

=back

Chris Petersen - (B<http://www.forevermore.net/>)

=over 4

Added cwrsync permanent-share support

=back

Robert Jackson (B<RobertJ@promedicalinc.com>)

=over 4

Added use_lazy_deletes feature

=back

Justin Grote (B<justin@grote.name>)

=over 4

Improved rsync error reporting code

=back

Anthony Ettinger (B<apwebdesign@yahoo.com>)

=over 4

Wrote the utils/mysqlbackup.pl script

=back

Sherman Boyd

=over 4

Wrote utils/random_file_verify.sh script

=back

William Bear (B<bear@umn.edu>)

=over 4

Wrote the utils/rsnapreport.pl script (pretty summary of rsync stats)

=back

Eric Anderson (B<anderson@centtech.com>)

=over 4

Improvements to utils/rsnapreport.pl.

=back

Alan Batie (B<alan@batie.org>)

=over 4

Bug fixes for include_conf

=back

Dieter Bloms (B<dieter@bloms.de>)

=over 4

Multi-line configuration options

=back

Henning Moll (B<newsScott@gmx.de>)

=over 4

stop_on_stale_lockfile

=back

Ben Low (B<ben@bdlow.net>)

=over 4

Linux LVM snapshot support

=back

=head1 COPYRIGHT

Copyright (C) 2003-2005 Nathan Rosenquist

Portions Copyright (C) 2002-2007 Mike Rubel, Carl Wilhelm Soderstrom,
Ted Zlatanov, Carl Boe, Shane Liebling, Bharat Mediratta, Peter Palfrader,
Nicolas Kaiser, David Cantrell, Chris Petersen, Robert Jackson, Justin Grote,
David Keegel, Alan Batie, Dieter Bloms, Henning Moll, Ben Low, Anthony
Ettinger

This man page is distributed under the same license as rsnapshot:
the GPL (see below).

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA

=cut