Welcome to mirror list, hosted at ThFree Co, Russian Federation.

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

   Copyright (C) 2000-2012 Free Software Foundation Europe e.V.
   Copyright (C) 2011-2012 Planets Communications B.V.
   Copyright (C) 2013-2022 Bareos GmbH & Co. KG

   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version three of the GNU Affero General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

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

   You should have received a copy of the GNU Affero 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.
*/
// Kern Sibbald, April MM
/**
 * @file
 * Bareos Tape manipulation program
 *
 * Has various tape manipulation commands -- mostly for
 * use in determining how tapes really work.
 *
 * Note, this program reads stored.conf, and will only
 * talk to devices that are configured.
 */

#include "include/bareos.h"
#include "stored/stored.h"
#include "stored/stored_globals.h"
#include "lib/crypto_cache.h"
#include "stored/acquire.h"
#include "stored/autochanger.h"
#include "stored/bsr.h"
#include "stored/btape_device_control_record.h"
#include "stored/butil.h"
#include "stored/device.h"
#include "stored/stored_jcr_impl.h"
#include "stored/label.h"
#include "stored/read_record.h"
#include "stored/sd_backends.h"
#include "lib/address_conf.h"
#include "lib/berrno.h"
#include "lib/cli.h"
#include "lib/edit.h"
#include "lib/bsignal.h"
#include "lib/recent_job_results_list.h"
#include "lib/parse_bsr.h"
#include "lib/parse_conf.h"
#include "lib/util.h"
#include "lib/watchdog.h"
#include "include/jcr.h"

inline void read_with_check(int fd, void* buf, size_t count)
{
  if (read(fd, buf, count) < 0) {
    BErrNo be;
    Emsg1(M_FATAL, 0, _("read failed: %s\n"), be.bstrerror());
  }
}

inline void write_with_check(int fd, void* buf, size_t count)
{
  if (write(fd, buf, count) < 0) {
    BErrNo be;
    Emsg1(M_FATAL, 0, _("write failed: %s\n"), be.bstrerror());
  }
}

namespace storagedaemon {
extern bool ParseSdConfig(const char* configfile, int exit_code);
}

using namespace storagedaemon;

static int quit = 0;
static char buf[100'000];

/**
 * If you change the format of the state file,
 *  increment this value
 */
static uint32_t btape_state_level = 2;

static Device* dev = nullptr;
static DeviceControlRecord* dcr;
static int exit_code = 0;

#define REC_SIZE 32768

/* Forward referenced subroutines */
static void do_tape_cmds();
static void HelpCmd();
static void scancmd();
static void rewindcmd();
static void clearcmd();
static void wrcmd();
static void rrcmd();
static void rbcmd();
static void eodcmd();
static void fillcmd();
static void qfillcmd();
static void statcmd();
static void unfillcmd();
static int FlushBlock(DeviceBlock* block);
static bool QuickieCb(DeviceControlRecord* dcr, DeviceRecord* rec);
static bool CompareBlocks(DeviceBlock* last_block, DeviceBlock* block);
static bool MyMountNextReadVolume(DeviceControlRecord* dcr);
static void scan_blocks();
static void SetVolumeName(const char* VolName, int volnum);
static void rawfill_cmd();
static bool open_the_device();
static void autochangercmd();
static bool do_unfill();

/* Static variables */

#define MAX_CMD_ARGS 30

static POOLMEM* cmd;
static POOLMEM* args;
static char* argk[MAX_CMD_ARGS];
static char* argv[MAX_CMD_ARGS];
static int argc;

static int quickie_count = 0;
static uint64_t write_count = 0;
static BootStrapRecord* bsr = nullptr;
static bool signals = true;
static bool ok;
static int stop = 0;
static uint64_t vol_size;
static uint64_t VolBytes;
static time_t now;
static int32_t file_index;
static int end_of_tape = 0;
static uint32_t LastBlock = 0;
static uint32_t eot_block;
static uint32_t eot_block_len;
static uint32_t eot_FileIndex;
static int dumped = 0;
static DeviceBlock* last_block1 = nullptr;
static DeviceBlock* last_block2 = nullptr;
static DeviceBlock* last_block = nullptr;
static DeviceBlock* this_block = nullptr;
static DeviceBlock* first_block = nullptr;
static uint32_t last_file1 = 0;
static uint32_t last_file2 = 0;
static uint32_t last_file = 0;
static uint32_t last_block_num1 = 0;
static uint32_t last_block_num2 = 0;
static uint32_t last_block_num = 0;
static uint32_t BlockNumber = 0;
static bool simple = true;

static const char* volumename = nullptr;
static int vol_num = 0;

static JobControlRecord* jcr = nullptr;

static std::string Generate_interactive_commands_help();
static void TerminateBtape(int sig);
int GetCmd(const char* prompt);


/**
 *
 * Bareos tape testing program
 *
 */
int main(int margc, char* margv[])
{
  setlocale(LC_ALL, "");
  tzset();
  bindtextdomain("bareos", LOCALEDIR);
  textdomain("bareos");
  InitStackDump();

  /* Sanity checks */
  if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
    Emsg2(M_ABORT, 0,
          _("Tape block size (%d) not multiple of system size (%d)\n"),
          TAPE_BSIZE, B_DEV_BSIZE);
  }
  if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE) - 1))) {
    Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"),
          TAPE_BSIZE);
  }
  if (sizeof(boffset_t) < 8) {
    Pmsg1(-1,
          _("\n\n!!!! Warning large disk addressing disabled. boffset_t=%d "
            "should be 8 or more !!!!!\n\n\n"),
          sizeof(boffset_t));
  }

  uint32_t x32 = 123456789;
  uint32_t y32;
  char buf[1'000];
  Bsnprintf(buf, sizeof(buf), "%u", x32);
  int i = bsscanf(buf, "%lu", &y32);
  if (i != 1 || x32 != y32) {
    Pmsg3(-1, _("32 bit printf/scanf problem. i=%d x32=%u y32=%u\n"), i, x32,
          y32);
    exit(1);
  }

  uint64_t x64 = 123456789;
  x64 = x64 << 32;
  x64 += 123456789;
  Bsnprintf(buf, sizeof(buf), "%llu", x64);

  uint64_t y64;
  i = bsscanf(buf, "%llu", &y64);
  if (i != 1 || x64 != y64) {
    Pmsg3(-1, _("64 bit printf/scanf problem. i=%d x64=%llu y64=%llu\n"), i,
          x64, y64);
    exit(1);
  }

  working_directory = "/tmp";
  MyNameIs(margc, margv, "btape");
  InitMsg(nullptr, nullptr);

  OSDependentInit();

  CLI::App btape_app;
  InitCLIApp(btape_app, "The Bareos Tape Manipulation tool.", 2000);

  btape_app
      .add_option(
          "-b,--parse-bootstrap",
          [](std::vector<std::string> vals) {
            bsr = libbareos::parse_bsr(nullptr, vals.front().data());
            return true;
          },
          "Specify a bootstrap file.")
      ->check(CLI::ExistingFile)
      ->type_name("<file>");

  btape_app
      .add_option(
          "-c,--config",
          [](std::vector<std::string> val) {
            if (configfile != nullptr) { free(configfile); }
            configfile = strdup(val.front().c_str());
            return true;
          },
          "Specify a configuration file or directory.")
      ->check(CLI::ExistingPath)
      ->type_name("<path>");

  std::string DirectorName;
  btape_app
      .add_option("-D,--director", DirectorName,
                  "Specify a director name specified in the storage.\n"
                  "Configuration file for the Key Encryption Key selection.")
      ->type_name("<director>");

  AddDebugOptions(btape_app);

  btape_app.add_flag("-p,--proceed-io", forge_on,
                     "Proceed inspite of IO errors");

  btape_app.add_flag("-s{false},--no-signals{false}", signals,
                     "Turn off signals.");

  AddVerboseOption(btape_app);

  std::string archive_name;
  btape_app
      .add_option("bareos-archive-device-name", archive_name,
                  "Specify the input device name (either as name of a Bareos "
                  "Storage Daemon Device resource or identical to the Archive "
                  "Device in a Bareos Storage Daemon Device resource).")
      ->required()
      ->type_name(" ");

  btape_app.add_option_group("Interactive commands",
                             Generate_interactive_commands_help());

  CLI11_PARSE(btape_app, margc, margv)

  printf(_("Tape block granularity is %d bytes.\n"), TAPE_BSIZE);

  cmd = GetPoolMemory(PM_FNAME);
  args = GetPoolMemory(PM_FNAME);

  if (signals) { InitSignals(TerminateBtape); }

  daemon_start_time = time(nullptr);

  my_config = InitSdConfig(configfile, M_ERROR_TERM);
  ParseSdConfig(configfile, M_ERROR_TERM);

  DirectorResource* director = nullptr;
  if (!DirectorName.empty()) {
    foreach_res (director, R_DIRECTOR) {
      if (bstrcmp(director->resource_name_, DirectorName.c_str())) { break; }
    }
    if (!director) {
      Emsg2(M_ERROR_TERM, 0,
            _("No Director resource named %s defined in %s. Cannot "
              "continue.\n"),
            DirectorName.c_str(), configfile);
    }
  }

  LoadSdPlugins(me->plugin_directory, me->plugin_names);

  ReadCryptoCache(me->working_directory, "bareos-sd",
                  GetFirstPortHostOrder(me->SDaddrs));

  dcr = new BTAPE_DCR;
  jcr = SetupJcr("btape", archive_name.data(), bsr, director, dcr, "",
                 false); /* write device */
  if (!jcr) { exit(1); }

  dev = jcr->sd_impl->dcr->dev;
  if (!dev) { exit(1); }

  if (!dev->IsTape()) {
    Pmsg0(000, _("btape only works with tape storage.\n"));
    exit(1);
  }

  if (!open_the_device()) { exit(1); }

  Dmsg0(200, "Do tape commands\n");
  do_tape_cmds();

  TerminateBtape(exit_code);
}

static void TerminateBtape(int status)
{
  FreeJcr(jcr);
  jcr = nullptr;

  if (args) {
    FreePoolMemory(args);
    args = nullptr;
  }

  if (cmd) {
    FreePoolMemory(cmd);
    cmd = nullptr;
  }

  if (bsr) { libbareos::FreeBsr(bsr); }

  FreeVolumeLists();

  if (dev) { delete dev; }

  if (configfile) { free(configfile); }

  if (my_config) {
    delete my_config;
    my_config = nullptr;
  }

  if (this_block) {
    FreeBlock(this_block);
    this_block = nullptr;
  }

  StopWatchdog();
  TermMsg();
  RecentJobResultsList::Cleanup();
  CleanupJcrChain();

  exit(status);
}


btime_t total_time = 0;
uint64_t total_size = 0;

static void init_total_speed()
{
  total_size = 0;
  total_time = 0;
}

static void print_total_speed()
{
  char ec1[50], ec2[50];
  uint64_t rate = total_size / total_time;
  Pmsg2(000, _("Total Volume bytes=%sB. Total Write rate = %sB/s\n"),
        edit_uint64_with_suffix(total_size, ec1),
        edit_uint64_with_suffix(rate, ec2));
}

static void init_speed()
{
  time(&jcr->run_time); /* start counting time for rates */
  jcr->JobBytes = 0;
}

static void PrintSpeed(uint64_t bytes)
{
  char ec1[50], ec2[50];
  uint64_t rate;

  now = time(nullptr);
  now -= jcr->run_time;
  if (now <= 0) { now = 1; /* don't divide by zero */ }

  total_time += now;
  total_size += bytes;

  rate = bytes / now;
  Pmsg2(000, _("Volume bytes=%sB. Write rate = %sB/s\n"),
        edit_uint64_with_suffix(bytes, ec1),
        edit_uint64_with_suffix(rate, ec2));
}

// Helper that fill a buffer with random data or not
typedef enum
{
  FILL_RANDOM,
  FILL_ZERO
} fill_mode_t;

static void FillBuffer(fill_mode_t mode, char* buf, uint32_t len)
{
  int fd;
  switch (mode) {
    case FILL_RANDOM:
      fd = open("/dev/urandom", O_RDONLY);
      if (fd != -1) {
        read_with_check(fd, buf, len);
        close(fd);
      } else {
        uint32_t* p = (uint32_t*)buf;
        srandom(time(nullptr));
        for (uint32_t i = 0; i < len / sizeof(uint32_t); i++) {
          p[i] = random();
        }
      }
      break;

    case FILL_ZERO:
      memset(buf, 0xFF, len);
      break;

    default:
      ASSERT(0);
  }
}

static void MixBuffer(fill_mode_t mode, char* data, uint32_t len)
{
  uint32_t i;
  uint32_t* lp = (uint32_t*)data;

  if (mode == FILL_ZERO) { return; }

  lp[0] += lp[13];
  for (i = 1; i < (len - sizeof(uint32_t)) / sizeof(uint32_t) - 1; i += 100) {
    lp[i] += lp[0];
  }
}

static bool open_the_device()
{
  DeviceBlock* block;
  bool ok = true;

  block = new_block(dev);
  dev->rLock();
  Dmsg1(200, "Opening device %s\n", dcr->VolumeName);
  if (!dev->open(dcr, DeviceMode::OPEN_READ_WRITE)) {
    Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
    ok = false;
    goto bail_out;
  }
  Pmsg1(000, _("open device %s: OK\n"), dev->print_name());
  dev->SetAppend(); /* put volume in append mode */

bail_out:
  dev->Unlock();
  FreeBlock(block);
  return ok;
}


void QuitCmd() { quit = 1; }

// Write a label to the tape
static void labelcmd()
{
  if (volumename) {
    PmStrcpy(cmd, volumename);
  } else {
    if (!GetCmd(_("Enter Volume Name: "))) { return; }
  }

  if (!dev->IsOpen()) {
    if (!FirstOpenDevice(dcr)) {
      Pmsg1(0, _("Device open failed. ERR=%s\n"), dev->bstrerror());
    }
  }
  dev->rewind(dcr);
  WriteNewVolumeLabelToDev(dcr, cmd, "Default", false /*no relabel*/);
  Pmsg1(-1, _("Wrote Volume label for volume \"%s\".\n"), cmd);
}

// Read the tape label
static void readlabelcmd()
{
  int save_debug_level = debug_level;
  int status;

  status = ReadDevVolumeLabel(dcr);
  switch (status) {
    case VOL_NO_LABEL:
      Pmsg0(0, _("Volume has no label.\n"));
      break;
    case VOL_OK:
      Pmsg0(0, _("Volume label read correctly.\n"));
      debug_level = 20;
      DumpVolumeLabel(dev);
      break;
    case VOL_IO_ERROR:
      Pmsg1(0, _("I/O error on device: ERR=%s"), dev->bstrerror());
      break;
    case VOL_NAME_ERROR:
      Pmsg0(0, _("Volume name error\n"));
      break;
    case VOL_CREATE_ERROR:
      Pmsg1(0, _("Error creating label. ERR=%s"), dev->bstrerror());
      break;
    case VOL_VERSION_ERROR:
      Pmsg0(0, _("Volume version error.\n"));
      break;
    case VOL_LABEL_ERROR:
      Pmsg0(0, _("Bad Volume label type.\n"));
      break;
    default:
      Pmsg0(0, _("Unknown error.\n"));
      break;
  }
  debug_level = save_debug_level;
}


/**
 * Load the tape should have prevously been taken
 * off line, otherwise this command is not necessary.
 */
static void loadcmd()
{
  if (!dev->LoadDev()) {
    Pmsg1(0, _("Bad status from load. ERR=%s\n"), dev->bstrerror());
  } else
    Pmsg1(0, _("Loaded %s\n"), dev->print_name());
}

// Rewind the tape.
static void rewindcmd()
{
  if (!dev->rewind(dcr)) {
    Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
    dev->clrerror(-1);
  } else {
    Pmsg1(0, _("Rewound %s\n"), dev->print_name());
  }
}

// Clear any tape error
static void clearcmd() { dev->clrerror(-1); }

// Write and end of file on the tape
static void weofcmd()
{
  int num = 1;
  if (argc > 1) { num = atoi(argk[1]); }
  if (num <= 0) { num = 1; }

  if (!dev->weof(num)) {
    Pmsg1(0, _("Bad status from weof. ERR=%s\n"), dev->bstrerror());
    return;
  } else {
    if (num == 1) {
      Pmsg1(0, _("Wrote 1 EOF to %s\n"), dev->print_name());
    } else {
      Pmsg2(0, _("Wrote %d EOFs to %s\n"), num, dev->print_name());
    }
  }
}


/* Go to the end of the medium -- raw command
 * The idea was orginally that the end of the Bareos
 * medium would be flagged differently. This is not
 * currently the case. So, this is identical to the
 * eodcmd().
 */
static void eomcmd()
{
  if (!dev->eod(dcr)) {
    Pmsg1(0, "%s", dev->bstrerror());
    return;
  } else {
    Pmsg0(0, _("Moved to end of medium.\n"));
  }
}

/**
 * Go to the end of the medium (either hardware determined
 *  or defined by two eofs.
 */
static void eodcmd() { eomcmd(); }

// Backspace file
static void bsfcmd()
{
  int num = 1;
  if (argc > 1) { num = atoi(argk[1]); }
  if (num <= 0) { num = 1; }

  if (!dev->bsf(num)) {
    Pmsg1(0, _("Bad status from bsf. ERR=%s\n"), dev->bstrerror());
  } else {
    Pmsg2(0, _("Backspaced %d file%s.\n"), num, num == 1 ? "" : "s");
  }
}

// Backspace record
static void bsrcmd()
{
  int num = 1;
  if (argc > 1) { num = atoi(argk[1]); }
  if (num <= 0) { num = 1; }
  if (!dev->bsr(num)) {
    Pmsg1(0, _("Bad status from bsr. ERR=%s\n"), dev->bstrerror());
  } else {
    Pmsg2(0, _("Backspaced %d record%s.\n"), num, num == 1 ? "" : "s");
  }
}

// List device capabilities as defined in the stored.conf file.
static void capcmd()
{
  printf(_("Configured device capabilities:\n"));
  printf("%sEOF ", dev->HasCap(CAP_EOF) ? "" : "!");
  printf("%sBSR ", dev->HasCap(CAP_BSR) ? "" : "!");
  printf("%sBSF ", dev->HasCap(CAP_BSF) ? "" : "!");
  printf("%sFSR ", dev->HasCap(CAP_FSR) ? "" : "!");
  printf("%sFSF ", dev->HasCap(CAP_FSF) ? "" : "!");
  printf("%sFASTFSF ", dev->HasCap(CAP_FASTFSF) ? "" : "!");
  printf("%sBSFATEOM ", dev->HasCap(CAP_BSFATEOM) ? "" : "!");
  printf("%sEOM ", dev->HasCap(CAP_EOM) ? "" : "!");
  printf("%sREM ", dev->HasCap(CAP_REM) ? "" : "!");
  printf("%sRACCESS ", dev->HasCap(CAP_RACCESS) ? "" : "!");
  printf("%sAUTOMOUNT ", dev->HasCap(CAP_AUTOMOUNT) ? "" : "!");
  printf("%sLABEL ", dev->HasCap(CAP_LABEL) ? "" : "!");
  printf("%sANONVOLS ", dev->HasCap(CAP_ANONVOLS) ? "" : "!");
  printf("%sALWAYSOPEN ", dev->HasCap(CAP_ALWAYSOPEN) ? "" : "!");
  printf("%sMTIOCGET ", dev->HasCap(CAP_MTIOCGET) ? "" : "!");
  printf("\n");

  printf(_("Device status:\n"));
  printf("%sOPENED ", dev->IsOpen() ? "" : "!");
  printf("%sTAPE ", dev->IsTape() ? "" : "!");
  printf("%sLABEL ", dev->IsLabeled() ? "" : "!");
  printf("%sMALLOC ", BitIsSet(ST_ALLOCATED, dev->state) ? "" : "!");
  printf("%sAPPEND ", dev->CanAppend() ? "" : "!");
  printf("%sREAD ", dev->CanRead() ? "" : "!");
  printf("%sEOT ", dev->AtEot() ? "" : "!");
  printf("%sWEOT ", BitIsSet(ST_WEOT, dev->state) ? "" : "!");
  printf("%sEOF ", dev->AtEof() ? "" : "!");
  printf("%sNEXTVOL ", BitIsSet(ST_NEXTVOL, dev->state) ? "" : "!");
  printf("%sSHORT ", BitIsSet(ST_SHORT, dev->state) ? "" : "!");
  printf("\n");

  printf(_("Device parameters:\n"));
  printf("Device name: %s\n", dev->archive_device_string);
  printf("File=%u block=%u\n", dev->file, dev->block_num);
  printf("Min block=%u Max block=%u\n", dev->min_block_size,
         dev->max_block_size);

  printf(_("Status:\n"));
  statcmd();
}

/**
 * Test writing larger and larger records.
 * This is a torture test for records.
 */
static void rectestcmd()
{
  DeviceBlock* save_block;
  DeviceRecord* rec;
  int i, blkno = 0;

  Pmsg0(0,
        _("Test writing larger and larger records.\n"
          "This is a torture test for records.\nI am going to write\n"
          "larger and larger records. It will stop when the record size\n"
          "plus the header exceeds the block size (by default about 64K)\n"));


  GetCmd(_("Do you want to continue? (y/n): "));
  if (cmd[0] != 'y') {
    Pmsg0(000, _("Command aborted.\n"));
    return;
  }

  save_block = dcr->block;
  dcr->block = new_block(dev);
  rec = new_record();

  for (i = 1; i < 500000; i++) {
    rec->data = CheckPoolMemorySize(rec->data, i);
    memset(rec->data, i & 0xFF, i);
    rec->data_len = i;
    if (WriteRecordToBlock(dcr, rec)) {
      EmptyBlock(dcr->block);
      blkno++;
      Pmsg2(0, _("Block %d i=%d\n"), blkno, i);
    } else {
      break;
    }
  }
  FreeRecord(rec);
  FreeBlock(dcr->block);
  dcr->block = save_block; /* restore block to dcr */
}

/**
 * This test attempts to re-read a block written by Bareos
 *   normally at the end of the tape. Bareos will then back up
 *   over the two eof marks, backup over the record and reread
 *   it to make sure it is valid.  Bareos can skip this validation
 *   if you set "Backward space record = no"
 */
static bool re_read_block_test()
{
  DeviceBlock* block = dcr->block;
  DeviceRecord* rec;
  bool rc = false;
  int len;

  if (!dev->HasCap(CAP_BSR)) {
    Pmsg0(-1, _("Skipping read backwards test because BootStrapRecord turned "
                "off.\n"));
    return true;
  }

  Pmsg0(-1, _("\n=== Write, backup, and re-read test ===\n\n"
              "I'm going to write three records and an EOF\n"
              "then backup over the EOF and re-read the last record.\n"
              "Bareos does this after writing the last block on the\n"
              "tape to verify that the block was written correctly.\n\n"
              "This is not an *essential* feature ...\n\n"));
  rewindcmd();
  EmptyBlock(block);
  rec = new_record();
  rec->data = CheckPoolMemorySize(rec->data, block->buf_len);
  len = rec->data_len = block->buf_len - 100;
  memset(rec->data, 1, rec->data_len);
  if (!WriteRecordToBlock(dcr, rec)) {
    Pmsg0(0, _("Error writing record to block.\n"));
    goto bail_out;
  }
  if (!dcr->WriteBlockToDev()) {
    Pmsg0(0, _("Error writing block to device.\n"));
    goto bail_out;
  } else {
    Pmsg1(0, _("Wrote first record of %d bytes.\n"), rec->data_len);
  }
  memset(rec->data, 2, rec->data_len);
  if (!WriteRecordToBlock(dcr, rec)) {
    Pmsg0(0, _("Error writing record to block.\n"));
    goto bail_out;
  }
  if (!dcr->WriteBlockToDev()) {
    Pmsg0(0, _("Error writing block to device.\n"));
    goto bail_out;
  } else {
    Pmsg1(0, _("Wrote second record of %d bytes.\n"), rec->data_len);
  }
  memset(rec->data, 3, rec->data_len);
  if (!WriteRecordToBlock(dcr, rec)) {
    Pmsg0(0, _("Error writing record to block.\n"));
    goto bail_out;
  }
  if (!dcr->WriteBlockToDev()) {
    Pmsg0(0, _("Error writing block to device.\n"));
    goto bail_out;
  } else {
    Pmsg1(0, _("Wrote third record of %d bytes.\n"), rec->data_len);
  }
  weofcmd();
  if (dev->HasCap(CAP_TWOEOF)) { weofcmd(); }
  if (!dev->bsf(1)) {
    Pmsg1(0, _("Backspace file failed! ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  if (dev->HasCap(CAP_TWOEOF)) {
    if (!dev->bsf(1)) {
      Pmsg1(0, _("Backspace file failed! ERR=%s\n"), dev->bstrerror());
      goto bail_out;
    }
  }
  Pmsg0(0, _("Backspaced over EOF OK.\n"));
  if (!dev->bsr(1)) {
    Pmsg1(0, _("Backspace record failed! ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg0(0, _("Backspace record OK.\n"));
  if (DeviceControlRecord::ReadStatus::Ok
      != dcr->ReadBlockFromDev(NO_BLOCK_NUMBER_CHECK)) {
    BErrNo be;
    Pmsg1(0, _("Read block failed! ERR=%s\n"), be.bstrerror(dev->dev_errno));
    goto bail_out;
  }
  memset(rec->data, 0, rec->data_len);
  if (!ReadRecordFromBlock(dcr, rec)) {
    BErrNo be;
    Pmsg1(0, _("Read block failed! ERR=%s\n"), be.bstrerror(dev->dev_errno));
    goto bail_out;
  }
  for (int i = 0; i < len; i++) {
    if (rec->data[i] != 3) {
      Pmsg0(0, _("Bad data in record. Test failed!\n"));
      goto bail_out;
    }
  }
  Pmsg0(0, _("\nBlock re-read correct. Test succeeded!\n"));
  Pmsg0(-1, _("=== End Write, backup, and re-read test ===\n\n"));

  rc = true;

bail_out:
  FreeRecord(rec);
  if (!rc) {
    Pmsg0(0, _("This is not terribly serious since Bareos only uses\n"
               "this function to verify the last block written to the\n"
               "tape. Bareos will skip the last block verification\n"
               "if you add:\n\n"
               "Backward Space Record = No\n\n"
               "to your Storage daemon's Device resource definition.\n"));
  }
  return rc;
}

static bool SpeedTestRaw(fill_mode_t mode, uint64_t nb_gb, uint32_t nb)
{
  DeviceBlock* block = dcr->block;
  int status;
  uint32_t block_num = 0;
  int my_errno;
  char ed1[200];
  nb_gb *= 1024 * 1024 * 1024; /* convert size from nb to GB */

  init_total_speed();
  FillBuffer(mode, block->buf, block->buf_len);

  Pmsg3(0, _("Begin writing %i files of %sB with raw blocks of %u bytes.\n"),
        nb, edit_uint64_with_suffix(nb_gb, ed1), block->buf_len);

  for (uint32_t j = 0; j < nb; j++) {
    init_speed();
    for (; jcr->JobBytes < nb_gb;) {
      status = dev->d_write(dev->fd, block->buf, block->buf_len);
      if (status == (int)block->buf_len) {
        if ((block_num++ % 500) == 0) {
          printf("+");
          fflush(stdout);
        }

        MixBuffer(mode, block->buf, block->buf_len);

        jcr->JobBytes += status;

      } else {
        my_errno = errno;
        printf("\n");
        BErrNo be;
        printf(_("Write failed at block %u. status=%d ERR=%s\n"), block_num,
               status, be.bstrerror(my_errno));
        return false;
      }
    }
    printf("\n");
    weofcmd();
    PrintSpeed(jcr->JobBytes);
  }
  print_total_speed();
  printf("\n");
  return true;
}


static bool SpeedTestBareos(fill_mode_t mode, uint64_t nb_gb, uint32_t nb)
{
  DeviceBlock* block = dcr->block;
  char ed1[200];
  DeviceRecord* rec;
  uint64_t last_bytes = dev->VolCatInfo.VolCatBytes;
  uint64_t written = 0;

  nb_gb *= 1024 * 1024 * 1024; /* convert size from nb to GB */

  init_total_speed();

  EmptyBlock(block);
  rec = new_record();
  rec->data = CheckPoolMemorySize(rec->data, block->buf_len);
  rec->data_len = block->buf_len - 100;

  FillBuffer(mode, rec->data, rec->data_len);

  Pmsg3(0, _("Begin writing %i files of %sB with blocks of %u bytes.\n"), nb,
        edit_uint64_with_suffix(nb_gb, ed1), block->buf_len);

  for (uint32_t j = 0; j < nb; j++) {
    written = 0;
    init_speed();
    for (; written < nb_gb;) {
      if (!WriteRecordToBlock(dcr, rec)) {
        Pmsg0(0, _("\nError writing record to block.\n"));
        goto bail_out;
      }
      if (!dcr->WriteBlockToDev()) {
        Pmsg0(0, _("\nError writing block to device.\n"));
        goto bail_out;
      }

      if ((block->BlockNumber % 500) == 0) {
        printf("+");
        fflush(stdout);
      }
      written += dev->VolCatInfo.VolCatBytes - last_bytes;
      last_bytes = dev->VolCatInfo.VolCatBytes;
      MixBuffer(mode, rec->data, rec->data_len);
    }
    printf("\n");
    weofcmd();
    PrintSpeed(written);
  }
  print_total_speed();
  printf("\n");
  FreeRecord(rec);
  return true;

bail_out:
  FreeRecord(rec);
  return false;
}

/* TODO: use UaContext */
static int BtapeFindArg(const char* keyword)
{
  for (int i = 1; i < argc; i++) {
    if (Bstrcasecmp(keyword, argk[i])) { return i; }
  }
  return -1;
}

#define ok(a) \
  if (!(a)) return

/**
 * For file (/dev/zero, /dev/urandom, normal?)
 *    use raw mode to write a suite of 3 files of 1, 2, 4, 8 GB
 *    use qfill mode to write the same
 *
 */
static void speed_test()
{
  bool do_zero = true, do_random = true, do_block = true, do_raw = true;
  uint32_t file_size = 0, nb_file = 3;
  int32_t i;

  i = BtapeFindArg("file_size");
  if (i > 0) {
    file_size = atoi(argv[i]);
    if (file_size > 100) {
      Pmsg0(0, _("The file_size is too big, stop this test with Ctrl-c.\n"));
    }
  }

  i = BtapeFindArg("nb_file");
  if (i > 0) { nb_file = atoi(argv[i]); }

  if (BtapeFindArg("skip_zero") > 0) { do_zero = false; }

  if (BtapeFindArg("skip_random") > 0) { do_random = false; }

  if (BtapeFindArg("skip_raw") > 0) { do_raw = false; }

  if (BtapeFindArg("skip_block") > 0) { do_block = false; }

  if (do_raw) {
    dev->rewind(dcr);
    if (do_zero) {
      Pmsg0(0, _("Test with zero data, should give the "
                 "maximum throughput.\n"));
      if (file_size) {
        ok(SpeedTestRaw(FILL_ZERO, file_size, nb_file));
      } else {
        ok(SpeedTestRaw(FILL_ZERO, 1, nb_file));
        ok(SpeedTestRaw(FILL_ZERO, 2, nb_file));
        ok(SpeedTestRaw(FILL_ZERO, 4, nb_file));
      }
    }

    if (do_random) {
      Pmsg0(0, _("Test with random data, should give the minimum "
                 "throughput.\n"));
      if (file_size) {
        ok(SpeedTestRaw(FILL_RANDOM, file_size, nb_file));
      } else {
        ok(SpeedTestRaw(FILL_RANDOM, 1, nb_file));
        ok(SpeedTestRaw(FILL_RANDOM, 2, nb_file));
        ok(SpeedTestRaw(FILL_RANDOM, 4, nb_file));
      }
    }
  }

  if (do_block) {
    dev->rewind(dcr);
    if (do_zero) {
      Pmsg0(0, _("Test with zero data and bareos block structure.\n"));
      if (file_size) {
        ok(SpeedTestBareos(FILL_ZERO, file_size, nb_file));
      } else {
        ok(SpeedTestBareos(FILL_ZERO, 1, nb_file));
        ok(SpeedTestBareos(FILL_ZERO, 2, nb_file));
        ok(SpeedTestBareos(FILL_ZERO, 4, nb_file));
      }
    }

    if (do_random) {
      Pmsg0(0, _("Test with random data, should give the minimum "
                 "throughput.\n"));
      if (file_size) {
        ok(SpeedTestBareos(FILL_RANDOM, file_size, nb_file));
      } else {
        ok(SpeedTestBareos(FILL_RANDOM, 1, nb_file));
        ok(SpeedTestBareos(FILL_RANDOM, 2, nb_file));
        ok(SpeedTestBareos(FILL_RANDOM, 4, nb_file));
      }
    }
  }
}

const uint64_t num_recs = 10'000LL;

static bool write_two_files()
{
  DeviceBlock* block;
  DeviceRecord* rec;
  uint32_t len;
  uint32_t* p;
  bool rc = false; /* bad return code */
  Device* dev = dcr->dev;

  /*
   * Set big max_file_size so that write_record_to_block
   * doesn't insert any additional EOF marks
   */
  if (dev->max_block_size) {
    dev->max_file_size = 2LL * num_recs * (uint64_t)dev->max_block_size;
  } else {
    dev->max_file_size = 2LL * num_recs * (uint64_t)DEFAULT_BLOCK_SIZE;
  }
  Dmsg1(100, "max_file_size was set to %lld\n", dev->max_file_size);

  Pmsg2(-1,
        _("\n=== Write, rewind, and re-read test ===\n\n"
          "I'm going to write %d records and an EOF\n"
          "then write %d records and an EOF, then rewind,\n"
          "and re-read the data to verify that it is correct.\n\n"
          "This is an *essential* feature ...\n\n"),
        num_recs, num_recs);

  block = dcr->block;
  EmptyBlock(block);
  rec = new_record();
  rec->data = CheckPoolMemorySize(rec->data, block->buf_len);
  rec->data_len = block->buf_len - 100;
  len = rec->data_len / sizeof(uint32_t);

  if (!dev->rewind(dcr)) {
    Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }

  for (uint32_t i = 1; i <= num_recs; i++) {
    p = (uint32_t*)rec->data;
    for (uint32_t j = 0; j < len; j++) { *p++ = i; }
    if (!WriteRecordToBlock(dcr, rec)) {
      Pmsg0(0, _("Error writing record to block.\n"));
      goto bail_out;
    }
    if (!dcr->WriteBlockToDev()) {
      Pmsg0(0, _("Error writing block to device.\n"));
      goto bail_out;
    }
  }
  Pmsg2(0, _("Wrote %d blocks of %d bytes.\n"), num_recs, rec->data_len);
  weofcmd();
  for (uint32_t i = num_recs + 1; i <= 2 * num_recs; i++) {
    p = (uint32_t*)rec->data;
    for (uint32_t j = 0; j < len; j++) { *p++ = i; }
    if (!WriteRecordToBlock(dcr, rec)) {
      Pmsg0(0, _("Error writing record to block.\n"));
      goto bail_out;
    }
    if (!dcr->WriteBlockToDev()) {
      Pmsg0(0, _("Error writing block to device.\n"));
      goto bail_out;
    }
  }
  Pmsg2(0, _("Wrote %d blocks of %d bytes.\n"), num_recs, rec->data_len);
  weofcmd();
  if (dev->HasCap(CAP_TWOEOF)) { weofcmd(); }
  rc = true;

bail_out:
  FreeRecord(rec);
  if (!rc) { exit_code = 1; }

  return rc;
}

/**
 * This test writes Bareos blocks to the tape in
 * several files. It then rewinds the tape and attepts
 * to read these blocks back checking the data.
 */
static bool write_read_test()
{
  DeviceBlock* block;
  DeviceRecord* rec;
  bool rc = false;
  uint32_t len;
  uint32_t* p;

  rec = new_record();

  if (!write_two_files()) { goto bail_out; }

  block = dcr->block;
  EmptyBlock(block);

  if (!dev->rewind(dcr)) {
    Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  } else {
    Pmsg0(0, _("Rewind OK.\n"));
  }

  rec->data = CheckPoolMemorySize(rec->data, block->buf_len);
  rec->data_len = block->buf_len - 100;
  len = rec->data_len / sizeof(uint32_t);

  // Now read it back
  for (uint32_t i = 1; i <= 2 * num_recs; i++) {
  read_again:
    if (DeviceControlRecord::ReadStatus::Ok
        != dcr->ReadBlockFromDev(NO_BLOCK_NUMBER_CHECK)) {
      BErrNo be;
      if (dev->AtEof()) {
        Pmsg0(-1, _("Got EOF on tape.\n"));
        if (i == num_recs + 1) { goto read_again; }
      }
      Pmsg2(0, _("Read block %d failed! ERR=%s\n"), i,
            be.bstrerror(dev->dev_errno));
      goto bail_out;
    }
    memset(rec->data, 0, rec->data_len);
    if (!ReadRecordFromBlock(dcr, rec)) {
      BErrNo be;
      Pmsg2(0, _("Read record failed. Block %d! ERR=%s\n"), i,
            be.bstrerror(dev->dev_errno));
      goto bail_out;
    }
    p = (uint32_t*)rec->data;
    for (uint32_t j = 0; j < len; j++) {
      if (*p != i) {
        Pmsg3(0,
              _("Bad data in record. Expected %d, got %d at byte %d. Test "
                "failed!\n"),
              i, *p, j);
        goto bail_out;
      }
      p++;
    }
    if (i == num_recs || i == 2 * num_recs) {
      Pmsg1(-1, _("%d blocks re-read correctly.\n"), num_recs);
    }
  }
  Pmsg0(-1,
        _("=== Test Succeeded. End Write, rewind, and re-read test ===\n\n"));
  rc = true;

bail_out:
  FreeRecord(rec);
  if (!rc) { exit_code = 1; }
  return rc;
}

/**
 * This test writes Bareos blocks to the tape in
 * several files. It then rewinds the tape and attepts
 * to read these blocks back checking the data.
 */
static bool position_test()
{
  DeviceBlock* block = dcr->block;
  DeviceRecord* rec;
  bool rc = false;
  int len, j;
  bool more = true;
  int recno = 0;
  int file = 0, blk = 0;
  int* p;
  bool got_eof = false;

  Pmsg0(0, _("Block position test\n"));
  block = dcr->block;
  EmptyBlock(block);
  rec = new_record();
  rec->data = CheckPoolMemorySize(rec->data, block->buf_len);
  rec->data_len = block->buf_len - 100;
  len = rec->data_len / sizeof(j);

  if (!dev->rewind(dcr)) {
    Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  } else {
    Pmsg0(0, _("Rewind OK.\n"));
  }

  while (more) {
    /* Set up next item to read based on where we are */
    /* At each step, recno is what we print for the "block number"
     *  and file, blk are the real positions to go to.
     */
    switch (recno) {
      case 0:
        recno = 5;
        file = 0;
        blk = 4;
        break;
      case 5:
        recno = 201;
        file = 0;
        blk = 200;
        break;
      case 201:
        recno = num_recs;
        file = 0;
        blk = num_recs - 1;
        break;
      case num_recs:
        recno = num_recs + 1;
        file = 1;
        blk = 0;
        break;
      case num_recs + 1:
        recno = num_recs + 601;
        file = 1;
        blk = 600;
        break;
      case num_recs + 601:
        recno = 2 * num_recs;
        file = 1;
        blk = num_recs - 1;
        break;
      case 2 * num_recs:
        more = false;
        continue;
    }
    Pmsg2(-1, _("Reposition to file:block %d:%d\n"), file, blk);
    if (!dev->Reposition(dcr, file, blk)) {
      Pmsg0(0, _("Reposition error.\n"));
      goto bail_out;
    }
  read_again:
    if (DeviceControlRecord::ReadStatus::Ok
        != dcr->ReadBlockFromDev(NO_BLOCK_NUMBER_CHECK)) {
      BErrNo be;
      if (dev->AtEof()) {
        Pmsg0(-1, _("Got EOF on tape.\n"));
        if (!got_eof) {
          got_eof = true;
          goto read_again;
        }
      }
      Pmsg4(0, _("Read block %d failed! file=%d blk=%d. ERR=%s\n\n"), recno,
            file, blk, be.bstrerror(dev->dev_errno));
      Pmsg0(0, _("This may be because the tape drive block size is not\n"
                 " set to variable blocking as normally used by Bareos.\n"
                 " Please see the Tape Testing chapter in the manual and \n"
                 " look for using mt with defblksize and setoptions\n"
                 "If your tape drive block size is correct, then perhaps\n"
                 " your SCSI driver is *really* stupid and does not\n"
                 " correctly report the file:block after a FSF. In this\n"
                 " case try setting:\n"
                 "    Fast Forward Space File = no\n"
                 " in your Device resource.\n"));

      goto bail_out;
    }
    memset(rec->data, 0, rec->data_len);
    if (!ReadRecordFromBlock(dcr, rec)) {
      BErrNo be;
      Pmsg1(0, _("Read record failed! ERR=%s\n"), be.bstrerror(dev->dev_errno));
      goto bail_out;
    }
    p = (int*)rec->data;
    for (j = 0; j < len; j++) {
      if (p[j] != recno) {
        Pmsg3(0,
              _("Bad data in record. Expected %d, got %d at byte %d. Test "
                "failed!\n"),
              recno, p[j], j);
        goto bail_out;
      }
    }
    Pmsg1(-1, _("Block %d re-read correctly.\n"), recno);
  }
  Pmsg0(-1,
        _("=== Test Succeeded. End Write, rewind, and re-read test ===\n\n"));
  rc = true;

bail_out:
  FreeRecord(rec);
  return rc;
}


/**
 * This test writes some records, then writes an end of file,
 *   rewinds the tape, moves to the end of the data and attepts
 *   to append to the tape.  This function is essential for
 *   Bareos to be able to write multiple jobs to the tape.
 */
static int append_test()
{
  Pmsg0(-1, _("\n\n=== Append files test ===\n\n"
              "This test is essential to Bareos.\n\n"
              "I'm going to write one record  in file 0,\n"
              "                   two records in file 1,\n"
              "             and three records in file 2\n\n"));
  argc = 1;
  rewindcmd();
  wrcmd();
  weofcmd(); /* end file 0 */
  wrcmd();
  wrcmd();
  weofcmd(); /* end file 1 */
  wrcmd();
  wrcmd();
  wrcmd();
  weofcmd(); /* end file 2 */
  if (dev->HasCap(CAP_TWOEOF)) { weofcmd(); }
  dev->close(dcr); /* release device */
  if (!open_the_device()) { return -1; }
  rewindcmd();
  Pmsg0(0, _("Now moving to end of medium.\n"));
  eodcmd();
  Pmsg2(-1, _("We should be in file 3. I am at file %d. %s\n"), dev->file,
        dev->file == 3 ? _("This is correct!") : _("This is NOT correct!!!!"));

  if (dev->file != 3) { return -1; }

  Pmsg0(-1, _("\nNow the important part, I am going to attempt to append to "
              "the tape.\n\n"));
  wrcmd();
  weofcmd();
  if (dev->HasCap(CAP_TWOEOF)) { weofcmd(); }
  rewindcmd();
  Pmsg0(-1, _("Done appending, there should be no I/O errors\n\n"));
  Pmsg0(-1, _("Doing Bareos scan of blocks:\n"));
  scan_blocks();
  Pmsg0(-1, _("End scanning the tape.\n"));
  Pmsg2(-1, _("We should be in file 4. I am at file %d. %s\n"), dev->file,
        dev->file == 4 ? _("This is correct!") : _("This is NOT correct!!!!"));

  if (dev->file != 4) { return -2; }
  return 1;
}


// This test exercises the autochanger
static int autochanger_test()
{
  POOLMEM *results, *changer;
  slot_number_t slot, loaded;
  int status;
  int timeout = dcr->device_resource->max_changer_wait;
  int sleep_time = 0;

  Dmsg1(100, "Max changer wait = %d sec\n", timeout);
  if (!dev->HasCap(CAP_ATTACHED_TO_AUTOCHANGER)) { return 1; }
  if (!(dcr->device_resource && dcr->device_resource->changer_name
        && dcr->device_resource->changer_command)) {
    Pmsg0(-1, _("\nAutochanger enabled, but no name or no command device "
                "specified.\n"));
    return 1;
  }

  Pmsg0(-1, _("\nAh, I see you have an autochanger configured.\n"
              "To test the autochanger you must have a blank tape\n"
              " that I can write on in Slot 1.\n"));
  if (!GetCmd(
          _("\nDo you wish to continue with the Autochanger test? (y/n): "))) {
    return 0;
  }
  if (cmd[0] != 'y' && cmd[0] != 'Y') { return 0; }

  Pmsg0(-1, _("\n\n=== Autochanger test ===\n\n"));

  results = GetPoolMemory(PM_MESSAGE);
  changer = GetPoolMemory(PM_FNAME);

try_again:
  slot = 1;
  dcr->VolCatInfo.Slot = slot;
  /* Find out what is loaded, zero means device is unloaded */
  Pmsg0(-1, _("3301 Issuing autochanger \"loaded\" command.\n"));
  changer = edit_device_codes(dcr, changer,
                              dcr->device_resource->changer_command, "loaded");
  status = RunProgram(changer, timeout, results);
  Dmsg3(100, "run_prog: %s stat=%d result=\"%s\"\n", changer, status, results);
  if (status == 0) {
    loaded = atoi(results);
  } else {
    BErrNo be;
    Pmsg1(-1, _("3991 Bad autochanger command: %s\n"), changer);
    Pmsg2(-1, _("3991 result=\"%s\": ERR=%s\n"), results, be.bstrerror(status));
    goto bail_out;
  }
  if (loaded) {
    Pmsg1(-1, _("Slot %d loaded. I am going to unload it.\n"), loaded);
  } else {
    Pmsg0(-1, _("Nothing loaded in the drive. OK.\n"));
  }
  Dmsg1(100, "Results from loaded query=%s\n", results);
  if (loaded) {
    dcr->VolCatInfo.Slot = loaded;
    /* We are going to load a new tape, so close the device */
    dev->close(dcr);
    Pmsg2(-1, _("3302 Issuing autochanger \"unload %d %d\" command.\n"), loaded,
          dev->drive);
    changer = edit_device_codes(
        dcr, changer, dcr->device_resource->changer_command, "unload");
    status = RunProgram(changer, timeout, results);
    Pmsg2(-1, _("unload status=%s %d\n"), status == 0 ? _("OK") : _("Bad"),
          status);
    if (status != 0) {
      BErrNo be;
      Pmsg1(-1, _("3992 Bad autochanger command: %s\n"), changer);
      Pmsg2(-1, _("3992 result=\"%s\": ERR=%s\n"), results,
            be.bstrerror(status));
    }
  }

  // Load the Slot 1

  slot = 1;
  dcr->VolCatInfo.Slot = slot;
  Pmsg2(-1, _("3303 Issuing autochanger \"load %d %d\" command.\n"), slot,
        dev->drive);
  changer = edit_device_codes(dcr, changer,
                              dcr->device_resource->changer_command, "load");
  Dmsg1(100, "Changer=%s\n", changer);
  dev->close(dcr);
  status = RunProgram(changer, timeout, results);
  if (status == 0) {
    Pmsg2(-1, _("3303 Autochanger \"load %d %d\" status is OK.\n"), slot,
          dev->drive);
  } else {
    BErrNo be;
    Pmsg1(-1, _("3993 Bad autochanger command: %s\n"), changer);
    Pmsg2(-1, _("3993 result=\"%s\": ERR=%s\n"), results, be.bstrerror(status));
    goto bail_out;
  }

  if (!open_the_device()) { goto bail_out; }
  /*
   * Start with sleep_time 0 then increment by 30 seconds if we get
   * a failure.
   */
  Bmicrosleep(sleep_time, 0);
  if (!dev->rewind(dcr) || !dev->weof(1)) {
    Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
    dev->clrerror(-1);
    Pmsg0(-1, _("\nThe test failed, probably because you need to put\n"
                "a longer sleep time in the mtx-script in the load) case.\n"
                "Adding a 30 second sleep and trying again ...\n"));
    sleep_time += 30;
    goto try_again;
  } else {
    Pmsg1(0, _("Rewound %s\n"), dev->print_name());
  }

  if (!dev->weof(1)) {
    Pmsg1(0, _("Bad status from weof. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  } else {
    Pmsg1(0, _("Wrote EOF to %s\n"), dev->print_name());
  }

  if (sleep_time) {
    Pmsg1(-1,
          _("\nThe test worked this time. Please add:\n\n"
            "   sleep %d\n\n"
            "to your mtx-changer script in the load) case.\n\n"),
          sleep_time);
  } else {
    Pmsg0(-1, _("\nThe test autochanger worked!!\n\n"));
  }

  FreePoolMemory(changer);
  FreePoolMemory(results);
  return 1;


bail_out:
  FreePoolMemory(changer);
  FreePoolMemory(results);
  Pmsg0(-1,
        _("You must correct this error or the Autochanger will not work.\n"));
  return -2;
}

static void autochangercmd() { autochanger_test(); }


/**
 * This test assumes that the append test has been done,
 *   then it tests the fsf function.
 */
static bool fsf_test()
{
  bool set_off = false;

  Pmsg0(-1, _("\n\n=== Forward space files test ===\n\n"
              "This test is essential to Bareos.\n\n"
              "I'm going to write five files then test forward spacing\n\n"));
  argc = 1;
  rewindcmd();
  wrcmd();
  weofcmd(); /* end file 0 */
  wrcmd();
  wrcmd();
  weofcmd(); /* end file 1 */
  wrcmd();
  wrcmd();
  wrcmd();
  weofcmd(); /* end file 2 */
  wrcmd();
  wrcmd();
  weofcmd(); /* end file 3 */
  wrcmd();
  weofcmd(); /* end file 4 */
  if (dev->HasCap(CAP_TWOEOF)) { weofcmd(); }

test_again:
  rewindcmd();
  Pmsg0(0, _("Now forward spacing 1 file.\n"));
  if (!dev->fsf(1)) {
    Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg2(-1, _("We should be in file 1. I am at file %d. %s\n"), dev->file,
        dev->file == 1 ? _("This is correct!") : _("This is NOT correct!!!!"));

  if (dev->file != 1) { goto bail_out; }

  Pmsg0(0, _("Now forward spacing 2 files.\n"));
  if (!dev->fsf(2)) {
    Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg2(-1, _("We should be in file 3. I am at file %d. %s\n"), dev->file,
        dev->file == 3 ? _("This is correct!") : _("This is NOT correct!!!!"));

  if (dev->file != 3) { goto bail_out; }

  rewindcmd();
  Pmsg0(0, _("Now forward spacing 4 files.\n"));
  if (!dev->fsf(4)) {
    Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg2(-1, _("We should be in file 4. I am at file %d. %s\n"), dev->file,
        dev->file == 4 ? _("This is correct!") : _("This is NOT correct!!!!"));

  if (dev->file != 4) { goto bail_out; }
  if (set_off) {
    Pmsg0(-1, _("The test worked this time. Please add:\n\n"
                "   Fast Forward Space File = no\n\n"
                "to your Device resource for this drive.\n"));
  }

  Pmsg0(-1, "\n");
  Pmsg0(0, _("Now forward spacing 1 more file.\n"));
  if (!dev->fsf(1)) {
    Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
  }
  Pmsg2(-1, _("We should be in file 5. I am at file %d. %s\n"), dev->file,
        dev->file == 5 ? _("This is correct!") : _("This is NOT correct!!!!"));
  if (dev->file != 5) { goto bail_out; }
  Pmsg0(-1, _("\n=== End Forward space files test ===\n\n"));
  return true;

bail_out:
  Pmsg0(-1, _("\nThe forward space file test failed.\n"));
  if (dev->HasCap(CAP_FASTFSF)) {
    Pmsg0(-1, _("You have Fast Forward Space File enabled.\n"
                "I am turning it off then retrying the test.\n"));
    dev->ClearCap(CAP_FASTFSF);
    set_off = true;
    goto test_again;
  }
  Pmsg0(-1, _("You must correct this error or Bareos will not work.\n"
              "Some systems, e.g. OpenBSD, require you to set\n"
              "   Use MTIOCGET= no\n"
              "in your device resource. Use with caution.\n"));
  return false;
}


/**
 * This is a general test of Bareos's functions
 *   needed to read and write the tape.
 */
static void testcmd()
{
  int status;

  if (!write_read_test()) {
    exit_code = 1;
    return;
  }
  if (!position_test()) {
    exit_code = 1;
    return;
  }

  status = append_test();
  if (status == 1) { /* OK get out */
    goto all_done;
  }
  if (status == -1) { /* first test failed */
    if (dev->HasCap(CAP_EOM) || dev->HasCap(CAP_FASTFSF)) {
      Pmsg0(-1, _("\nAppend test failed. Attempting again.\n"
                  "Setting \"Hardware End of Medium = no\n"
                  "    and \"Fast Forward Space File = no\n"
                  "and retrying append test.\n\n"));
      dev->ClearCap(CAP_EOM);     /* turn off eom */
      dev->ClearCap(CAP_FASTFSF); /* turn off fast fsf */
      status = append_test();
      if (status == 1) {
        Pmsg0(-1,
              _("\n\nIt looks like the test worked this time, please add:\n\n"
                "    Hardware End of Medium = No\n\n"
                "    Fast Forward Space File = No\n"
                "to your Device resource in the Storage conf file.\n"));
        goto all_done;
      }
      if (status == -1) {
        Pmsg0(-1, _("\n\nThat appears *NOT* to have corrected the problem.\n"));
        goto failed;
      }
      /* Wrong count after append */
      if (status == -2) {
        Pmsg0(-1,
              _("\n\nIt looks like the append failed. Attempting again.\n"
                "Setting \"BSF at EOM = yes\" and retrying append test.\n"));
        dev->SetCap(CAP_BSFATEOM); /* Backspace on eom */
        status = append_test();
        if (status == 1) {
          Pmsg0(-1,
                _("\n\nIt looks like the test worked this time, please add:\n\n"
                  "    Hardware End of Medium = No\n"
                  "    Fast Forward Space File = No\n"
                  "    BSF at EOM = yes\n\n"
                  "to your Device resource in the Storage conf file.\n"));
          goto all_done;
        }
      }
    }
  failed:
    Pmsg0(-1,
          _("\nAppend test failed.\n\n"
            "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
            "Unable to correct the problem. You MUST fix this\n"
            "problem before Bareos can use your tape drive correctly\n"
            "\nPerhaps running Bareos in fixed block mode will work.\n"
            "Do so by setting:\n\n"
            "Minimum Block Size = nnn\n"
            "Maximum Block Size = nnn\n\n"
            "in your Storage daemon's Device definition.\n"
            "nnn must match your tape driver's block size, which\n"
            "can be determined by reading your tape manufacturers\n"
            "information, and the information on your kernel dirver.\n"
            "Fixed block sizes, however, are not normally an ideal solution.\n"
            "\n"
            "Some systems, e.g. OpenBSD, require you to set\n"
            "   Use MTIOCGET= no\n"
            "in your device resource. Use with caution.\n"));
    exit_code = 1;
    return;
  }

all_done:
  Pmsg0(-1, _("\nThe above Bareos scan should have output identical to what "
              "follows.\n"
              "Please double check it ...\n"
              "=== Sample correct output ===\n"
              "1 block of 64448 bytes in file 1\n"
              "End of File mark.\n"
              "2 blocks of 64448 bytes in file 2\n"
              "End of File mark.\n"
              "3 blocks of 64448 bytes in file 3\n"
              "End of File mark.\n"
              "1 block of 64448 bytes in file 4\n"
              "End of File mark.\n"
              "Total files=4, blocks=7, bytes = 451,136\n"
              "=== End sample correct output ===\n\n"
              "If the above scan output is not identical to the\n"
              "sample output, you MUST correct the problem\n"
              "or Bareos will not be able to write multiple Jobs to \n"
              "the tape.\n\n"));

  if (status == 1) {
    if (!re_read_block_test()) { exit_code = 1; }
  }

  if (!fsf_test()) { /* do fast forward space file test */
    exit_code = 1;
  }

  autochanger_test(); /* do autochanger test */
}

/* Forward space a file */
static void fsfcmd()
{
  int num = 1;
  if (argc > 1) { num = atoi(argk[1]); }
  if (num <= 0) { num = 1; }
  if (!dev->fsf(num)) {
    Pmsg1(0, _("Bad status from fsf. ERR=%s\n"), dev->bstrerror());
    return;
  }
  if (num == 1) {
    Pmsg0(0, _("Forward spaced 1 file.\n"));
  } else {
    Pmsg1(0, _("Forward spaced %d files.\n"), num);
  }
}

/* Forward space a record */
static void fsrcmd()
{
  int num = 1;
  if (argc > 1) { num = atoi(argk[1]); }
  if (num <= 0) { num = 1; }
  if (!dev->fsr(num)) {
    Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
    return;
  }
  if (num == 1) {
    Pmsg0(0, _("Forward spaced 1 record.\n"));
  } else {
    Pmsg1(0, _("Forward spaced %d records.\n"), num);
  }
}

// Read a Bareos block from the tape
static void rbcmd()
{
  dev->open(dcr, DeviceMode::OPEN_READ_ONLY);
  dcr->ReadBlockFromDev(NO_BLOCK_NUMBER_CHECK);
}

// Write a Bareos block to the tape
static void wrcmd()
{
  DeviceBlock* block = dcr->block;
  DeviceRecord* rec = dcr->rec;
  int i;

  if (!dev->IsOpen()) { open_the_device(); }
  EmptyBlock(block);
  if (verbose > 1) { DumpBlock(block, "test"); }

  i = block->buf_len - 100;
  ASSERT(i > 0);
  rec->data = CheckPoolMemorySize(rec->data, i);
  memset(rec->data, i & 0xFF, i);
  rec->data_len = i;
  if (!WriteRecordToBlock(dcr, rec)) {
    Pmsg0(0, _("Error writing record to block.\n"));
    goto bail_out;
  }
  if (!dcr->WriteBlockToDev()) {
    Pmsg0(0, _("Error writing block to device.\n"));
    goto bail_out;
  } else {
    Pmsg1(0, _("Wrote one record of %d bytes.\n"), i);
  }
  Pmsg0(0, _("Wrote block to device.\n"));

bail_out:
  return;
}

// Read a record from the tape
static void rrcmd()
{
  char* buf;
  int status, len;

  if (!GetCmd(_("Enter length to read: "))) { return; }
  len = atoi(cmd);
  if (len < 0 || len > 1'000'000) {
    Pmsg0(0, _("Bad length entered, using default of 1024 bytes.\n"));
    len = 1024;
  }
  buf = (char*)malloc(len);
  status = read(dev->fd, buf, len);
  if (status > 0 && status <= len) { errno = 0; }
  BErrNo be;
  Pmsg3(0, _("Read of %d bytes gives status=%d. ERR=%s\n"), len, status,
        be.bstrerror());
  free(buf);
}


/**
 * Scan tape by reading block by block. Report what is
 * on the tape.  Note, this command does raw reads, and as such
 * will not work with fixed block size devices.
 */
static void scancmd()
{
  int status;
  int blocks, tot_blocks, tot_files;
  int block_size;
  uint64_t bytes;
  char ec1[50];


  blocks = block_size = tot_blocks = 0;
  bytes = 0;
  if (dev->AtEot()) {
    Pmsg0(0, _("End of tape\n"));
    return;
  }
  dev->UpdatePos(dcr);
  tot_files = dev->file;
  Pmsg1(0, _("Starting scan at file %u\n"), dev->file);
  for (;;) {
    if ((status = read(dev->fd, buf, sizeof(buf))) < 0) {
      BErrNo be;
      dev->clrerror(-1);
      Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
            dev->archive_device_string, be.bstrerror());
      Pmsg2(0, _("Bad status from read %d. ERR=%s\n"), status,
            dev->bstrerror());
      if (blocks > 0) {
        if (blocks == 1) {
          printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
        } else {
          printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size,
                 dev->file);
        }
      }
      return;
    }
    Dmsg1(200, "read status = %d\n", status);
    /*    sleep(1); */
    if (status != block_size) {
      dev->UpdatePos(dcr);
      if (blocks > 0) {
        if (blocks == 1) {
          printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
        } else {
          printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size,
                 dev->file);
        }
        blocks = 0;
      }
      block_size = status;
    }
    if (status == 0) { /* EOF */
      dev->UpdatePos(dcr);
      printf(_("End of File mark.\n"));
      /* Two reads of zero means end of tape */
      if (dev->AtEof()) {
        dev->SetEot();
      } else {
        dev->SetEof();
        dev->file++;
      }
      if (dev->AtEot()) {
        printf(_("End of tape\n"));
        break;
      }
    } else { /* Got data */
      dev->ClearEof();
      blocks++;
      tot_blocks++;
      bytes += status;
    }
  }
  dev->UpdatePos(dcr);
  tot_files = dev->file - tot_files;
  printf(_("Total files=%d, blocks=%d, bytes = %s\n"), tot_files, tot_blocks,
         edit_uint64_with_commas(bytes, ec1));
}


/**
 * Scan tape by reading Bareos block by block. Report what is
 * on the tape.  This function reads Bareos blocks, so if your
 * Device resource is correctly defined, it should work with
 * either variable or fixed block sizes.
 */
static void scan_blocks()
{
  int blocks, tot_blocks, tot_files;
  uint32_t block_size;
  uint64_t bytes;
  DeviceBlock* block = dcr->block;
  char ec1[50];
  char buf1[100], buf2[100];

  blocks = block_size = tot_blocks = 0;
  bytes = 0;

  EmptyBlock(block);
  dev->UpdatePos(dcr);
  tot_files = dev->file;
  for (;;) {
    switch (dcr->ReadBlockFromDevice(NO_BLOCK_NUMBER_CHECK)) {
      case DeviceControlRecord::ReadStatus::Ok:
        // no special handling required
        break;
      case DeviceControlRecord::ReadStatus::EndOfTape:
        if (blocks > 0) {
          if (blocks == 1) {
            printf(_("1 block of %d bytes in file %d\n"), block_size,
                   dev->file);
          } else {
            printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size,
                   dev->file);
          }
          blocks = 0;
        }
        goto bail_out;
      case DeviceControlRecord::ReadStatus::EndOfFile:
        if (blocks > 0) {
          if (blocks == 1) {
            printf(_("1 block of %d bytes in file %d\n"), block_size,
                   dev->file);
          } else {
            printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size,
                   dev->file);
          }
          blocks = 0;
        }
        printf(_("End of File mark.\n"));
        continue;
      default:
        Dmsg1(100, "!read_block(): ERR=%s\n", dev->bstrerror());
        if (BitIsSet(ST_SHORT, dev->state)) {
          if (blocks > 0) {
            if (blocks == 1) {
              printf(_("1 block of %d bytes in file %d\n"), block_size,
                     dev->file);
            } else {
              printf(_("%d blocks of %d bytes in file %d\n"), blocks,
                     block_size, dev->file);
            }
            blocks = 0;
          }
          printf(_("Short block read.\n"));
          continue;
        }
        printf(_("Error reading block. ERR=%s\n"), dev->bstrerror());
        goto bail_out;
    }
    if (block->block_len != block_size) {
      if (blocks > 0) {
        if (blocks == 1) {
          printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
        } else {
          printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size,
                 dev->file);
        }
        blocks = 0;
      }
      block_size = block->block_len;
    }
    blocks++;
    tot_blocks++;
    bytes += block->block_len;
    Dmsg7(100,
          "Blk_blk=%u file,blk=%u,%u blen=%u bVer=%d SessId=%u SessTim=%u\n",
          block->BlockNumber, dev->file, dev->block_num, block->block_len,
          block->BlockVer, block->VolSessionId, block->VolSessionTime);
    if (verbose == 1) {
      DeviceRecord* rec = new_record();
      ReadRecordFromBlock(dcr, rec);
      Pmsg9(-1,
            _("Block=%u file,blk=%u,%u blen=%u First rec FI=%s SessId=%u "
              "SessTim=%u Strm=%s rlen=%d\n"),
            block->BlockNumber, dev->file, dev->block_num, block->block_len,
            FI_to_ascii(buf1, rec->FileIndex), rec->VolSessionId,
            rec->VolSessionTime,
            stream_to_ascii(buf2, rec->Stream, rec->FileIndex), rec->data_len);
      rec->remainder = 0;
      FreeRecord(rec);
    } else if (verbose > 1) {
      DumpBlock(block, "");
    }
  }
bail_out:
  tot_files = dev->file - tot_files;
  printf(_("Total files=%d, blocks=%d, bytes = %s\n"), tot_files, tot_blocks,
         edit_uint64_with_commas(bytes, ec1));
}

static void statcmd()
{
  char* status;

  status = dev->StatusDev();

  printf(_("Device status:"));
  if (BitIsSet(BMT_TAPE, status)) printf(" TAPE");
  if (BitIsSet(BMT_EOF, status)) printf(" EOF");
  if (BitIsSet(BMT_BOT, status)) printf(" BOT");
  if (BitIsSet(BMT_EOT, status)) printf(" EOT");
  if (BitIsSet(BMT_SM, status)) printf(" SETMARK");
  if (BitIsSet(BMT_EOD, status)) printf(" EOD");
  if (BitIsSet(BMT_WR_PROT, status)) printf(" WRPROT");
  if (BitIsSet(BMT_ONLINE, status)) printf(" ONLINE");
  if (BitIsSet(BMT_DR_OPEN, status)) printf(" DOOROPEN");
  if (BitIsSet(BMT_IM_REP_EN, status)) printf(" IMMREPORT");

  free(status);

  printf(_(". ERR=%s\n"), dev->bstrerror());
}

/**
 * First we label the tape, then we fill
 *  it with data get a new tape and write a few blocks.
 */
static void fillcmd()
{
  DeviceBlock* block = dcr->block;
  char ec1[50], ec2[50];
  char buf1[100], buf2[100];
  uint64_t write_eof;
  uint64_t rate;
  uint32_t min_block_size;
  int fd;

  ok = true;
  stop = 0;
  vol_num = 0;
  last_file = 0;
  last_block_num = 0;
  BlockNumber = 0;
  exit_code = 0;

  Pmsg1(-1,
        _("\n"
          "This command simulates Bareos writing to a tape.\n"
          "It requires either one or two blank tapes, which it\n"
          "will label and write.\n\n"
          "If you have an autochanger configured, it will use\n"
          "the tapes that are in slots 1 and 2, otherwise, you will\n"
          "be prompted to insert the tapes when necessary.\n\n"
          "It will print a status approximately\n"
          "every 322 MB, and write an EOF every %s.  If you have\n"
          "selected the simple test option, after writing the first tape\n"
          "it will rewind it and re-read the last block written.\n\n"
          "If you have selected the multiple tape test, when the first tape\n"
          "fills, it will ask for a second, and after writing a few more \n"
          "blocks, it will stop.  Then it will begin re-reading the\n"
          "two tapes.\n\n"
          "This may take a long time -- hours! ...\n\n"),
        edit_uint64_with_suffix(dev->max_file_size, buf1));

  GetCmd(
      _("Do you want to run the simplified test (s) with one tape\n"
        "or the complete multiple tape (m) test: (s/m) "));
  if (cmd[0] == 's') {
    Pmsg0(-1, _("Simple test (single tape) selected.\n"));
    simple = true;
  } else if (cmd[0] == 'm') {
    Pmsg0(-1, _("Multiple tape test selected.\n"));
    simple = false;
  } else {
    Pmsg0(000, _("Command aborted.\n"));
    exit_code = 1;
    return;
  }

  Dmsg1(20, "Begin append device=%s\n", dev->print_name());
  Dmsg1(20, "MaxVolSize=%s\n", edit_uint64(dev->max_volume_size, ec1));

  /* Use fixed block size to simplify read back */
  min_block_size = dev->min_block_size;
  dev->min_block_size = dev->max_block_size;
  write_eof = dev->max_file_size / REC_SIZE; /*compute when we add EOF*/
  ASSERT(write_eof > 0);

  SetVolumeName("TestVolume1", 1);
  dcr->DirAskSysopToCreateAppendableVolume();
  dev->SetAppend(); /* force volume to be relabeled */

  /*
   * Acquire output device for writing.  Note, after acquiring a
   *   device, we MUST release it, which is done at the end of this
   *   subroutine.
   */
  Dmsg0(100, "just before acquire_device\n");
  if (!AcquireDeviceForAppend(dcr)) {
    jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
    exit_code = 1;
    return;
  }
  block = jcr->sd_impl->dcr->block;

  Dmsg0(100, "Just after AcquireDeviceForAppend\n");
  // Write Begin Session Record
  if (!WriteSessionLabel(dcr, SOS_LABEL)) {
    jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
    Jmsg1(jcr, M_FATAL, 0, _("Write session label failed. ERR=%s\n"),
          dev->bstrerror());
    ok = false;
  }
  Pmsg0(-1, _("Wrote Start of Session label.\n"));

  DeviceRecord rec;
  rec.data = GetMemory(100'000); /* max record size */
  rec.data_len = REC_SIZE;

  // Put some random data in the record
  FillBuffer(FILL_RANDOM, rec.data, rec.data_len);

  // Generate data as if from File daemon, write to device
  jcr->sd_impl->dcr->VolFirstIndex = 0;
  time(&jcr->run_time); /* start counting time for rates */

  bstrftime(buf1, sizeof(buf1), jcr->run_time, "%H:%M:%S");

  if (simple) {
    Pmsg1(-1, _("%s Begin writing Bareos records to tape ...\n"), buf1);
  } else {
    Pmsg1(-1, _("%s Begin writing Bareos records to first tape ...\n"), buf1);
  }
  for (file_index = 0; ok && !JobCanceled(jcr);) {
    rec.VolSessionId = jcr->VolSessionId;
    rec.VolSessionTime = jcr->VolSessionTime;
    rec.FileIndex = ++file_index;
    rec.Stream = STREAM_FILE_DATA;
    rec.maskedStream = STREAM_FILE_DATA;

    /* Mix up the data just a bit */
    MixBuffer(FILL_RANDOM, rec.data, rec.data_len);

    Dmsg4(250, "before write_rec FI=%d SessId=%d Strm=%s len=%d\n",
          rec.FileIndex, rec.VolSessionId,
          stream_to_ascii(buf1, rec.Stream, rec.FileIndex), rec.data_len);

    while (!WriteRecordToBlock(dcr, &rec)) {
      // When we get here we have just filled a block
      Dmsg2(150, "!WriteRecordToBlock data_len=%d rem=%d\n", rec.data_len,
            rec.remainder);

      /* Write block to tape */
      if (!FlushBlock(block)) {
        Pmsg0(000, _("Flush block failed.\n"));
        exit_code = 1;
        break;
      }

      /* Every 5000 blocks (approx 322MB) report where we are.
       */
      if ((block->BlockNumber % 5000) == 0) {
        now = time(nullptr);
        now -= jcr->run_time;
        if (now <= 0) { now = 1; /* prevent divide error */ }
        rate = dev->VolCatInfo.VolCatBytes / now;
        Pmsg5(-1, _("Wrote block=%u, file,blk=%u,%u VolBytes=%s rate=%sB/s\n"),
              block->BlockNumber, dev->file, dev->block_num,
              edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1),
              edit_uint64_with_suffix(rate, ec2));
      }
      /* Every X blocks (dev->max_file_size) write an EOF.
       */
      if ((block->BlockNumber % write_eof) == 0) {
        now = time(nullptr);
        bstrftime(buf1, sizeof(buf1), now, "%H:%M:%S");
        Pmsg1(-1, _("%s Flush block, write EOF\n"), buf1);
        FlushBlock(block);
      }

      /* Get out after writing 1000 blocks to the second tape */
      if (++BlockNumber > 1000 && stop != 0) { /* get out */
        Pmsg0(000, _("Wrote 1000 blocks on second tape. Done.\n"));
        break;
      }
    }
    if (!ok) {
      Pmsg0(000, _("Not OK\n"));
      exit_code = 1;
      break;
    }
    jcr->JobBytes += rec.data_len; /* increment bytes of this job */
    Dmsg4(190, "WriteRecord FI=%s SessId=%d Strm=%s len=%d\n",
          FI_to_ascii(buf1, rec.FileIndex), rec.VolSessionId,
          stream_to_ascii(buf2, rec.Stream, rec.FileIndex), rec.data_len);

    /* Get out after writing 1000 blocks to the second tape */
    if (BlockNumber > 1000 && stop != 0) { /* get out */
      char ed1[50];
      Pmsg1(-1, "Done writing %s records ...\n",
            edit_uint64_with_commas(write_count, ed1));
      break;
    }
  } /* end big for loop */

  if (vol_num > 1) {
    Dmsg0(100, "Write_end_session_label()\n");
    /* Create Job status for end of session label */
    if (!JobCanceled(jcr) && ok) {
      jcr->setJobStatusWithPriorityCheck(JS_Terminated);
    } else if (!ok) {
      Pmsg0(000, _("Job canceled.\n"));
      jcr->setJobStatusWithPriorityCheck(JS_ErrorTerminated);
      exit_code = 1;
    }
    if (!WriteSessionLabel(dcr, EOS_LABEL)) {
      Pmsg1(000, _("Error writing end session label. ERR=%s\n"),
            dev->bstrerror());
      ok = false;
      exit_code = 1;
    }
    /* Write out final block of this session */
    if (!dcr->WriteBlockToDevice()) {
      Pmsg0(-1, _("Set ok=false after WriteBlockToDevice.\n"));
      ok = false;
      exit_code = 1;
    }
    Pmsg0(-1, _("Wrote End of Session label.\n"));

    /* Save last block info for second tape */
    last_block_num2 = last_block_num;
    last_file2 = last_file;
    if (last_block2) { FreeBlock(last_block2); }
    last_block2 = dup_block(last_block);
  }

  sprintf(buf, "%s/btape.state", working_directory);
  fd = open(buf, O_CREAT | O_TRUNC | O_WRONLY, 0640);
  if (fd >= 0) {
    write_with_check(fd, &btape_state_level, sizeof(btape_state_level));
    write_with_check(fd, &simple, sizeof(simple));
    write_with_check(fd, &last_block_num1, sizeof(last_block_num1));
    write_with_check(fd, &last_block_num2, sizeof(last_block_num2));
    write_with_check(fd, &last_file1, sizeof(last_file1));
    write_with_check(fd, &last_file2, sizeof(last_file2));
    write_with_check(fd, last_block1->buf, last_block1->buf_len);
    write_with_check(fd, last_block2->buf, last_block2->buf_len);
    write_with_check(fd, first_block->buf, first_block->buf_len);
    close(fd);
    Pmsg2(0, _("Wrote state file last_block_num1=%d last_block_num2=%d\n"),
          last_block_num1, last_block_num2);
  } else {
    BErrNo be;
    Pmsg2(0, _("Could not create state file: %s ERR=%s\n"), buf,
          be.bstrerror());
    exit_code = 1;
    ok = false;
  }

  now = time(nullptr);
  bstrftime(buf1, sizeof(buf1), now, "%H:%M:%S");

  if (ok) {
    if (simple) {
      Pmsg3(0,
            _("\n\n%s Done filling tape at %d:%d. Now beginning re-read of "
              "tape ...\n"),
            buf1, jcr->sd_impl->dcr->dev->file,
            jcr->sd_impl->dcr->dev->block_num);
    } else {
      Pmsg3(0,
            _("\n\n%s Done filling tapes at %d:%d. Now beginning re-read of "
              "first tape ...\n"),
            buf1, jcr->sd_impl->dcr->dev->file,
            jcr->sd_impl->dcr->dev->block_num);
    }

    jcr->sd_impl->dcr->block = block;
    if (!do_unfill()) {
      Pmsg0(000, _("do_unfill failed.\n"));
      exit_code = 1;
      ok = false;
    }
  } else {
    Pmsg1(000, _("%s: Error during test.\n"), buf1);
  }
  dev->min_block_size = min_block_size;
  FreeMemory(rec.data);
}

/**
 * Read two tapes written by the "fill" command and ensure
 *  that the data is valid.  If stop==1 we simulate full read back
 *  of two tapes.  If stop==-1 we simply read the last block and
 *  verify that it is correct.
 */
static void unfillcmd()
{
  int fd;

  exit_code = 0;
  last_block1 = new_block(dev);
  last_block2 = new_block(dev);
  first_block = new_block(dev);
  sprintf(buf, "%s/btape.state", working_directory);
  fd = open(buf, O_RDONLY);
  if (fd >= 0) {
    uint32_t state_level;
    read_with_check(fd, &state_level, sizeof(btape_state_level));
    read_with_check(fd, &simple, sizeof(simple));
    read_with_check(fd, &last_block_num1, sizeof(last_block_num1));
    read_with_check(fd, &last_block_num2, sizeof(last_block_num2));
    read_with_check(fd, &last_file1, sizeof(last_file1));
    read_with_check(fd, &last_file2, sizeof(last_file2));
    read_with_check(fd, last_block1->buf, last_block1->buf_len);
    read_with_check(fd, last_block2->buf, last_block2->buf_len);
    read_with_check(fd, first_block->buf, first_block->buf_len);
    close(fd);
    if (state_level != btape_state_level) {
      Pmsg0(-1, _("\nThe state file level has changed. You must redo\n"
                  "the fill command.\n"));
      exit_code = 1;
      return;
    }
  } else {
    BErrNo be;
    Pmsg2(-1,
          _("\nCould not find the state file: %s ERR=%s\n"
            "You must redo the fill command.\n"),
          buf, be.bstrerror());
    exit_code = 1;
    return;
  }
  if (!do_unfill()) { exit_code = 1; }
  this_block = nullptr;
}

/**
 * This is the second part of the fill command. After the tape or
 *  tapes are written, we are called here to reread parts, particularly
 *  the last block.
 */
static bool do_unfill()
{
  DeviceBlock* block = dcr->block;
  int autochanger;
  bool rc = false;

  dumped = 0;
  VolBytes = 0;
  LastBlock = 0;

  Pmsg0(000, "Enter do_unfill\n");
  dev->SetCap(CAP_ANONVOLS); /* allow reading any volume */
  dev->ClearCap(CAP_LABEL);  /* don't label anything here */

  end_of_tape = 0;

  time(&jcr->run_time); /* start counting time for rates */
  stop = 0;
  file_index = 0;
  if (last_block) {
    FreeBlock(last_block);
    last_block = nullptr;
  }
  last_block_num = last_block_num1;
  last_file = last_file1;
  last_block = last_block1;

  FreeRestoreVolumeList(jcr);
  jcr->sd_impl->read_session.bsr = nullptr;
  bstrncpy(dcr->VolumeName, "TestVolume1|TestVolume2", sizeof(dcr->VolumeName));
  CreateRestoreVolumeList(jcr);
  if (jcr->sd_impl->VolList != nullptr) {
    jcr->sd_impl->VolList->Slot = 1;
    if (jcr->sd_impl->VolList->next != nullptr) {
      jcr->sd_impl->VolList->next->Slot = 2;
    }
  }

  SetVolumeName("TestVolume1", 1);

  if (!simple) {
    /* Multiple Volume tape */
    /* Close device so user can use autochanger if desired */
    if (dev->HasCap(CAP_OFFLINEUNMOUNT)) { dev->offline(); }
    autochanger = AutoloadDevice(dcr, 1, nullptr);
    if (autochanger != 1) {
      Pmsg1(100, "Autochanger returned: %d\n", autochanger);
      dev->close(dcr);
      GetCmd(_("Mount first tape. Press enter when ready: "));
      Pmsg0(000, "\n");
    }
  }

  dev->close(dcr);
  dev->num_writers = 0;
  jcr->sd_impl->dcr->clear_will_write();

  if (!AcquireDeviceForRead(dcr)) {
    Pmsg1(-1, "%s", dev->errmsg);
    goto bail_out;
  }
  /*
   * We now have the first tape mounted.
   * Note, re-reading last block may have caused us to
   *   loose track of where we are (block number unknown).
   */
  Pmsg0(-1, _("Rewinding.\n"));
  if (!dev->rewind(dcr)) { /* get to a known place on tape */
    goto bail_out;
  }
  /* Read the first 10'000 records */
  Pmsg2(-1, _("Reading the first 10'000 records from %u:%u.\n"), dev->file,
        dev->block_num);
  quickie_count = 0;
  ReadRecords(dcr, QuickieCb, MyMountNextReadVolume);
  Pmsg4(-1, _("Reposition from %u:%u to %u:%u\n"), dev->file, dev->block_num,
        last_file, last_block_num);
  if (!dev->Reposition(dcr, last_file, last_block_num)) {
    Pmsg1(-1, _("Reposition error. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg1(-1, _("Reading block %u.\n"), last_block_num);
  if (DeviceControlRecord::ReadStatus::Ok
      != dcr->ReadBlockFromDevice(NO_BLOCK_NUMBER_CHECK)) {
    Pmsg1(-1, _("Error reading block: ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  if (CompareBlocks(last_block, block)) {
    if (simple) {
      Pmsg0(-1, _("\nThe last block on the tape matches. Test succeeded.\n\n"));
      rc = true;
    } else {
      Pmsg0(-1, _("\nThe last block of the first tape matches.\n\n"));
    }
  }
  if (simple) { goto bail_out; }

  /* restore info for last block on second Volume */
  last_block_num = last_block_num2;
  last_file = last_file2;
  last_block = last_block2;

  /* Multiple Volume tape */
  /* Close device so user can use autochanger if desired */
  if (dev->HasCap(CAP_OFFLINEUNMOUNT)) { dev->offline(); }

  SetVolumeName("TestVolume2", 2);

  autochanger = AutoloadDevice(dcr, 1, nullptr);
  if (autochanger != 1) {
    Pmsg1(100, "Autochanger returned: %d\n", autochanger);
    dev->close(dcr);
    GetCmd(_("Mount second tape. Press enter when ready: "));
    Pmsg0(000, "\n");
  }

  dev->ClearRead();
  if (!AcquireDeviceForRead(dcr)) {
    Pmsg1(-1, "%s", dev->errmsg);
    goto bail_out;
  }

  /* Space to "first" block which is last block not written
   * on the previous tape.
   */
  Pmsg2(-1, _("Reposition from %u:%u to 0:1\n"), dev->file, dev->block_num);
  if (!dev->Reposition(dcr, 0, 1)) {
    Pmsg1(-1, _("Reposition error. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg1(-1, _("Reading block %d.\n"), dev->block_num);
  if (DeviceControlRecord::ReadStatus::Ok
      != dcr->ReadBlockFromDevice(NO_BLOCK_NUMBER_CHECK)) {
    Pmsg1(-1, _("Error reading block: ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  if (CompareBlocks(first_block, block)) {
    Pmsg0(-1, _("\nThe first block on the second tape matches.\n\n"));
  }

  /* Now find and compare the last block */
  Pmsg4(-1, _("Reposition from %u:%u to %u:%u\n"), dev->file, dev->block_num,
        last_file, last_block_num);
  if (!dev->Reposition(dcr, last_file, last_block_num)) {
    Pmsg1(-1, _("Reposition error. ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  Pmsg1(-1, _("Reading block %d.\n"), dev->block_num);
  if (DeviceControlRecord::ReadStatus::Ok
      != dcr->ReadBlockFromDevice(NO_BLOCK_NUMBER_CHECK)) {
    Pmsg1(-1, _("Error reading block: ERR=%s\n"), dev->bstrerror());
    goto bail_out;
  }
  if (CompareBlocks(last_block, block)) {
    Pmsg0(-1, _("\nThe last block on the second tape matches. Test "
                "succeeded.\n\n"));
    rc = true;
  }

bail_out:
  FreeBlock(last_block1);
  FreeBlock(last_block2);
  FreeBlock(first_block);

  last_block1 = nullptr;
  last_block2 = nullptr;
  last_block = nullptr;
  first_block = nullptr;

  return rc;
}

/* Read 10'000 records then stop */
static bool QuickieCb(DeviceControlRecord* dcr, DeviceRecord*)
{
  Device* dev = dcr->dev;
  quickie_count++;
  if (quickie_count == 10'000) {
    Pmsg2(-1, _("10'000 records read now at %d:%d\n"), dev->file,
          dev->block_num);
  }
  return quickie_count < 10'000;
}

static bool CompareBlocks(DeviceBlock* last_block, DeviceBlock* block)
{
  char *p, *q;
  union {
    uint32_t CheckSum;
    uint32_t block_len;
  };
  ser_declare;

  p = last_block->buf;
  q = block->buf;
  UnserBegin(q, BLKHDR2_LENGTH);
  unser_uint32(CheckSum);
  unser_uint32(block_len);
  while (q < (block->buf + block_len)) {
    if (*p == *q) {
      p++;
      q++;
      continue;
    }
    Pmsg0(-1, "\n");
    DumpBlock(last_block, _("Last block written"));
    Pmsg0(-1, "\n");
    DumpBlock(block, _("Block read back"));
    Pmsg1(-1, _("\n\nThe blocks differ at byte %u\n"), p - last_block->buf);
    Pmsg0(-1, _("\n\n!!!! The last block written and the block\n"
                "that was read back differ. The test FAILED !!!!\n"
                "This must be corrected before you use Bareos\n"
                "to write multi-tape Volumes.!!!!\n"));
    return false;
  }
  if (verbose) {
    DumpBlock(last_block, _("Last block written"));
    DumpBlock(block, _("Block read back"));
  }
  return true;
}

/**
 * Write current block to tape regardless of whether or
 *   not it is full. If the tape fills, attempt to
 *   acquire another tape.
 */
static int FlushBlock(DeviceBlock* block)
{
  char ec1[50], ec2[50];
  uint64_t rate;
  DeviceBlock* tblock;
  uint32_t thIsFile, this_block_num;

  dev->rLock();
  if (!this_block) { this_block = new_block(dev); }
  if (!last_block) { last_block = new_block(dev); }
  /* Copy block */
  thIsFile = dev->file;
  this_block_num = dev->block_num;
  if (!dcr->WriteBlockToDev()) {
    Pmsg3(000, _("Last block at: %u:%u this_dev_block_num=%d\n"), last_file,
          last_block_num, this_block_num);
    if (vol_num == 1) {
      /*
       * This is 1st tape, so save first tape info separate
       *  from second tape info
       */
      last_block_num1 = last_block_num;
      last_file1 = last_file;
      last_block1 = dup_block(last_block);
      last_block2 = dup_block(last_block);
      first_block = dup_block(block); /* first block second tape */
    }
    if (verbose) {
      Pmsg3(000, _("Block not written: FileIndex=%u blk_block=%u Size=%u\n"),
            (unsigned)file_index, block->BlockNumber, block->block_len);
      DumpBlock(last_block, _("Last block written"));
      Pmsg0(-1, "\n");
      DumpBlock(block, _("Block not written"));
    }
    if (stop == 0) {
      eot_block = block->BlockNumber;
      eot_block_len = block->block_len;
      eot_FileIndex = file_index;
      stop = 1;
    }
    now = time(nullptr);
    now -= jcr->run_time;
    if (now <= 0) { now = 1; /* don't divide by zero */ }
    rate = dev->VolCatInfo.VolCatBytes / now;
    vol_size = dev->VolCatInfo.VolCatBytes;
    Pmsg4(000, _("End of tape %d:%d. Volume Bytes=%s. Write rate = %sB/s\n"),
          dev->file, dev->block_num,
          edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1),
          edit_uint64_with_suffix(rate, ec2));

    if (simple) {
      stop = -1; /* stop, but do simplified test */
    } else {
      /* Full test in progress */
      if (!FixupDeviceBlockWriteError(jcr->sd_impl->dcr)) {
        Pmsg1(000, _("Cannot fixup device error. %s\n"), dev->bstrerror());
        ok = false;
        dev->Unlock();
        return 0;
      }
      BlockNumber = 0; /* start counting for second tape */
    }
    dev->Unlock();
    return 1; /* end of tape reached */
  }

  /* Save contents after write so that the header is serialized */
  memcpy(this_block->buf, block->buf, this_block->buf_len);

  /*
   * Note, we always read/write to block, but we toggle
   *  copying it to one or another of two allocated blocks.
   * Switch blocks so that the block just successfully written is
   *  always in last_block.
   */
  tblock = last_block;
  last_block = this_block;
  this_block = tblock;
  last_file = thIsFile;
  last_block_num = this_block_num;

  dev->Unlock();
  return 1;
}


/**
 * First we label the tape, then we fill
 *  it with data get a new tape and write a few blocks.
 */
static void qfillcmd()
{
  DeviceBlock* block = dcr->block;
  DeviceRecord* rec = dcr->rec;
  int i, count;

  Pmsg0(0, _("Test writing blocks of 64512 bytes to tape.\n"));

  GetCmd(_("How many blocks do you want to write? (1000): "));

  count = atoi(cmd);
  if (count <= 0) { count = 1000; }


  i = block->buf_len - 100;
  ASSERT(i > 0);
  rec->data = CheckPoolMemorySize(rec->data, i);
  memset(rec->data, i & 0xFF, i);
  rec->data_len = i;
  rewindcmd();
  init_speed();

  Pmsg1(0, _("Begin writing %d Bareos blocks to tape ...\n"), count);
  for (i = 0; i < count; i++) {
    if (i % 100 == 0) {
      printf("+");
      fflush(stdout);
    }
    if (!WriteRecordToBlock(dcr, rec)) {
      Pmsg0(0, _("Error writing record to block.\n"));
      goto bail_out;
    }
    if (!dcr->WriteBlockToDev()) {
      Pmsg0(0, _("Error writing block to device.\n"));
      goto bail_out;
    }
  }
  printf("\n");
  PrintSpeed(dev->VolCatInfo.VolCatBytes);
  weofcmd();
  if (dev->HasCap(CAP_TWOEOF)) { weofcmd(); }
  rewindcmd();
  scan_blocks();

bail_out:
  return;
}

// Fill a tape using raw write() command
static void rawfill_cmd()
{
  DeviceBlock* block = dcr->block;
  int status;
  uint32_t block_num = 0;
  uint32_t* p;
  int my_errno;

  FillBuffer(FILL_RANDOM, block->buf, block->buf_len);
  init_speed();

  p = (uint32_t*)block->buf;
  Pmsg1(0, _("Begin writing raw blocks of %u bytes.\n"), block->buf_len);
  for (;;) {
    *p = block_num;
    status = dev->d_write(dev->fd, block->buf, block->buf_len);
    if (status == (int)block->buf_len) {
      if ((block_num++ % 100) == 0) {
        printf("+");
        fflush(stdout);
      }

      MixBuffer(FILL_RANDOM, block->buf, block->buf_len);

      jcr->JobBytes += status;
      continue;
    }
    break;
  }
  my_errno = errno;
  printf("\n");
  BErrNo be;
  printf(_("Write failed at block %u. status=%d ERR=%s\n"), block_num, status,
         be.bstrerror(my_errno));

  PrintSpeed(jcr->JobBytes);
  weofcmd();
}


struct cmdstruct {
  const char* key;
  void (*func)();
  const char* help;
};
static struct cmdstruct commands[] = {
    {NT_("autochanger"), autochangercmd, _("test autochanger")},
    {NT_("bsf"), bsfcmd, _("backspace file")},
    {NT_("bsr"), bsrcmd, _("backspace record")},
    {NT_("cap"), capcmd, _("list device capabilities")},
    {NT_("clear"), clearcmd, _("clear tape errors")},
    {NT_("eod"), eodcmd, _("go to end of Bareos data for append")},
    {NT_("eom"), eomcmd, _("go to the physical end of medium")},
    {NT_("fill"), fillcmd, _("fill tape, write onto second volume")},
    {NT_("unfill"), unfillcmd, _("read filled tape")},
    {NT_("fsf"), fsfcmd, _("forward space a file")},
    {NT_("fsr"), fsrcmd, _("forward space a record")},
    {NT_("help"), HelpCmd, _("print this command")},
    {NT_("label"), labelcmd, _("write a Bareos label to the tape")},
    {NT_("load"), loadcmd, _("load a tape")},
    {NT_("quit"), QuitCmd, _("quit btape")},
    {NT_("rawfill"), rawfill_cmd, _("use write() to fill tape")},
    {NT_("readlabel"), readlabelcmd, _("read and print the Bareos tape label")},
    {NT_("rectest"), rectestcmd, _("test record handling functions")},
    {NT_("rewind"), rewindcmd, _("rewind the tape")},
    {NT_("scan"), scancmd, _("read() tape block by block to EOT and report")},
    {NT_("scanblocks"), scan_blocks,
     _("Bareos read block by block to EOT and report")},
    {NT_("speed"), speed_test,
     _("[file_size=n(GB)|nb_file=3|skip_zero|skip_random|skip_raw|skip_block]"
       " "
       "report drive speed")},
    {NT_("status"), statcmd, _("print tape status")},
    {NT_("test"), testcmd, _("General test Bareos tape functions")},
    {NT_("weof"), weofcmd, _("write an EOF on the tape")},
    {NT_("wr"), wrcmd, _("write a single Bareos block")},
    {NT_("rr"), rrcmd, _("read a single record")},
    {NT_("rb"), rbcmd, _("read a single Bareos block")},
    {NT_("qfill"), qfillcmd, _("quick fill command")}};
#define comsize (sizeof(commands) / sizeof(struct cmdstruct))

static void do_tape_cmds()
{
  unsigned int i;
  bool found;

  while (!quit && GetCmd("*")) {
    found = false;
    ParseArgs(cmd, args, &argc, argk, argv, MAX_CMD_ARGS);
    /* search for command */
    for (i = 0; i < comsize; i++) {
      if (argc > 0 && fstrsch(argk[0], commands[i].key)) {
        /* execute command */
        (*commands[i].func)();
        found = true;
        break;
      }
    }
    if (*cmd && !found) { Pmsg1(0, _("\"%s\" is an invalid command\n"), cmd); }
  }
}

static std::string Generate_interactive_commands_help()
{
  std::string output{
      "Interactive commands:\n"
      "  Command    Description\n  =======    ===========\n"};
  char tmp[1024];
  for (unsigned int i = 0; i < comsize; i++) {
    sprintf(tmp, "  %-10s %s\n", commands[i].key, commands[i].help);
    output += tmp;
  }

  output += "\n";
  return output;
}

static void HelpCmd()
{
  printf("%s", Generate_interactive_commands_help().c_str());
}

/**
 * Get next input command from terminal.  This
 * routine is REALLY primitive, and should be enhanced
 * to have correct backspacing, etc.
 */
int GetCmd(const char* prompt)
{
  int i = 0;
  int ch;

  fprintf(stdout, "%s", prompt);

  /* We really should turn off echoing and pretty this
   * up a bit.
   */
  cmd[i] = 0;
  while ((ch = fgetc(stdin)) != EOF) {
    if (ch == '\n') {
      StripTrailingJunk(cmd);
      return 1;
    } else if (ch == 4 || ch == 0xd3 || ch == 0x8) {
      if (i > 0) { cmd[--i] = 0; }
      continue;
    }

    cmd[i++] = ch;
    cmd[i] = 0;
  }
  quit = 1;
  return 0;
}

bool BTAPE_DCR::DirCreateJobmediaRecord(bool)
{
  WroteVol = false;
  return 1;
}

bool BTAPE_DCR::DirFindNextAppendableVolume()
{
  Dmsg1(20, "Enter DirFindNextAppendableVolume. stop=%d\n", stop);
  return VolumeName[0] != 0;
}

bool BTAPE_DCR::DirAskSysopToMountVolume(int)
{
  Dmsg0(20, "Enter DirAskSysopToMountVolume\n");
  if (VolumeName[0] == 0) { return DirAskSysopToCreateAppendableVolume(); }
  Pmsg1(-1, "%s", dev->errmsg); /* print reason */

  if (VolumeName[0] == 0 || bstrcmp(VolumeName, "TestVolume2")) {
    fprintf(stderr,
            _("Mount second Volume on device %s and press return when ready: "),
            dev->print_name());
  } else {
    fprintf(stderr,
            _("Mount Volume \"%s\" on device %s and press return when ready: "),
            VolumeName, dev->print_name());
  }

  dev->close(this);
  getchar();

  return true;
}

bool BTAPE_DCR::DirAskSysopToCreateAppendableVolume()
{
  int autochanger;

  Dmsg0(20, "Enter DirAskSysopToCreateAppendableVolume\n");
  if (stop == 0) {
    SetVolumeName("TestVolume1", 1);
  } else {
    SetVolumeName("TestVolume2", 2);
  }
  /* Close device so user can use autochanger if desired */
  if (dev->HasCap(CAP_OFFLINEUNMOUNT)) { dev->offline(); }
  autochanger = AutoloadDevice(this, 1, nullptr);
  if (autochanger != 1) {
    Pmsg1(100, "Autochanger returned: %d\n", autochanger);
    fprintf(stderr,
            _("Mount blank Volume on device %s and press return when ready: "),
            dev->print_name());
    dev->close(this);
    getchar();
    Pmsg0(000, "\n");
  }
  labelcmd();
  volumename = nullptr;
  BlockNumber = 0;

  return true;
}

DeviceControlRecord* BTAPE_DCR::get_new_spooling_dcr() { return new BTAPE_DCR; }

static bool MyMountNextReadVolume(DeviceControlRecord* dcr)
{
  char ec1[50], ec2[50];
  uint64_t rate;
  JobControlRecord* jcr = dcr->jcr;
  DeviceBlock* block = dcr->block;

  Dmsg0(20, "Enter MyMountNextReadVolume\n");
  Pmsg2(000, _("End of Volume \"%s\" %d records.\n"), dcr->VolumeName,
        quickie_count);

  VolumeUnused(dcr); /* release current volume */
  if (LastBlock != block->BlockNumber) { VolBytes += block->block_len; }
  LastBlock = block->BlockNumber;
  now = time(nullptr);
  now -= jcr->run_time;
  if (now <= 0) { now = 1; }
  rate = VolBytes / now;
  Pmsg3(-1, _("Read block=%u, VolBytes=%s rate=%sB/s\n"), block->BlockNumber,
        edit_uint64_with_commas(VolBytes, ec1),
        edit_uint64_with_suffix(rate, ec2));

  if (bstrcmp(dcr->VolumeName, "TestVolume2")) {
    end_of_tape = 1;
    return false;
  }

  SetVolumeName("TestVolume2", 2);

  dev->close(dcr);
  if (!AcquireDeviceForRead(dcr)) {
    Pmsg2(0, _("Cannot open Dev=%s, Vol=%s\n"), dev->print_name(),
          dcr->VolumeName);
    return false;
  }
  return true; /* next volume mounted */
}

static void SetVolumeName(const char* VolName, int volnum)
{
  DeviceControlRecord* dcr = jcr->sd_impl->dcr;
  volumename = VolName;
  vol_num = volnum;
  dev->setVolCatName(VolName);
  dcr->setVolCatName(VolName);
  bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
  dcr->VolCatInfo.Slot = volnum;
  dcr->VolCatInfo.InChanger = true;
}