summaryrefslogtreecommitdiffstats
path: root/src/rgw/rgw_admin.cc
blob: 21c9df6f1ff963c6dcd38ef5a198bc1afd605b5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp

#include <errno.h>
#include <iostream>
#include <sstream>
#include <string>

#include <boost/optional.hpp>

extern "C" {
#include <liboath/oath.h>
}

#include "auth/Crypto.h"
#include "compressor/Compressor.h"

#include "common/armor.h"
#include "common/ceph_json.h"
#include "common/config.h"
#include "common/ceph_argparse.h"
#include "common/Formatter.h"
#include "common/errno.h"
#include "common/safe_io.h"

#include "include/util.h"

#include "cls/rgw/cls_rgw_types.h"
#include "cls/rgw/cls_rgw_client.h"

#include "global/global_init.h"

#include "include/utime.h"
#include "include/str_list.h"

#include "rgw_user.h"
#include "rgw_bucket.h"
#include "rgw_otp.h"
#include "rgw_rados.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_datalog.h"
#include "rgw_lc.h"
#include "rgw_log.h"
#include "rgw_formats.h"
#include "rgw_usage.h"
#include "rgw_orphan.h"
#include "rgw_sync.h"
#include "rgw_trim_bilog.h"
#include "rgw_trim_datalog.h"
#include "rgw_trim_mdlog.h"
#include "rgw_data_sync.h"
#include "rgw_rest_conn.h"
#include "rgw_realm_watcher.h"
#include "rgw_role.h"
#include "rgw_reshard.h"
#include "rgw_http_client_curl.h"
#include "rgw_zone.h"
#include "rgw_pubsub.h"
#include "rgw_bucket_sync.h"
#include "rgw_sync_checkpoint.h"
#include "rgw_lua.h"

#include "services/svc_sync_modules.h"
#include "services/svc_cls.h"
#include "services/svc_bilog_rados.h"
#include "services/svc_mdlog.h"
#include "services/svc_meta_be_otp.h"
#include "services/svc_zone.h"

#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw

#define SECRET_KEY_LEN 40
#define PUBLIC_ID_LEN 20

static rgw::sal::RGWRadosStore *store = NULL;

static const DoutPrefixProvider* dpp() {
  struct GlobalPrefix : public DoutPrefixProvider {
    CephContext *get_cct() const override { return dout_context; }
    unsigned get_subsys() const override { return dout_subsys; }
    std::ostream& gen_prefix(std::ostream& out) const override { return out; }
  };
  static GlobalPrefix global_dpp;
  return &global_dpp;
}

#define CHECK_TRUE(x, msg, err) \
  do { \
    if (!x) { \
      cerr << msg << std::endl; \
      return err; \
    } \
  } while (0)

#define CHECK_SUCCESS(x, msg) \
  do { \
    int _x_val = (x); \
    if (_x_val < 0) { \
      cerr << msg << ": " << cpp_strerror(-_x_val) << std::endl; \
      return _x_val; \
    } \
  } while (0)

void usage()
{
  cout << "usage: radosgw-admin <cmd> [options...]" << std::endl;
  cout << "commands:\n";
  cout << "  user create                create a new user\n" ;
  cout << "  user modify                modify user\n";
  cout << "  user info                  get user info\n";
  cout << "  user rename                rename user\n";
  cout << "  user rm                    remove user\n";
  cout << "  user suspend               suspend a user\n";
  cout << "  user enable                re-enable user after suspension\n";
  cout << "  user check                 check user info\n";
  cout << "  user stats                 show user stats as accounted by quota subsystem\n";
  cout << "  user list                  list users\n";
  cout << "  caps add                   add user capabilities\n";
  cout << "  caps rm                    remove user capabilities\n";
  cout << "  subuser create             create a new subuser\n" ;
  cout << "  subuser modify             modify subuser\n";
  cout << "  subuser rm                 remove subuser\n";
  cout << "  key create                 create access key\n";
  cout << "  key rm                     remove access key\n";
  cout << "  bucket list                list buckets (specify --allow-unordered for\n";
  cout << "                             faster, unsorted listing)\n";
  cout << "  bucket limit check         show bucket sharding stats\n";
  cout << "  bucket link                link bucket to specified user\n";
  cout << "  bucket unlink              unlink bucket from specified user\n";
  cout << "  bucket stats               returns bucket statistics\n";
  cout << "  bucket rm                  remove bucket\n";
  cout << "  bucket check               check bucket index\n";
  cout << "  bucket chown               link bucket to specified user and update its object ACLs\n";
  cout << "  bucket reshard             reshard bucket\n";
  cout << "  bucket rewrite             rewrite all objects in the specified bucket\n";
  cout << "  bucket sync checkpoint     poll a bucket's sync status until it catches up to its remote\n";
  cout << "  bucket sync disable        disable bucket sync\n";
  cout << "  bucket sync enable         enable bucket sync\n";
  cout << "  bucket radoslist           list rados objects backing bucket's objects\n";
  cout << "  bi get                     retrieve bucket index object entries\n";
  cout << "  bi put                     store bucket index object entries\n";
  cout << "  bi list                    list raw bucket index entries\n";
  cout << "  bi purge                   purge bucket index entries\n";
  cout << "  object rm                  remove object\n";
  cout << "  object put                 put object\n";
  cout << "  object stat                stat an object for its metadata\n";
  cout << "  object unlink              unlink object from bucket index\n";
  cout << "  object rewrite             rewrite the specified object\n";
  cout << "  objects expire             run expired objects cleanup\n";
  cout << "  objects expire-stale list  list stale expired objects (caused by reshard)\n";
  cout << "  objects expire-stale rm    remove stale expired objects\n";
  cout << "  period rm                  remove a period\n";
  cout << "  period get                 get period info\n";
  cout << "  period get-current         get current period info\n";
  cout << "  period pull                pull a period\n";
  cout << "  period push                push a period\n";
  cout << "  period list                list all periods\n";
  cout << "  period update              update the staging period\n";
  cout << "  period commit              commit the staging period\n";
  cout << "  quota set                  set quota params\n";
  cout << "  quota enable               enable quota\n";
  cout << "  quota disable              disable quota\n";
  cout << "  global quota get           view global quota params\n";
  cout << "  global quota set           set global quota params\n";
  cout << "  global quota enable        enable a global quota\n";
  cout << "  global quota disable       disable a global quota\n";
  cout << "  realm create               create a new realm\n";
  cout << "  realm rm                   remove a realm\n";
  cout << "  realm get                  show realm info\n";
  cout << "  realm get-default          get default realm name\n";
  cout << "  realm list                 list realms\n";
  cout << "  realm list-periods         list all realm periods\n";
  cout << "  realm rename               rename a realm\n";
  cout << "  realm set                  set realm info (requires infile)\n";
  cout << "  realm default              set realm as default\n";
  cout << "  realm pull                 pull a realm and its current period\n";
  cout << "  zonegroup add              add a zone to a zonegroup\n";
  cout << "  zonegroup create           create a new zone group info\n";
  cout << "  zonegroup default          set default zone group\n";
  cout << "  zonegroup delete           delete a zone group info\n";
  cout << "  zonegroup get              show zone group info\n";
  cout << "  zonegroup modify           modify an existing zonegroup\n";
  cout << "  zonegroup set              set zone group info (requires infile)\n";
  cout << "  zonegroup rm               remove a zone from a zonegroup\n";
  cout << "  zonegroup rename           rename a zone group\n";
  cout << "  zonegroup list             list all zone groups set on this cluster\n";
  cout << "  zonegroup placement list   list zonegroup's placement targets\n";
  cout << "  zonegroup placement get    get a placement target of a specific zonegroup\n";
  cout << "  zonegroup placement add    add a placement target id to a zonegroup\n";
  cout << "  zonegroup placement modify modify a placement target of a specific zonegroup\n";
  cout << "  zonegroup placement rm     remove a placement target from a zonegroup\n";
  cout << "  zonegroup placement default  set a zonegroup's default placement target\n";
  cout << "  zone create                create a new zone\n";
  cout << "  zone rm                    remove a zone\n";
  cout << "  zone get                   show zone cluster params\n";
  cout << "  zone modify                modify an existing zone\n";
  cout << "  zone set                   set zone cluster params (requires infile)\n";
  cout << "  zone list                  list all zones set on this cluster\n";
  cout << "  zone rename                rename a zone\n";
  cout << "  zone placement list        list zone's placement targets\n";
  cout << "  zone placement get         get a zone placement target\n";
  cout << "  zone placement add         add a zone placement target\n";
  cout << "  zone placement modify      modify a zone placement target\n";
  cout << "  zone placement rm          remove a zone placement target\n";
  cout << "  metadata sync status       get metadata sync status\n";
  cout << "  metadata sync init         init metadata sync\n";
  cout << "  metadata sync run          run metadata sync\n";
  cout << "  data sync status           get data sync status of the specified source zone\n";
  cout << "  data sync init             init data sync for the specified source zone\n";
  cout << "  data sync run              run data sync for the specified source zone\n";
  cout << "  pool add                   add an existing pool for data placement\n";
  cout << "  pool rm                    remove an existing pool from data placement set\n";
  cout << "  pools list                 list placement active set\n";
  cout << "  policy                     read bucket/object policy\n";
  cout << "  log list                   list log objects\n";
  cout << "  log show                   dump a log from specific object or (bucket + date\n";
  cout << "                             + bucket-id)\n";
  cout << "                             (NOTE: required to specify formatting of date\n";
  cout << "                             to \"YYYY-MM-DD-hh\")\n";
  cout << "  log rm                     remove log object\n";
  cout << "  usage show                 show usage (by user, by bucket, date range)\n";
  cout << "  usage trim                 trim usage (by user, by bucket, date range)\n";
  cout << "  usage clear                reset all the usage stats for the cluster\n";
  cout << "  gc list                    dump expired garbage collection objects (specify\n";
  cout << "                             --include-all to list all entries, including unexpired)\n";
  cout << "  gc process                 manually process garbage (specify\n";
  cout << "                             --include-all to process all entries, including unexpired)\n";
  cout << "  lc list                    list all bucket lifecycle progress\n";
  cout << "  lc get                     get a lifecycle bucket configuration\n";
  cout << "  lc process                 manually process lifecycle\n";
  cout << "  lc reshard fix             fix LC for a resharded bucket\n";
  cout << "  metadata get               get metadata info\n";
  cout << "  metadata put               put metadata info\n";
  cout << "  metadata rm                remove metadata info\n";
  cout << "  metadata list              list metadata info\n";
  cout << "  mdlog list                 list metadata log\n";
  cout << "  mdlog trim                 trim metadata log (use marker)\n";
  cout << "  mdlog status               read metadata log status\n";
  cout << "  bilog list                 list bucket index log\n";
  cout << "  bilog trim                 trim bucket index log (use start-marker, end-marker)\n";
  cout << "  bilog status               read bucket index log status\n";
  cout << "  datalog list               list data log\n";
  cout << "  datalog trim               trim data log\n";
  cout << "  datalog status             read data log status\n";
  cout << "  datalog type               change datalog type to --log_type={fifo,omap}\n";
  cout << "  orphans find               deprecated -- init and run search for leaked rados objects (use job-id, pool)\n";
  cout << "  orphans finish             deprecated -- clean up search for leaked rados objects\n";
  cout << "  orphans list-jobs          deprecated -- list the current job-ids for orphans search\n";
  cout << "                           * the three 'orphans' sub-commands are now deprecated; consider using the `rgw-orphan-list` tool\n";
  cout << "  role create                create a AWS role for use with STS\n";
  cout << "  role rm                    remove a role\n";
  cout << "  role get                   get a role\n";
  cout << "  role list                  list roles with specified path prefix\n";
  cout << "  role modify                modify the assume role policy of an existing role\n";
  cout << "  role-policy put            add/update permission policy to role\n";
  cout << "  role-policy list           list policies attached to a role\n";
  cout << "  role-policy get            get the specified inline policy document embedded with the given role\n";
  cout << "  role-policy rm             remove policy attached to a role\n";
  cout << "  reshard add                schedule a resharding of a bucket\n";
  cout << "  reshard list               list all bucket resharding or scheduled to be resharded\n";
  cout << "  reshard status             read bucket resharding status\n";
  cout << "  reshard process            process of scheduled reshard jobs\n";
  cout << "  reshard cancel             cancel resharding a bucket\n";
  cout << "  reshard stale-instances list list stale-instances from bucket resharding\n";
  cout << "  reshard stale-instances rm   cleanup stale-instances from bucket resharding\n";
  cout << "  sync error list            list sync error\n";
  cout << "  sync error trim            trim sync error\n";
  cout << "  mfa create                 create a new MFA TOTP token\n";
  cout << "  mfa list                   list MFA TOTP tokens\n";
  cout << "  mfa get                    show MFA TOTP token\n";
  cout << "  mfa remove                 delete MFA TOTP token\n";
  cout << "  mfa check                  check MFA TOTP token\n";
  cout << "  mfa resync                 re-sync MFA TOTP token\n";
  cout << "  topic list                 list bucket notifications/pubsub topics\n";
  cout << "  topic get                  get a bucket notifications/pubsub topic\n";
  cout << "  topic rm                   remove a bucket notifications/pubsub topic\n";
  cout << "  subscription get           get a pubsub subscription definition\n";
  cout << "  subscription rm            remove a pubsub subscription\n";
  cout << "  subscription pull          show events in a pubsub subscription\n";
  cout << "  subscription ack           ack (remove) an events in a pubsub subscription\n";
  cout << "  script put                 upload a lua script to a context\n";
  cout << "  script get                 get the lua script of a context\n";
  cout << "  script rm                  remove the lua scripts of a context\n";
  cout << "  script-package add         add a lua package to the scripts allowlist\n";
  cout << "  script-package rm          remove a lua package from the scripts allowlist\n";
  cout << "  script-package list        get the lua packages allowlist\n";
  cout << "options:\n";
  cout << "   --tenant=<tenant>         tenant name\n";
  cout << "   --user_ns=<namespace>     namespace of user (oidc in case of users authenticated with oidc provider)\n";
  cout << "   --uid=<id>                user id\n";
  cout << "   --new-uid=<id>            new user id\n";
  cout << "   --subuser=<name>          subuser name\n";
  cout << "   --access-key=<key>        S3 access key\n";
  cout << "   --email=<email>           user's email address\n";
  cout << "   --secret/--secret-key=<key>\n";
  cout << "                             specify secret key\n";
  cout << "   --gen-access-key          generate random access key (for S3)\n";
  cout << "   --gen-secret              generate random secret key\n";
  cout << "   --key-type=<type>         key type, options are: swift, s3\n";
  cout << "   --temp-url-key[-2]=<key>  temp url key\n";
  cout << "   --access=<access>         Set access permissions for sub-user, should be one\n";
  cout << "                             of read, write, readwrite, full\n";
  cout << "   --display-name=<name>     user's display name\n";
  cout << "   --max-buckets             max number of buckets for a user\n";
  cout << "   --admin                   set the admin flag on the user\n";
  cout << "   --system                  set the system flag on the user\n";
  cout << "   --op-mask                 set the op mask on the user\n";
  cout << "   --bucket=<bucket>         Specify the bucket name. Also used by the quota command.\n";
  cout << "   --pool=<pool>             Specify the pool name. Also used to scan for leaked rados objects.\n";
  cout << "   --object=<object>         object name\n";
  cout << "   --object-version=<version>         object version\n";
  cout << "   --date=<date>             date in the format yyyy-mm-dd\n";
  cout << "   --start-date=<date>       start date in the format yyyy-mm-dd\n";
  cout << "   --end-date=<date>         end date in the format yyyy-mm-dd\n";
  cout << "   --bucket-id=<bucket-id>   bucket id\n";
  cout << "   --bucket-new-name=<bucket>\n";
  cout << "                             for bucket link: optional new name\n";
  cout << "   --shard-id=<shard-id>     optional for: \n";
  cout << "                               mdlog list\n";
  cout << "                               data sync status\n";
  cout << "                             required for: \n";
  cout << "                               mdlog trim\n";
  cout << "   --max-entries=<entries>   max entries for listing operations\n";
  cout << "   --metadata-key=<key>      key to retrieve metadata from with metadata get\n";
  cout << "   --remote=<remote>         zone or zonegroup id of remote gateway\n";
  cout << "   --period=<id>             period id\n";
  cout << "   --url=<url>               url for pushing/pulling period/realm\n";
  cout << "   --epoch=<number>          period epoch\n";
  cout << "   --commit                  commit the period during 'period update'\n";
  cout << "   --staging                 get staging period info\n";
  cout << "   --master                  set as master\n";
  cout << "   --master-zone=<id>        master zone id\n";
  cout << "   --rgw-realm=<name>        realm name\n";
  cout << "   --realm-id=<id>           realm id\n";
  cout << "   --realm-new-name=<name>   realm new name\n";
  cout << "   --rgw-zonegroup=<name>    zonegroup name\n";
  cout << "   --zonegroup-id=<id>       zonegroup id\n";
  cout << "   --zonegroup-new-name=<name>\n";
  cout << "                             zonegroup new name\n";
  cout << "   --rgw-zone=<name>         name of zone in which radosgw is running\n";
  cout << "   --zone-id=<id>            zone id\n";
  cout << "   --zone-new-name=<name>    zone new name\n";
  cout << "   --source-zone             specify the source zone (for data sync)\n";
  cout << "   --default                 set entity (realm, zonegroup, zone) as default\n";
  cout << "   --read-only               set zone as read-only (when adding to zonegroup)\n";
  cout << "   --redirect-zone           specify zone id to redirect when response is 404 (not found)\n";
  cout << "   --placement-id            placement id for zonegroup placement commands\n";
  cout << "   --storage-class           storage class for zonegroup placement commands\n";
  cout << "   --tags=<list>             list of tags for zonegroup placement add and modify commands\n";
  cout << "   --tags-add=<list>         list of tags to add for zonegroup placement modify command\n";
  cout << "   --tags-rm=<list>          list of tags to remove for zonegroup placement modify command\n";
  cout << "   --endpoints=<list>        zone endpoints\n";
  cout << "   --index-pool=<pool>       placement target index pool\n";
  cout << "   --data-pool=<pool>        placement target data pool\n";
  cout << "   --data-extra-pool=<pool>  placement target data extra (non-ec) pool\n";
  cout << "   --placement-index-type=<type>\n";
  cout << "                             placement target index type (normal, indexless, or #id)\n";
  cout << "   --compression=<type>      placement target compression type (plugin name or empty/none)\n";
  cout << "   --tier-type=<type>        zone tier type\n";
  cout << "   --tier-config=<k>=<v>[,...]\n";
  cout << "                             set zone tier config keys, values\n";
  cout << "   --tier-config-rm=<k>[,...]\n";
  cout << "                             unset zone tier config keys\n";
  cout << "   --sync-from-all[=false]   set/reset whether zone syncs from all zonegroup peers\n";
  cout << "   --sync-from=[zone-name][,...]\n";
  cout << "                             set list of zones to sync from\n";
  cout << "   --sync-from-rm=[zone-name][,...]\n";
  cout << "                             remove zones from list of zones to sync from\n";
  cout << "   --bucket-index-max-shards override a zone/zonegroup's default bucket index shard count\n";
  cout << "   --fix                     besides checking bucket index, will also fix it\n";
  cout << "   --check-objects           bucket check: rebuilds bucket index according to\n";
  cout << "                             actual objects state\n";
  cout << "   --format=<format>         specify output format for certain operations: xml,\n";
  cout << "                             json\n";
  cout << "   --purge-data              when specified, user removal will also purge all the\n";
  cout << "                             user data\n";
  cout << "   --purge-keys              when specified, subuser removal will also purge all the\n";
  cout << "                             subuser keys\n";
  cout << "   --purge-objects           remove a bucket's objects before deleting it\n";
  cout << "                             (NOTE: required to delete a non-empty bucket)\n";
  cout << "   --sync-stats              option to 'user stats', update user stats with current\n";
  cout << "                             stats reported by user's buckets indexes\n";
  cout << "   --reset-stats             option to 'user stats', reset stats in accordance with user buckets\n";
  cout << "   --show-log-entries=<flag> enable/disable dump of log entries on log show\n";
  cout << "   --show-log-sum=<flag>     enable/disable dump of log summation on log show\n";
  cout << "   --skip-zero-entries       log show only dumps entries that don't have zero value\n";
  cout << "                             in one of the numeric field\n";
  cout << "   --infile=<file>           specify a file to read in when setting data\n";
  cout << "   --categories=<list>       comma separated list of categories, used in usage show\n";
  cout << "   --caps=<caps>             list of caps (e.g., \"usage=read, write; user=read\")\n";
  cout << "   --op-mask=<op-mask>       permission of user's operations (e.g., \"read, write, delete, *\")\n";
  cout << "   --yes-i-really-mean-it    required for certain operations\n";
  cout << "   --warnings-only           when specified with bucket limit check, list\n";
  cout << "                             only buckets nearing or over the current max\n";
  cout << "                             objects per shard value\n";
  cout << "   --bypass-gc               when specified with bucket deletion, triggers\n";
  cout << "                             object deletions by not involving GC\n";
  cout << "   --inconsistent-index      when specified with bucket deletion and bypass-gc set to true,\n";
  cout << "                             ignores bucket index consistency\n";
  cout << "   --min-rewrite-size        min object size for bucket rewrite (default 4M)\n";
  cout << "   --max-rewrite-size        max object size for bucket rewrite (default ULLONG_MAX)\n";
  cout << "   --min-rewrite-stripe-size min stripe size for object rewrite (default 0)\n";
  cout << "   --trim-delay-ms           time interval in msec to limit the frequency of sync error log entries trimming operations,\n";
  cout << "                             the trimming process will sleep the specified msec for every 1000 entries trimmed\n";
  cout << "   --max-concurrent-ios      maximum concurrent ios for bucket operations (default: 32)\n";
  cout << "\n";
  cout << "<date> := \"YYYY-MM-DD[ hh:mm:ss]\"\n";
  cout << "\nQuota options:\n";
  cout << "   --max-objects             specify max objects (negative value to disable)\n";
  cout << "   --max-size                specify max size (in B/K/M/G/T, negative value to disable)\n";
  cout << "   --quota-scope             scope of quota (bucket, user)\n";
  cout << "\nOrphans search options:\n";
  cout << "   --num-shards              num of shards to use for keeping the temporary scan info\n";
  cout << "   --orphan-stale-secs       num of seconds to wait before declaring an object to be an orphan (default: 86400)\n";
  cout << "   --job-id                  set the job id (for orphans find)\n";
  cout << "   --detail                  detailed mode, log and stat head objects as well\n";
  cout << "\nOrphans list-jobs options:\n";
  cout << "   --extra-info              provide extra info in job list\n";
  cout << "\nRole options:\n";
  cout << "   --role-name               name of the role to create\n";
  cout << "   --path                    path to the role\n";
  cout << "   --assume-role-policy-doc  the trust relationship policy document that grants an entity permission to assume the role\n";
  cout << "   --policy-name             name of the policy document\n";
  cout << "   --policy-doc              permission policy document\n";
  cout << "   --path-prefix             path prefix for filtering roles\n";
  cout << "\nMFA options:\n";
  cout << "   --totp-serial             a string that represents the ID of a TOTP token\n";
  cout << "   --totp-seed               the secret seed that is used to calculate the TOTP\n";
  cout << "   --totp-seconds            the time resolution that is being used for TOTP generation\n";
  cout << "   --totp-window             the number of TOTP tokens that are checked before and after the current token when validating token\n";
  cout << "   --totp-pin                the valid value of a TOTP token at a certain time\n";
  cout << "\nBucket notifications/pubsub options:\n";
  cout << "   --topic                   bucket notifications/pubsub topic name\n";
  cout << "   --subscription            pubsub subscription name\n";
  cout << "   --event-id                event id in a pubsub subscription\n";
  cout << "\nScript options:\n";
  cout << "   --context                 context in which the script runs. one of: preRequest, postRequest\n";
  cout << "   --package                 name of the lua package that should be added/removed to/from the allowlist\n";
  cout << "   --allow-compilation       package is allowed to compile C code as part of its installation\n";
  cout << "\nradoslist options:\n";
  cout << "   --rgw-obj-fs              the field separator that will separate the rados\n";
  cout << "                             object name from the rgw object name;\n";
  cout << "                             additionally rados objects for incomplete\n";
  cout << "                             multipart uploads will not be output\n";
  cout << "\n";
  generic_client_usage();
}


class SimpleCmd {
public:
  struct Def {
    string cmd;
    std::any opt;
  };

  using Aliases = std::vector<std::set<string> >;
  using Commands = std::vector<Def>;

private:
  struct Node {
    map<string, Node> next;
    set<string> expected; /* separate un-normalized list */
    std::any opt;
  };

  Node cmd_root;
  map<string, string> alias_map;

  string normalize_alias(const string& s) const {
    auto iter = alias_map.find(s);
    if (iter == alias_map.end()) {
      return s;
    }

    return iter->second;
  }
  void init_alias_map(Aliases& aliases) {
    for (auto& alias_set : aliases) {
      std::optional<string> first;

      for (auto& alias : alias_set) {
        if (!first) {
          first = alias;
        } else {
          alias_map[alias] = *first;
        }
      }
    }
  }

  bool gen_next_expected(Node *node, vector<string> *expected, bool ret) {
    for (auto& next_cmd : node->expected) {
      expected->push_back(next_cmd);
    }
    return ret;
  }

  Node root;

public:
  SimpleCmd() {}

  SimpleCmd(std::optional<Commands> cmds,
            std::optional<Aliases> aliases) {
    if (aliases) {
      add_aliases(*aliases);
    }

    if (cmds) {
      add_commands(*cmds);
    }
  }

  void add_aliases(Aliases& aliases) {
    init_alias_map(aliases);
  }

  void add_commands(std::vector<Def>& cmds) {
    for (auto& cmd : cmds) {
      vector<string> words;
      get_str_vec(cmd.cmd, " ", words);

      auto node = &cmd_root;
      for (auto& word : words) {
        auto norm = normalize_alias(word);
        auto parent = node;

        node->expected.insert(word);

        node = &node->next[norm];

        if (norm == "[*]") { /* optional param at the end */
          parent->next["*"] = *node; /* can be also looked up by '*' */
          parent->opt = cmd.opt;
        }
      }

      node->opt = cmd.opt;
    }
  }

  template <class Container>
  bool find_command(Container& args,
                    std::any *opt_cmd,
                    vector<string> *extra_args,
                    string *error,
                    vector<string> *expected) {
    auto node = &cmd_root;

    std::optional<std::any> found_opt;

    for (auto& arg : args) {
      string norm = normalize_alias(arg);
      auto iter = node->next.find(norm);
      if (iter == node->next.end()) {
        iter = node->next.find("*");
        if (iter == node->next.end()) {
          *error = string("ERROR: Unrecognized argument: '") + arg + "'";
          return gen_next_expected(node, expected, false);
        }
        extra_args->push_back(arg);
        if (!found_opt) {
          found_opt = node->opt;
        }
      }
      node = &(iter->second);
    }

    *opt_cmd = found_opt.value_or(node->opt);

    if (!opt_cmd->has_value()) {
      *error ="ERROR: Unknown command";
      return gen_next_expected(node, expected, false);
    }

    return true;
  }
};


namespace rgw_admin {

enum class OPT {
  NO_CMD,
  USER_CREATE,
  USER_INFO,
  USER_MODIFY,
  USER_RENAME,
  USER_RM,
  USER_SUSPEND,
  USER_ENABLE,
  USER_CHECK,
  USER_STATS,
  USER_LIST,
  SUBUSER_CREATE,
  SUBUSER_MODIFY,
  SUBUSER_RM,
  KEY_CREATE,
  KEY_RM,
  BUCKETS_LIST,
  BUCKET_LIMIT_CHECK,
  BUCKET_LINK,
  BUCKET_UNLINK,
  BUCKET_STATS,
  BUCKET_CHECK,
  BUCKET_SYNC_CHECKPOINT,
  BUCKET_SYNC_INFO,
  BUCKET_SYNC_STATUS,
  BUCKET_SYNC_MARKERS,
  BUCKET_SYNC_INIT,
  BUCKET_SYNC_RUN,
  BUCKET_SYNC_DISABLE,
  BUCKET_SYNC_ENABLE,
  BUCKET_RM,
  BUCKET_REWRITE,
  BUCKET_RESHARD,
  BUCKET_CHOWN,
  BUCKET_RADOS_LIST,
  POLICY,
  POOL_ADD,
  POOL_RM,
  POOLS_LIST,
  LOG_LIST,
  LOG_SHOW,
  LOG_RM,
  USAGE_SHOW,
  USAGE_TRIM,
  USAGE_CLEAR,
  OBJECT_PUT,
  OBJECT_RM,
  OBJECT_UNLINK,
  OBJECT_STAT,
  OBJECT_REWRITE,
  OBJECTS_EXPIRE,
  OBJECTS_EXPIRE_STALE_LIST,
  OBJECTS_EXPIRE_STALE_RM,
  BI_GET,
  BI_PUT,
  BI_LIST,
  BI_PURGE,
  OLH_GET,
  OLH_READLOG,
  QUOTA_SET,
  QUOTA_ENABLE,
  QUOTA_DISABLE,
  GC_LIST,
  GC_PROCESS,
  LC_LIST,
  LC_GET,
  LC_PROCESS,
  LC_RESHARD_FIX,
  ORPHANS_FIND,
  ORPHANS_FINISH,
  ORPHANS_LIST_JOBS,
  ZONEGROUP_ADD,
  ZONEGROUP_CREATE,
  ZONEGROUP_DEFAULT,
  ZONEGROUP_DELETE,
  ZONEGROUP_GET,
  ZONEGROUP_MODIFY,
  ZONEGROUP_SET,
  ZONEGROUP_LIST,
  ZONEGROUP_REMOVE,
  ZONEGROUP_RENAME,
  ZONEGROUP_PLACEMENT_ADD,
  ZONEGROUP_PLACEMENT_MODIFY,
  ZONEGROUP_PLACEMENT_RM,
  ZONEGROUP_PLACEMENT_LIST,
  ZONEGROUP_PLACEMENT_GET,
  ZONEGROUP_PLACEMENT_DEFAULT,
  ZONE_CREATE,
  ZONE_DELETE,
  ZONE_GET,
  ZONE_MODIFY,
  ZONE_SET,
  ZONE_LIST,
  ZONE_RENAME,
  ZONE_DEFAULT,
  ZONE_PLACEMENT_ADD,
  ZONE_PLACEMENT_MODIFY,
  ZONE_PLACEMENT_RM,
  ZONE_PLACEMENT_LIST,
  ZONE_PLACEMENT_GET,
  CAPS_ADD,
  CAPS_RM,
  METADATA_GET,
  METADATA_PUT,
  METADATA_RM,
  METADATA_LIST,
  METADATA_SYNC_STATUS,
  METADATA_SYNC_INIT,
  METADATA_SYNC_RUN,
  MDLOG_LIST,
  MDLOG_AUTOTRIM,
  MDLOG_TRIM,
  MDLOG_FETCH,
  MDLOG_STATUS,
  SYNC_ERROR_LIST,
  SYNC_ERROR_TRIM,
  SYNC_GROUP_CREATE,
  SYNC_GROUP_MODIFY,
  SYNC_GROUP_GET,
  SYNC_GROUP_REMOVE,
  SYNC_GROUP_FLOW_CREATE,
  SYNC_GROUP_FLOW_REMOVE,
  SYNC_GROUP_PIPE_CREATE,
  SYNC_GROUP_PIPE_MODIFY,
  SYNC_GROUP_PIPE_REMOVE,
  SYNC_POLICY_GET,
  BILOG_LIST,
  BILOG_TRIM,
  BILOG_STATUS,
  BILOG_AUTOTRIM,
  DATA_SYNC_STATUS,
  DATA_SYNC_INIT,
  DATA_SYNC_RUN,
  DATALOG_LIST,
  DATALOG_STATUS,
  DATALOG_AUTOTRIM,
  DATALOG_TRIM,
  DATALOG_TYPE,
  DATALOG_PRUNE,
  REALM_CREATE,
  REALM_DELETE,
  REALM_GET,
  REALM_GET_DEFAULT,
  REALM_LIST,
  REALM_LIST_PERIODS,
  REALM_RENAME,
  REALM_SET,
  REALM_DEFAULT,
  REALM_PULL,
  PERIOD_DELETE,
  PERIOD_GET,
  PERIOD_GET_CURRENT,
  PERIOD_PULL,
  PERIOD_PUSH,
  PERIOD_LIST,
  PERIOD_UPDATE,
  PERIOD_COMMIT,
  GLOBAL_QUOTA_GET,
  GLOBAL_QUOTA_SET,
  GLOBAL_QUOTA_ENABLE,
  GLOBAL_QUOTA_DISABLE,
  SYNC_INFO,
  SYNC_STATUS,
  ROLE_CREATE,
  ROLE_DELETE,
  ROLE_GET,
  ROLE_MODIFY,
  ROLE_LIST,
  ROLE_POLICY_PUT,
  ROLE_POLICY_LIST,
  ROLE_POLICY_GET,
  ROLE_POLICY_DELETE,
  RESHARD_ADD,
  RESHARD_LIST,
  RESHARD_STATUS,
  RESHARD_PROCESS,
  RESHARD_CANCEL,
  MFA_CREATE,
  MFA_REMOVE,
  MFA_GET,
  MFA_LIST,
  MFA_CHECK,
  MFA_RESYNC,
  RESHARD_STALE_INSTANCES_LIST,
  RESHARD_STALE_INSTANCES_DELETE,
  PUBSUB_TOPICS_LIST,
  // TODO add "subscription list" command
  PUBSUB_TOPIC_GET,
  PUBSUB_TOPIC_RM,
  PUBSUB_SUB_GET,
  PUBSUB_SUB_RM,
  PUBSUB_SUB_PULL,
  PUBSUB_EVENT_RM,
  SCRIPT_PUT,
  SCRIPT_GET,
  SCRIPT_RM,
  SCRIPT_PACKAGE_ADD,
  SCRIPT_PACKAGE_RM,
  SCRIPT_PACKAGE_LIST
};

}

using namespace rgw_admin;

static SimpleCmd::Commands all_cmds = {
  { "user create", OPT::USER_CREATE },
  { "user info", OPT::USER_INFO },
  { "user modify", OPT::USER_MODIFY },
  { "user rename", OPT::USER_RENAME },
  { "user rm", OPT::USER_RM },
  { "user suspend", OPT::USER_SUSPEND },
  { "user enable", OPT::USER_ENABLE },
  { "user check", OPT::USER_CHECK },
  { "user stats", OPT::USER_STATS },
  { "user list", OPT::USER_LIST },
  { "subuser create", OPT::SUBUSER_CREATE },
  { "subuser modify", OPT::SUBUSER_MODIFY },
  { "subuser rm", OPT::SUBUSER_RM },
  { "key create", OPT::KEY_CREATE },
  { "key rm", OPT::KEY_RM },
  { "buckets list", OPT::BUCKETS_LIST },
  { "bucket list", OPT::BUCKETS_LIST },
  { "bucket limit check", OPT::BUCKET_LIMIT_CHECK },
  { "bucket link", OPT::BUCKET_LINK },
  { "bucket unlink", OPT::BUCKET_UNLINK },
  { "bucket stats", OPT::BUCKET_STATS },
  { "bucket check", OPT::BUCKET_CHECK },
  { "bucket sync checkpoint", OPT::BUCKET_SYNC_CHECKPOINT },
  { "bucket sync info", OPT::BUCKET_SYNC_INFO },
  { "bucket sync status", OPT::BUCKET_SYNC_STATUS },
  { "bucket sync markers", OPT::BUCKET_SYNC_MARKERS },
  { "bucket sync init", OPT::BUCKET_SYNC_INIT },
  { "bucket sync run", OPT::BUCKET_SYNC_RUN },
  { "bucket sync disable", OPT::BUCKET_SYNC_DISABLE },
  { "bucket sync enable", OPT::BUCKET_SYNC_ENABLE },
  { "bucket rm", OPT::BUCKET_RM },
  { "bucket rewrite", OPT::BUCKET_REWRITE },
  { "bucket reshard", OPT::BUCKET_RESHARD },
  { "bucket chown", OPT::BUCKET_CHOWN },
  { "bucket radoslist", OPT::BUCKET_RADOS_LIST },
  { "bucket rados list", OPT::BUCKET_RADOS_LIST },
  { "policy", OPT::POLICY },
  { "pool add", OPT::POOL_ADD },
  { "pool rm", OPT::POOL_RM },
  { "pool list", OPT::POOLS_LIST },
  { "pools list", OPT::POOLS_LIST },
  { "log list", OPT::LOG_LIST },
  { "log show", OPT::LOG_SHOW },
  { "log rm", OPT::LOG_RM },
  { "usage show", OPT::USAGE_SHOW },
  { "usage trim", OPT::USAGE_TRIM },
  { "usage clear", OPT::USAGE_CLEAR },
  { "object put", OPT::OBJECT_PUT },
  { "object rm", OPT::OBJECT_RM },
  { "object unlink", OPT::OBJECT_UNLINK },
  { "object stat", OPT::OBJECT_STAT },
  { "object rewrite", OPT::OBJECT_REWRITE },
  { "objects expire", OPT::OBJECTS_EXPIRE },
  { "objects expire-stale list", OPT::OBJECTS_EXPIRE_STALE_LIST },
  { "objects expire-stale rm", OPT::OBJECTS_EXPIRE_STALE_RM },
  { "bi get", OPT::BI_GET },
  { "bi put", OPT::BI_PUT },
  { "bi list", OPT::BI_LIST },
  { "bi purge", OPT::BI_PURGE },
  { "olh get", OPT::OLH_GET },
  { "olh readlog", OPT::OLH_READLOG },
  { "quota set", OPT::QUOTA_SET },
  { "quota enable", OPT::QUOTA_ENABLE },
  { "quota disable", OPT::QUOTA_DISABLE },
  { "gc list", OPT::GC_LIST },
  { "gc process", OPT::GC_PROCESS },
  { "lc list", OPT::LC_LIST },
  { "lc get", OPT::LC_GET },
  { "lc process", OPT::LC_PROCESS },
  { "lc reshard fix", OPT::LC_RESHARD_FIX },
  { "orphans find", OPT::ORPHANS_FIND },
  { "orphans finish", OPT::ORPHANS_FINISH },
  { "orphans list jobs", OPT::ORPHANS_LIST_JOBS },
  { "orphans list-jobs", OPT::ORPHANS_LIST_JOBS },
  { "zonegroup add", OPT::ZONEGROUP_ADD },
  { "zonegroup create", OPT::ZONEGROUP_CREATE },
  { "zonegroup default", OPT::ZONEGROUP_DEFAULT },
  { "zonegroup delete", OPT::ZONEGROUP_DELETE },
  { "zonegroup get", OPT::ZONEGROUP_GET },
  { "zonegroup modify", OPT::ZONEGROUP_MODIFY },
  { "zonegroup set", OPT::ZONEGROUP_SET },
  { "zonegroup list", OPT::ZONEGROUP_LIST },
  { "zonegroups list", OPT::ZONEGROUP_LIST },
  { "zonegroup remove", OPT::ZONEGROUP_REMOVE },
  { "zonegroup remove zone", OPT::ZONEGROUP_REMOVE },
  { "zonegroup rename", OPT::ZONEGROUP_RENAME },
  { "zonegroup placement add", OPT::ZONEGROUP_PLACEMENT_ADD },
  { "zonegroup placement modify", OPT::ZONEGROUP_PLACEMENT_MODIFY },
  { "zonegroup placement rm", OPT::ZONEGROUP_PLACEMENT_RM },
  { "zonegroup placement list", OPT::ZONEGROUP_PLACEMENT_LIST },
  { "zonegroup placement get", OPT::ZONEGROUP_PLACEMENT_GET },
  { "zonegroup placement default", OPT::ZONEGROUP_PLACEMENT_DEFAULT },
  { "zone create", OPT::ZONE_CREATE },
  { "zone delete", OPT::ZONE_DELETE },
  { "zone get", OPT::ZONE_GET },
  { "zone modify", OPT::ZONE_MODIFY },
  { "zone set", OPT::ZONE_SET },
  { "zone list", OPT::ZONE_LIST },
  { "zones list", OPT::ZONE_LIST },
  { "zone rename", OPT::ZONE_RENAME },
  { "zone default", OPT::ZONE_DEFAULT },
  { "zone placement add", OPT::ZONE_PLACEMENT_ADD },
  { "zone placement modify", OPT::ZONE_PLACEMENT_MODIFY },
  { "zone placement rm", OPT::ZONE_PLACEMENT_RM },
  { "zone placement list", OPT::ZONE_PLACEMENT_LIST },
  { "zone placement get", OPT::ZONE_PLACEMENT_GET },
  { "caps add", OPT::CAPS_ADD },
  { "caps rm", OPT::CAPS_RM },
  { "metadata get [*]", OPT::METADATA_GET },
  { "metadata put [*]", OPT::METADATA_PUT },
  { "metadata rm [*]", OPT::METADATA_RM },
  { "metadata list [*]", OPT::METADATA_LIST },
  { "metadata sync status", OPT::METADATA_SYNC_STATUS },
  { "metadata sync init", OPT::METADATA_SYNC_INIT },
  { "metadata sync run", OPT::METADATA_SYNC_RUN },
  { "mdlog list", OPT::MDLOG_LIST },
  { "mdlog autotrim", OPT::MDLOG_AUTOTRIM },
  { "mdlog trim", OPT::MDLOG_TRIM },
  { "mdlog fetch", OPT::MDLOG_FETCH },
  { "mdlog status", OPT::MDLOG_STATUS },
  { "sync error list", OPT::SYNC_ERROR_LIST },
  { "sync error trim", OPT::SYNC_ERROR_TRIM },
  { "sync policy get", OPT::SYNC_POLICY_GET },
  { "sync group create", OPT::SYNC_GROUP_CREATE },
  { "sync group modify", OPT::SYNC_GROUP_MODIFY },
  { "sync group get", OPT::SYNC_GROUP_GET },
  { "sync group remove", OPT::SYNC_GROUP_REMOVE },
  { "sync group flow create", OPT::SYNC_GROUP_FLOW_CREATE },
  { "sync group flow remove", OPT::SYNC_GROUP_FLOW_REMOVE },
  { "sync group pipe create", OPT::SYNC_GROUP_PIPE_CREATE },
  { "sync group pipe modify", OPT::SYNC_GROUP_PIPE_MODIFY },
  { "sync group pipe remove", OPT::SYNC_GROUP_PIPE_REMOVE },
  { "bilog list", OPT::BILOG_LIST },
  { "bilog trim", OPT::BILOG_TRIM },
  { "bilog status", OPT::BILOG_STATUS },
  { "bilog autotrim", OPT::BILOG_AUTOTRIM },
  { "data sync status", OPT::DATA_SYNC_STATUS },
  { "data sync init", OPT::DATA_SYNC_INIT },
  { "data sync run", OPT::DATA_SYNC_RUN },
  { "datalog list", OPT::DATALOG_LIST },
  { "datalog status", OPT::DATALOG_STATUS },
  { "datalog autotrim", OPT::DATALOG_AUTOTRIM },
  { "datalog trim", OPT::DATALOG_TRIM },
  { "datalog type", OPT::DATALOG_TYPE },
  { "datalog prune", OPT::DATALOG_PRUNE },
  { "realm create", OPT::REALM_CREATE },
  { "realm delete", OPT::REALM_DELETE },
  { "realm get", OPT::REALM_GET },
  { "realm get default", OPT::REALM_GET_DEFAULT },
  { "realm get-default", OPT::REALM_GET_DEFAULT },
  { "realm list", OPT::REALM_LIST },
  { "realm list periods", OPT::REALM_LIST_PERIODS },
  { "realm list-periods", OPT::REALM_LIST_PERIODS },
  { "realm rename", OPT::REALM_RENAME },
  { "realm set", OPT::REALM_SET },
  { "realm default", OPT::REALM_DEFAULT },
  { "realm pull", OPT::REALM_PULL },
  { "period delete", OPT::PERIOD_DELETE },
  { "period get", OPT::PERIOD_GET },
  { "period get-current", OPT::PERIOD_GET_CURRENT },
  { "period get current", OPT::PERIOD_GET_CURRENT },
  { "period pull", OPT::PERIOD_PULL },
  { "period push", OPT::PERIOD_PUSH },
  { "period list", OPT::PERIOD_LIST },
  { "period update", OPT::PERIOD_UPDATE },
  { "period commit", OPT::PERIOD_COMMIT },
  { "global quota get", OPT::GLOBAL_QUOTA_GET },
  { "global quota set", OPT::GLOBAL_QUOTA_SET },
  { "global quota enable", OPT::GLOBAL_QUOTA_ENABLE },
  { "global quota disable", OPT::GLOBAL_QUOTA_DISABLE },
  { "sync info", OPT::SYNC_INFO },
  { "sync status", OPT::SYNC_STATUS },
  { "role create", OPT::ROLE_CREATE },
  { "role delete", OPT::ROLE_DELETE },
  { "role get", OPT::ROLE_GET },
  { "role modify", OPT::ROLE_MODIFY },
  { "role list", OPT::ROLE_LIST },
  { "role policy put", OPT::ROLE_POLICY_PUT },
  { "role-policy put", OPT::ROLE_POLICY_PUT },
  { "role policy list", OPT::ROLE_POLICY_LIST },
  { "role-policy list", OPT::ROLE_POLICY_LIST },
  { "role policy get", OPT::ROLE_POLICY_GET },
  { "role-policy get", OPT::ROLE_POLICY_GET },
  { "role policy delete", OPT::ROLE_POLICY_DELETE },
  { "role-policy delete", OPT::ROLE_POLICY_DELETE },
  { "reshard bucket", OPT::BUCKET_RESHARD },
  { "reshard add", OPT::RESHARD_ADD },
  { "reshard list", OPT::RESHARD_LIST },
  { "reshard status", OPT::RESHARD_STATUS },
  { "reshard process", OPT::RESHARD_PROCESS },
  { "reshard cancel", OPT::RESHARD_CANCEL },
  { "mfa create", OPT::MFA_CREATE },
  { "mfa remove", OPT::MFA_REMOVE },
  { "mfa get", OPT::MFA_GET },
  { "mfa list", OPT::MFA_LIST },
  { "mfa check", OPT::MFA_CHECK },
  { "mfa resync", OPT::MFA_RESYNC },
  { "reshard stale-instances list", OPT::RESHARD_STALE_INSTANCES_LIST },
  { "reshard stale list", OPT::RESHARD_STALE_INSTANCES_LIST },
  { "reshard stale-instances delete", OPT::RESHARD_STALE_INSTANCES_DELETE },
  { "reshard stale delete", OPT::RESHARD_STALE_INSTANCES_DELETE },
  { "topic list", OPT::PUBSUB_TOPICS_LIST },
  { "topic get", OPT::PUBSUB_TOPIC_GET },
  { "topic rm", OPT::PUBSUB_TOPIC_RM },
  { "subscription get", OPT::PUBSUB_SUB_GET },
  { "subscription rm", OPT::PUBSUB_SUB_RM },
  { "subscription pull", OPT::PUBSUB_SUB_PULL },
  { "subscription ack", OPT::PUBSUB_EVENT_RM },
  { "script put", OPT::SCRIPT_PUT },
  { "script get", OPT::SCRIPT_GET },
  { "script rm", OPT::SCRIPT_RM },
  { "script-package add", OPT::SCRIPT_PACKAGE_ADD },
  { "script-package rm", OPT::SCRIPT_PACKAGE_RM },
  { "script-package list", OPT::SCRIPT_PACKAGE_LIST },
};

static SimpleCmd::Aliases cmd_aliases = {
  { "delete", "del" },
  { "remove", "rm" },
  { "rename", "mv" },
};



BIIndexType get_bi_index_type(const string& type_str) {
  if (type_str == "plain")
    return BIIndexType::Plain;
  if (type_str == "instance")
    return BIIndexType::Instance;
  if (type_str == "olh")
    return BIIndexType::OLH;

  return BIIndexType::Invalid;
}

log_type get_log_type(const string& type_str) {
  if (strcasecmp(type_str.c_str(), "fifo") == 0)
    return log_type::fifo;
  if (strcasecmp(type_str.c_str(), "omap") == 0)
    return log_type::omap;

  return static_cast<log_type>(0xff);
}

void dump_bi_entry(bufferlist& bl, BIIndexType index_type, Formatter *formatter)
{
  auto iter = bl.cbegin();
  switch (index_type) {
    case BIIndexType::Plain:
    case BIIndexType::Instance:
      {
        rgw_bucket_dir_entry entry;
        decode(entry, iter);
        encode_json("entry", entry, formatter);
      }
      break;
    case BIIndexType::OLH:
      {
        rgw_bucket_olh_entry entry;
        decode(entry, iter);
        encode_json("entry", entry, formatter);
      }
      break;
    default:
      ceph_abort();
      break;
  }
}

static void show_user_info(RGWUserInfo& info, Formatter *formatter)
{
  encode_json("user_info", info, formatter);
  formatter->flush(cout);
  cout << std::endl;
}

static void show_perm_policy(string perm_policy, Formatter* formatter)
{
  formatter->open_object_section("role");
  formatter->dump_string("Permission policy", perm_policy);
  formatter->close_section();
  formatter->flush(cout);
}

static void show_policy_names(std::vector<string> policy_names, Formatter* formatter)
{
  formatter->open_array_section("PolicyNames");
  for (const auto& it : policy_names) {
    formatter->dump_string("policyname", it);
  }
  formatter->close_section();
  formatter->flush(cout);
}

static void show_role_info(RGWRole& role, Formatter* formatter)
{
  formatter->open_object_section("role");
  role.dump(formatter);
  formatter->close_section();
  formatter->flush(cout);
}

static void show_roles_info(vector<RGWRole>& roles, Formatter* formatter)
{
  formatter->open_array_section("Roles");
  for (const auto& it : roles) {
    formatter->open_object_section("role");
    it.dump(formatter);
    formatter->close_section();
  }
  formatter->close_section();
  formatter->flush(cout);
}

static void show_reshard_status(
  const list<cls_rgw_bucket_instance_entry>& status, Formatter *formatter)
{
  formatter->open_array_section("status");
  for (const auto& entry : status) {
    formatter->open_object_section("entry");
    formatter->dump_string("reshard_status", to_string(entry.reshard_status));
    formatter->dump_string("new_bucket_instance_id",
			   entry.new_bucket_instance_id);
    formatter->dump_int("num_shards", entry.num_shards);
    formatter->close_section();
  }
  formatter->close_section();
  formatter->flush(cout);
}

class StoreDestructor {
  rgw::sal::RGWRadosStore *store;
public:
  explicit StoreDestructor(rgw::sal::RGWRadosStore *_s) : store(_s) {}
  ~StoreDestructor() {
    RGWStoreManager::close_storage(store);
    rgw_http_client_cleanup();
  }
};

static int init_bucket(const string& tenant_name,
		       const string& bucket_name,
		       const string& bucket_id,
                       RGWBucketInfo& bucket_info,
		       rgw_bucket& bucket,
		       map<string, bufferlist> *pattrs = nullptr)
{
  if (!bucket_name.empty()) {
    auto obj_ctx = store->svc()->sysobj->init_obj_ctx();
    int r;
    if (bucket_id.empty()) {
      r = store->getRados()->get_bucket_info(store->svc(), tenant_name, bucket_name, bucket_info, nullptr, null_yield, dpp(), pattrs);
    } else {
      string bucket_instance_id = bucket_name + ":" + bucket_id;
      r = store->getRados()->get_bucket_instance_info(obj_ctx, bucket_instance_id, bucket_info, NULL, pattrs, null_yield, dpp());
    }
    if (r < 0) {
      cerr << "could not get bucket info for bucket=" << bucket_name << std::endl;
      return r;
    }
    bucket = bucket_info.bucket;
  }
  return 0;
}

static int init_bucket(const rgw_bucket& b,
                       RGWBucketInfo& bucket_info,
                       rgw_bucket& bucket,
                       map<string, bufferlist> *pattrs = nullptr)
{
  return init_bucket(b.tenant, b.name, b.bucket_id,
                     bucket_info, bucket, pattrs);
}

static int read_input(const string& infile, bufferlist& bl)
{
  int fd = 0;
  if (infile.size()) {
    fd = open(infile.c_str(), O_RDONLY);
    if (fd < 0) {
      int err = -errno;
      cerr << "error reading input file " << infile << std::endl;
      return err;
    }
  }

#define READ_CHUNK 8196
  int r;
  int err;

  do {
    char buf[READ_CHUNK];

    r = safe_read(fd, buf, READ_CHUNK);
    if (r < 0) {
      err = -errno;
      cerr << "error while reading input" << std::endl;
      goto out;
    }
    bl.append(buf, r);
  } while (r > 0);
  err = 0;

 out:
  if (infile.size()) {
    close(fd);
  }
  return err;
}

template <class T>
static int read_decode_json(const string& infile, T& t)
{
  bufferlist bl;
  int ret = read_input(infile, bl);
  if (ret < 0) {
    cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  JSONParser p;
  if (!p.parse(bl.c_str(), bl.length())) {
    cout << "failed to parse JSON" << std::endl;
    return -EINVAL;
  }

  try {
    decode_json_obj(t, &p);
  } catch (const JSONDecoder::err& e) {
    cout << "failed to decode JSON input: " << e.what() << std::endl;
    return -EINVAL;
  }
  return 0;
}

template <class T, class K>
static int read_decode_json(const string& infile, T& t, K *k)
{
  bufferlist bl;
  int ret = read_input(infile, bl);
  if (ret < 0) {
    cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  JSONParser p;
  if (!p.parse(bl.c_str(), bl.length())) {
    cout << "failed to parse JSON" << std::endl;
    return -EINVAL;
  }

  try {
    t.decode_json(&p, k);
  } catch (const JSONDecoder::err& e) {
    cout << "failed to decode JSON input: " << e.what() << std::endl;
    return -EINVAL;
  }
  return 0;
}

template <class T>
static bool decode_dump(const char *field_name, bufferlist& bl, Formatter *f)
{
  T t;

  auto iter = bl.cbegin();

  try {
    decode(t, iter);
  } catch (buffer::error& err) {
    return false;
  }

  encode_json(field_name, t, f);

  return true;
}

static bool dump_string(const char *field_name, bufferlist& bl, Formatter *f)
{
  string val = bl.to_str();
  f->dump_string(field_name, val.c_str() /* hide encoded null termination chars */);

  return true;
}

void set_quota_info(RGWQuotaInfo& quota, OPT opt_cmd, int64_t max_size, int64_t max_objects,
                    bool have_max_size, bool have_max_objects)
{
  switch (opt_cmd) {
    case OPT::QUOTA_ENABLE:
    case OPT::GLOBAL_QUOTA_ENABLE:
      quota.enabled = true;

      // falling through on purpose

    case OPT::QUOTA_SET:
    case OPT::GLOBAL_QUOTA_SET:
      if (have_max_objects) {
        if (max_objects < 0) {
          quota.max_objects = -1;
        } else {
          quota.max_objects = max_objects;
        }
      }
      if (have_max_size) {
        if (max_size < 0) {
          quota.max_size = -1;
        } else {
          quota.max_size = rgw_rounded_kb(max_size) * 1024;
        }
      }
      break;
    case OPT::QUOTA_DISABLE:
    case OPT::GLOBAL_QUOTA_DISABLE:
      quota.enabled = false;
      break;
    default:
      break;
  }
}

int set_bucket_quota(rgw::sal::RGWRadosStore *store, OPT opt_cmd,
                     const string& tenant_name, const string& bucket_name,
                     int64_t max_size, int64_t max_objects,
                     bool have_max_size, bool have_max_objects)
{
  RGWBucketInfo bucket_info;
  map<string, bufferlist> attrs;
  int r = store->getRados()->get_bucket_info(store->svc(), tenant_name, bucket_name, bucket_info, NULL, null_yield, dpp(), &attrs);
  if (r < 0) {
    cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl;
    return -r;
  }

  set_quota_info(bucket_info.quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);

   r = store->getRados()->put_bucket_instance_info(bucket_info, false, real_time(), &attrs, dpp());
  if (r < 0) {
    cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl;
    return -r;
  }
  return 0;
}

int set_user_bucket_quota(OPT opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects,
                          bool have_max_size, bool have_max_objects)
{
  RGWUserInfo& user_info = op_state.get_user_info();

  set_quota_info(user_info.bucket_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);

  op_state.set_bucket_quota(user_info.bucket_quota);

  string err;
  int r = user.modify(dpp(), op_state, null_yield, &err);
  if (r < 0) {
    cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl;
    return -r;
  }
  return 0;
}

int set_user_quota(OPT opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects,
                   bool have_max_size, bool have_max_objects)
{
  RGWUserInfo& user_info = op_state.get_user_info();

  set_quota_info(user_info.user_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);

  op_state.set_user_quota(user_info.user_quota);

  string err;
  int r = user.modify(dpp(), op_state, null_yield, &err);
  if (r < 0) {
    cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl;
    return -r;
  }
  return 0;
}

int check_min_obj_stripe_size(rgw::sal::RGWRadosStore *store, RGWBucketInfo& bucket_info, rgw::sal::RGWObject* obj, uint64_t min_stripe_size, bool *need_rewrite)
{
  RGWObjectCtx obj_ctx(store);
  int ret = obj->get_obj_attrs(&obj_ctx, null_yield, dpp());
  if (ret < 0) {
    ldpp_dout(dpp(), -1) << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << dendl;
    return ret;
  }

  map<string, bufferlist>::iterator iter;
  iter = obj->get_attrs().find(RGW_ATTR_MANIFEST);
  if (iter == obj->get_attrs().end()) {
    *need_rewrite = (obj->get_obj_size() >= min_stripe_size);
    return 0;
  }

  RGWObjManifest manifest;

  try {
    bufferlist& bl = iter->second;
    auto biter = bl.cbegin();
    decode(manifest, biter);
  } catch (buffer::error& err) {
    ldpp_dout(dpp(), 0) << "ERROR: failed to decode manifest" << dendl;
    return -EIO;
  }

  map<uint64_t, RGWObjManifestPart>& objs = manifest.get_explicit_objs();
  map<uint64_t, RGWObjManifestPart>::iterator oiter;
  for (oiter = objs.begin(); oiter != objs.end(); ++oiter) {
    RGWObjManifestPart& part = oiter->second;

    if (part.size >= min_stripe_size) {
      *need_rewrite = true;
      return 0;
    }
  }
  *need_rewrite = false;

  return 0;
}


int check_obj_locator_underscore(RGWBucketInfo& bucket_info, rgw_obj& obj, rgw_obj_key& key, bool fix, bool remove_bad, Formatter *f) {
  f->open_object_section("object");
  f->open_object_section("key");
  f->dump_string("type", "head");
  f->dump_string("name", key.name);
  f->dump_string("instance", key.instance);
  f->close_section();

  string oid;
  string locator;

  get_obj_bucket_and_oid_loc(obj, oid, locator);

  f->dump_string("oid", oid);
  f->dump_string("locator", locator);


  RGWObjectCtx obj_ctx(store);

  RGWRados::Object op_target(store->getRados(), bucket_info, obj_ctx, obj);
  RGWRados::Object::Read read_op(&op_target);

  int ret = read_op.prepare(null_yield, dpp());
  bool needs_fixing = (ret == -ENOENT);

  f->dump_bool("needs_fixing", needs_fixing);

  string status = (needs_fixing ? "needs_fixing" : "ok");

  if ((needs_fixing || remove_bad) && fix) {
    ret = store->getRados()->fix_head_obj_locator(dpp(), bucket_info, needs_fixing, remove_bad, key);
    if (ret < 0) {
      cerr << "ERROR: fix_head_object_locator() returned ret=" << ret << std::endl;
      goto done;
    }
    status = "fixed";
  }

done:
  f->dump_string("status", status);

  f->close_section();

  return 0;
}

int check_obj_tail_locator_underscore(RGWBucketInfo& bucket_info, rgw_obj& obj, rgw_obj_key& key, bool fix, Formatter *f) {
  f->open_object_section("object");
  f->open_object_section("key");
  f->dump_string("type", "tail");
  f->dump_string("name", key.name);
  f->dump_string("instance", key.instance);
  f->close_section();

  bool needs_fixing;
  string status;

  int ret = store->getRados()->fix_tail_obj_locator(dpp(), bucket_info, key, fix, &needs_fixing, null_yield);
  if (ret < 0) {
    cerr << "ERROR: fix_tail_object_locator_underscore() returned ret=" << ret << std::endl;
    status = "failed";
  } else {
    status = (needs_fixing && !fix ? "needs_fixing" : "ok");
  }

  f->dump_bool("needs_fixing", needs_fixing);
  f->dump_string("status", status);

  f->close_section();

  return 0;
}

int do_check_object_locator(const string& tenant_name, const string& bucket_name,
                            bool fix, bool remove_bad, Formatter *f)
{
  if (remove_bad && !fix) {
    cerr << "ERROR: can't have remove_bad specified without fix" << std::endl;
    return -EINVAL;
  }

  RGWBucketInfo bucket_info;
  rgw_bucket bucket;
  string bucket_id;

  f->open_object_section("bucket");
  f->dump_string("bucket", bucket_name);
  int ret = init_bucket(tenant_name, bucket_name, bucket_id, bucket_info, bucket);
  if (ret < 0) {
    cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  bool truncated;
  int count = 0;

  int max_entries = 1000;

  string prefix;
  string delim;
  vector<rgw_bucket_dir_entry> result;
  map<string, bool> common_prefixes;
  string ns;

  RGWRados::Bucket target(store->getRados(), bucket_info);
  RGWRados::Bucket::List list_op(&target);

  string marker;

  list_op.params.prefix = prefix;
  list_op.params.delim = delim;
  list_op.params.marker = rgw_obj_key(marker);
  list_op.params.ns = ns;
  list_op.params.enforce_ns = true;
  list_op.params.list_versions = true;

  f->open_array_section("check_objects");
  do {
    ret = list_op.list_objects(dpp(), max_entries - count, &result, &common_prefixes, &truncated, null_yield);
    if (ret < 0) {
      cerr << "ERROR: store->list_objects(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    count += result.size();

    for (vector<rgw_bucket_dir_entry>::iterator iter = result.begin(); iter != result.end(); ++iter) {
      rgw_obj_key key = iter->key;
      rgw_obj obj(bucket, key);

      if (key.name[0] == '_') {
        ret = check_obj_locator_underscore(bucket_info, obj, key, fix, remove_bad, f);

	if (ret >= 0) {
          ret = check_obj_tail_locator_underscore(bucket_info, obj, key, fix, f);
          if (ret < 0) {
              cerr << "ERROR: check_obj_tail_locator_underscore(): " << cpp_strerror(-ret) << std::endl;
              return -ret;
          }
	}
      }
    }
    f->flush(cout);
  } while (truncated && count < max_entries);
  f->close_section();
  f->close_section();

  f->flush(cout);

  return 0;
}

/// search for a matching zone/zonegroup id and return a connection if found
static boost::optional<RGWRESTConn> get_remote_conn(rgw::sal::RGWRadosStore *store,
                                                    const RGWZoneGroup& zonegroup,
                                                    const std::string& remote)
{
  boost::optional<RGWRESTConn> conn;
  if (remote == zonegroup.get_id()) {
    conn.emplace(store->ctx(), store->svc()->zone, remote, zonegroup.endpoints);
  } else {
    for (const auto& z : zonegroup.zones) {
      const auto& zone = z.second;
      if (remote == zone.id) {
        conn.emplace(store->ctx(), store->svc()->zone, remote, zone.endpoints);
        break;
      }
    }
  }
  return conn;
}

/// search each zonegroup for a connection
static boost::optional<RGWRESTConn> get_remote_conn(rgw::sal::RGWRadosStore *store,
                                                    const RGWPeriodMap& period_map,
                                                    const std::string& remote)
{
  boost::optional<RGWRESTConn> conn;
  for (const auto& zg : period_map.zonegroups) {
    conn = get_remote_conn(store, zg.second, remote);
    if (conn) {
      break;
    }
  }
  return conn;
}

// we expect a very small response
static constexpr size_t MAX_REST_RESPONSE = 128 * 1024;

static int send_to_remote_gateway(RGWRESTConn* conn, req_info& info,
                                  bufferlist& in_data, JSONParser& parser)
{
  if (!conn) {
    return -EINVAL;
  }

  ceph::bufferlist response;
  rgw_user user;
  int ret = conn->forward(dpp(), user, info, nullptr, MAX_REST_RESPONSE, &in_data, &response, null_yield);

  int parse_ret = parser.parse(response.c_str(), response.length());
  if (parse_ret < 0) {
    cerr << "failed to parse response" << std::endl;
    return parse_ret;
  }
  return ret;
}

static int send_to_url(const string& url, const string& access,
                       const string& secret, req_info& info,
                       bufferlist& in_data, JSONParser& parser)
{
  if (access.empty() || secret.empty()) {
    cerr << "An --access-key and --secret must be provided with --url." << std::endl;
    return -EINVAL;
  }
  RGWAccessKey key;
  key.id = access;
  key.key = secret;

  param_vec_t params;
  RGWRESTSimpleRequest req(g_ceph_context, info.method, url, NULL, &params);

  bufferlist response;
  int ret = req.forward_request(dpp(), key, info, MAX_REST_RESPONSE, &in_data, &response, null_yield);

  int parse_ret = parser.parse(response.c_str(), response.length());
  if (parse_ret < 0) {
    cout << "failed to parse response" << std::endl;
    return parse_ret;
  }
  return ret;
}

static int send_to_remote_or_url(RGWRESTConn *conn, const string& url,
                                 const string& access, const string& secret,
                                 req_info& info, bufferlist& in_data,
                                 JSONParser& parser)
{
  if (url.empty()) {
    return send_to_remote_gateway(conn, info, in_data, parser);
  }
  return send_to_url(url, access, secret, info, in_data, parser);
}

static int commit_period(RGWRealm& realm, RGWPeriod& period,
                         string remote, const string& url,
                         const string& access, const string& secret,
                         bool force)
{
  auto& master_zone = period.get_master_zone();
  if (master_zone.empty()) {
    cerr << "cannot commit period: period does not have a master zone of a master zonegroup" << std::endl;
    return -EINVAL;
  }
  // are we the period's master zone?
  if (store->svc()->zone->zone_id() == master_zone) {
    // read the current period
    RGWPeriod current_period;
    int ret = current_period.init(dpp(), g_ceph_context,
				  store->svc()->sysobj, realm.get_id(),
				  null_yield);
    if (ret < 0) {
      cerr << "Error initializing current period: "
          << cpp_strerror(-ret) << std::endl;
      return ret;
    }
    // the master zone can commit locally
    ret = period.commit(dpp(), store, realm, current_period, cerr, null_yield, force);
    if (ret < 0) {
      cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
    }
    return ret;
  }

  if (remote.empty() && url.empty()) {
    // use the new master zone's connection
    remote = master_zone.id;
    cerr << "Sending period to new master zone " << remote << std::endl;
  }
  boost::optional<RGWRESTConn> conn;
  RGWRESTConn *remote_conn = nullptr;
  if (!remote.empty()) {
    conn = get_remote_conn(store, period.get_map(), remote);
    if (!conn) {
      cerr << "failed to find a zone or zonegroup for remote "
          << remote << std::endl;
      return -ENOENT;
    }
    remote_conn = &*conn;
  }

  // push period to the master with an empty period id
  period.set_id(string());

  RGWEnv env;
  req_info info(g_ceph_context, &env);
  info.method = "POST";
  info.request_uri = "/admin/realm/period";

  // json format into a bufferlist
  JSONFormatter jf(false);
  encode_json("period", period, &jf);
  bufferlist bl;
  jf.flush(bl);

  JSONParser p;
  int ret = send_to_remote_or_url(remote_conn, url, access, secret, info, bl, p);
  if (ret < 0) {
    cerr << "request failed: " << cpp_strerror(-ret) << std::endl;

    // did we parse an error message?
    auto message = p.find_obj("Message");
    if (message) {
      cerr << "Reason: " << message->get_data() << std::endl;
    }
    return ret;
  }

  // decode the response and store it back
  try {
    decode_json_obj(period, &p);
  } catch (const JSONDecoder::err& e) {
    cout << "failed to decode JSON input: " << e.what() << std::endl;
    return -EINVAL;
  }
  if (period.get_id().empty()) {
    cerr << "Period commit got back an empty period id" << std::endl;
    return -EINVAL;
  }
  // the master zone gave us back the period that it committed, so it's
  // safe to save it as our latest epoch
  ret = period.store_info(dpp(), false, null_yield);
  if (ret < 0) {
    cerr << "Error storing committed period " << period.get_id() << ": "
        << cpp_strerror(ret) << std::endl;
    return ret;
  }
  ret = period.set_latest_epoch(dpp(), null_yield, period.get_epoch());
  if (ret < 0) {
    cerr << "Error updating period epoch: " << cpp_strerror(ret) << std::endl;
    return ret;
  }
  ret = period.reflect(dpp(), null_yield);
  if (ret < 0) {
    cerr << "Error updating local objects: " << cpp_strerror(ret) << std::endl;
    return ret;
  }
  realm.notify_new_period(dpp(), period, null_yield);
  return ret;
}

static int update_period(const string& realm_id, const string& realm_name,
                         const string& period_id, const string& period_epoch,
                         bool commit, const string& remote, const string& url,
                         const string& access, const string& secret,
                         Formatter *formatter, bool force)
{
  RGWRealm realm(realm_id, realm_name);
  int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
  if (ret < 0 ) {
    cerr << "Error initializing realm " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  epoch_t epoch = 0;
  if (!period_epoch.empty()) {
    epoch = atoi(period_epoch.c_str());
  }
  RGWPeriod period(period_id, epoch);
  ret = period.init(dpp(), g_ceph_context, store->svc()->sysobj, realm.get_id(), null_yield);
  if (ret < 0) {
    cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  period.fork();
  ret = period.update(dpp(), null_yield);
  if(ret < 0) {
    // Dropping the error message here, as both the ret codes were handled in
    // period.update()
    return ret;
  }
  ret = period.store_info(dpp(), false, null_yield);
  if (ret < 0) {
    cerr << "failed to store period: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  if (commit) {
    ret = commit_period(realm, period, remote, url, access, secret, force);
    if (ret < 0) {
      cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
      return ret;
    }
  }
  encode_json("period", period, formatter);
  formatter->flush(cout);
  return 0;
}

static int init_bucket_for_sync(const string& tenant, const string& bucket_name,
                                const string& bucket_id, rgw_bucket& bucket)
{
  RGWBucketInfo bucket_info;

  int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
  if (ret < 0) {
    cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }

  return 0;
}

static int do_period_pull(RGWRESTConn *remote_conn, const string& url,
                          const string& access_key, const string& secret_key,
                          const string& realm_id, const string& realm_name,
                          const string& period_id, const string& period_epoch,
                          RGWPeriod *period)
{
  RGWEnv env;
  req_info info(g_ceph_context, &env);
  info.method = "GET";
  info.request_uri = "/admin/realm/period";

  map<string, string> &params = info.args.get_params();
  if (!realm_id.empty())
    params["realm_id"] = realm_id;
  if (!realm_name.empty())
    params["realm_name"] = realm_name;
  if (!period_id.empty())
    params["period_id"] = period_id;
  if (!period_epoch.empty())
    params["epoch"] = period_epoch;

  bufferlist bl;
  JSONParser p;
  int ret = send_to_remote_or_url(remote_conn, url, access_key, secret_key,
                                  info, bl, p);
  if (ret < 0) {
    cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  ret = period->init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield, false);
  if (ret < 0) {
    cerr << "faile to init period " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  try {
    decode_json_obj(*period, &p);
  } catch (const JSONDecoder::err& e) {
    cout << "failed to decode JSON input: " << e.what() << std::endl;
    return -EINVAL;
  }
  ret = period->store_info(dpp(), false, null_yield);
  if (ret < 0) {
    cerr << "Error storing period " << period->get_id() << ": " << cpp_strerror(ret) << std::endl;
  }
  // store latest epoch (ignore errors)
  period->update_latest_epoch(dpp(), period->get_epoch(), null_yield);
  return 0;
}

static int read_current_period_id(rgw::sal::RGWRadosStore* store, const std::string& realm_id,
                                  const std::string& realm_name,
                                  std::string* period_id)
{
  RGWRealm realm(realm_id, realm_name);
  int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
  if (ret < 0) {
    std::cerr << "failed to read realm: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }
  *period_id = realm.get_current_period();
  return 0;
}

void flush_ss(stringstream& ss, list<string>& l)
{
  if (!ss.str().empty()) {
    l.push_back(ss.str());
  }
  ss.str("");
}

stringstream& push_ss(stringstream& ss, list<string>& l, int tab = 0)
{
  flush_ss(ss, l);
  if (tab > 0) {
    ss << setw(tab) << "" << setw(1);
  }
  return ss;
}

static void get_md_sync_status(list<string>& status)
{
  RGWMetaSyncStatusManager sync(store, store->svc()->rados->get_async_processor());

  int ret = sync.init(dpp());
  if (ret < 0) {
    status.push_back(string("failed to retrieve sync info: sync.init() failed: ") + cpp_strerror(-ret));
    return;
  }

  rgw_meta_sync_status sync_status;
  ret = sync.read_sync_status(dpp(), &sync_status);
  if (ret < 0) {
    status.push_back(string("failed to read sync status: ") + cpp_strerror(-ret));
    return;
  }

  string status_str;
  switch (sync_status.sync_info.state) {
    case rgw_meta_sync_info::StateInit:
      status_str = "init";
      break;
    case rgw_meta_sync_info::StateBuildingFullSyncMaps:
      status_str = "preparing for full sync";
      break;
    case rgw_meta_sync_info::StateSync:
      status_str = "syncing";
      break;
    default:
      status_str = "unknown";
  }

  status.push_back(status_str);

  uint64_t full_total = 0;
  uint64_t full_complete = 0;

  int num_full = 0;
  int num_inc = 0;
  int total_shards = 0;
  set<int> shards_behind_set;

  for (auto marker_iter : sync_status.sync_markers) {
    full_total += marker_iter.second.total_entries;
    total_shards++;
    if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
      num_full++;
      full_complete += marker_iter.second.pos;
      int shard_id = marker_iter.first;
      shards_behind_set.insert(shard_id);
    } else {
      full_complete += marker_iter.second.total_entries;
    }
    if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync) {
      num_inc++;
    }
  }

  stringstream ss;
  push_ss(ss, status) << "full sync: " << num_full << "/" << total_shards << " shards";

  if (num_full > 0) {
    push_ss(ss, status) << "full sync: " << full_total - full_complete << " entries to sync";
  }

  push_ss(ss, status) << "incremental sync: " << num_inc << "/" << total_shards << " shards";

  map<int, RGWMetadataLogInfo> master_shards_info;
  string master_period = store->svc()->zone->get_current_period_id();

  ret = sync.read_master_log_shards_info(dpp(), master_period, &master_shards_info);
  if (ret < 0) {
    status.push_back(string("failed to fetch master sync status: ") + cpp_strerror(-ret));
    return;
  }

  map<int, string> shards_behind;
  if (sync_status.sync_info.period != master_period) {
    status.push_back(string("master is on a different period: master_period=" +
                            master_period + " local_period=" + sync_status.sync_info.period));
  } else {
    for (auto local_iter : sync_status.sync_markers) {
      int shard_id = local_iter.first;
      auto iter = master_shards_info.find(shard_id);

      if (iter == master_shards_info.end()) {
        /* huh? */
        derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl;
        continue;
      }
      auto master_marker = iter->second.marker;
      if (local_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync &&
          master_marker > local_iter.second.marker) {
        shards_behind[shard_id] = local_iter.second.marker;
        shards_behind_set.insert(shard_id);
      }
    }
  }

  // fetch remote log entries to determine the oldest change
  std::optional<std::pair<int, ceph::real_time>> oldest;
  if (!shards_behind.empty()) {
    map<int, rgw_mdlog_shard_data> master_pos;
    ret = sync.read_master_log_shards_next(dpp(), sync_status.sync_info.period, shards_behind, &master_pos);
    if (ret < 0) {
      derr << "ERROR: failed to fetch master next positions (" << cpp_strerror(-ret) << ")" << dendl;
    } else {
      for (auto iter : master_pos) {
        rgw_mdlog_shard_data& shard_data = iter.second;

        if (shard_data.entries.empty()) {
          // there aren't any entries in this shard, so we're not really behind
          shards_behind.erase(iter.first);
          shards_behind_set.erase(iter.first);
        } else {
          rgw_mdlog_entry& entry = shard_data.entries.front();
          if (!oldest) {
            oldest.emplace(iter.first, entry.timestamp);
          } else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest->second) {
            oldest.emplace(iter.first, entry.timestamp);
          }
        }
      }
    }
  }

  int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc);
  if (total_behind == 0) {
    push_ss(ss, status) << "metadata is caught up with master";
  } else {
    push_ss(ss, status) << "metadata is behind on " << total_behind << " shards";
    push_ss(ss, status) << "behind shards: " << "[" << shards_behind_set << "]";
    if (oldest) {
      push_ss(ss, status) << "oldest incremental change not applied: "
          << oldest->second << " [" << oldest->first << ']';
    }
  }

  flush_ss(ss, status);
}

static void get_data_sync_status(const rgw_zone_id& source_zone, list<string>& status, int tab)
{
  stringstream ss;

  RGWZone *sz;

  if (!store->svc()->zone->find_zone(source_zone, &sz)) {
    push_ss(ss, status, tab) << string("zone not found");
    flush_ss(ss, status);
    return;
  }

  if (!store->svc()->zone->zone_syncs_from(store->svc()->zone->get_zone(), *sz)) {
    push_ss(ss, status, tab) << string("not syncing from zone");
    flush_ss(ss, status);
    return;
  }
  RGWDataSyncStatusManager sync(store, store->svc()->rados->get_async_processor(), source_zone, nullptr);

  int ret = sync.init(dpp());
  if (ret < 0) {
    push_ss(ss, status, tab) << string("failed to retrieve sync info: ") + cpp_strerror(-ret);
    flush_ss(ss, status);
    return;
  }

  rgw_data_sync_status sync_status;
  ret = sync.read_sync_status(dpp(), &sync_status);
  if (ret < 0 && ret != -ENOENT) {
    push_ss(ss, status, tab) << string("failed read sync status: ") + cpp_strerror(-ret);
    return;
  }

  set<int> recovering_shards;
  ret = sync.read_recovering_shards(dpp(), sync_status.sync_info.num_shards, recovering_shards);
  if (ret < 0 && ret != ENOENT) {
    push_ss(ss, status, tab) << string("failed read recovering shards: ") + cpp_strerror(-ret);
    return;
  }

  string status_str;
  switch (sync_status.sync_info.state) {
    case rgw_data_sync_info::StateInit:
      status_str = "init";
      break;
    case rgw_data_sync_info::StateBuildingFullSyncMaps:
      status_str = "preparing for full sync";
      break;
    case rgw_data_sync_info::StateSync:
      status_str = "syncing";
      break;
    default:
      status_str = "unknown";
  }

  push_ss(ss, status, tab) << status_str;

  uint64_t full_total = 0;
  uint64_t full_complete = 0;

  int num_full = 0;
  int num_inc = 0;
  int total_shards = 0;
  set<int> shards_behind_set;

  for (auto marker_iter : sync_status.sync_markers) {
    full_total += marker_iter.second.total_entries;
    total_shards++;
    if (marker_iter.second.state == rgw_data_sync_marker::SyncState::FullSync) {
      num_full++;
      full_complete += marker_iter.second.pos;
      int shard_id = marker_iter.first;
      shards_behind_set.insert(shard_id);
    } else {
      full_complete += marker_iter.second.total_entries;
    }
    if (marker_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync) {
      num_inc++;
    }
  }

  push_ss(ss, status, tab) << "full sync: " << num_full << "/" << total_shards << " shards";

  if (num_full > 0) {
    push_ss(ss, status, tab) << "full sync: " << full_total - full_complete << " buckets to sync";
  }

  push_ss(ss, status, tab) << "incremental sync: " << num_inc << "/" << total_shards << " shards";

  map<int, RGWDataChangesLogInfo> source_shards_info;

  ret = sync.read_source_log_shards_info(dpp(), &source_shards_info);
  if (ret < 0) {
    push_ss(ss, status, tab) << string("failed to fetch source sync status: ") + cpp_strerror(-ret);
    return;
  }

  map<int, string> shards_behind;

  for (auto local_iter : sync_status.sync_markers) {
    int shard_id = local_iter.first;
    auto iter = source_shards_info.find(shard_id);

    if (iter == source_shards_info.end()) {
      /* huh? */
      derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl;
      continue;
    }
    auto master_marker = iter->second.marker;
    if (local_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync &&
        master_marker > local_iter.second.marker) {
      shards_behind[shard_id] = local_iter.second.marker;
      shards_behind_set.insert(shard_id);
    }
  }

  int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc);
  int total_recovering = recovering_shards.size();
  if (total_behind == 0 && total_recovering == 0) {
    push_ss(ss, status, tab) << "data is caught up with source";
  } else if (total_behind > 0) {
    push_ss(ss, status, tab) << "data is behind on " << total_behind << " shards";

    push_ss(ss, status, tab) << "behind shards: " << "[" << shards_behind_set << "]" ;

    map<int, rgw_datalog_shard_data> master_pos;
    ret = sync.read_source_log_shards_next(dpp(), shards_behind, &master_pos);
    if (ret < 0) {
      derr << "ERROR: failed to fetch next positions (" << cpp_strerror(-ret) << ")" << dendl;
    } else {
      std::optional<std::pair<int, ceph::real_time>> oldest;

      for (auto iter : master_pos) {
        rgw_datalog_shard_data& shard_data = iter.second;

        if (!shard_data.entries.empty()) {
          rgw_datalog_entry& entry = shard_data.entries.front();
          if (!oldest) {
            oldest.emplace(iter.first, entry.timestamp);
          } else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest->second) {
            oldest.emplace(iter.first, entry.timestamp);
          }
        }
      }

      if (oldest) {
        push_ss(ss, status, tab) << "oldest incremental change not applied: "
            << oldest->second << " [" << oldest->first << ']';
      }
    }
  }

  if (total_recovering > 0) {
    push_ss(ss, status, tab) << total_recovering << " shards are recovering";
    push_ss(ss, status, tab) << "recovering shards: " << "[" << recovering_shards << "]";
  }

  flush_ss(ss, status);
}

static void tab_dump(const string& header, int width, const list<string>& entries)
{
  string s = header;

  for (auto e : entries) {
    cout << std::setw(width) << s << std::setw(1) << " " << e << std::endl;
    s.clear();
  }
}


static void sync_status(Formatter *formatter)
{
  const RGWRealm& realm = store->svc()->zone->get_realm();
  const RGWZoneGroup& zonegroup = store->svc()->zone->get_zonegroup();
  const RGWZone& zone = store->svc()->zone->get_zone();

  int width = 15;

  cout << std::setw(width) << "realm" << std::setw(1) << " " << realm.get_id() << " (" << realm.get_name() << ")" << std::endl;
  cout << std::setw(width) << "zonegroup" << std::setw(1) << " " << zonegroup.get_id() << " (" << zonegroup.get_name() << ")" << std::endl;
  cout << std::setw(width) << "zone" << std::setw(1) << " " << zone.id << " (" << zone.name << ")" << std::endl;

  list<string> md_status;

  if (store->svc()->zone->is_meta_master()) {
    md_status.push_back("no sync (zone is master)");
  } else {
    get_md_sync_status(md_status);
  }

  tab_dump("metadata sync", width, md_status);

  list<string> data_status;

  auto& zone_conn_map = store->svc()->zone->get_zone_conn_map();

  for (auto iter : zone_conn_map) {
    const rgw_zone_id& source_id = iter.first;
    string source_str = "source: ";
    string s = source_str + source_id.id;
    RGWZone *sz;
    if (store->svc()->zone->find_zone(source_id, &sz)) {
      s += string(" (") + sz->name + ")";
    }
    data_status.push_back(s);
    get_data_sync_status(source_id, data_status, source_str.size());
  }

  tab_dump("data sync", width, data_status);
}

struct indented {
  int w; // indent width
  std::string_view header;
  indented(int w, std::string_view header = "") : w(w), header(header) {}
};
std::ostream& operator<<(std::ostream& out, const indented& h) {
  return out << std::setw(h.w) << h.header << std::setw(1) << ' ';
}

static int bucket_source_sync_status(const DoutPrefixProvider *dpp, rgw::sal::RGWRadosStore *store, const RGWZone& zone,
                                     const RGWZone& source, RGWRESTConn *conn,
                                     const RGWBucketInfo& bucket_info,
                                     rgw_sync_bucket_pipe pipe,
                                     int width, std::ostream& out)
{
  out << indented{width, "source zone"} << source.id << " (" << source.name << ")" << std::endl;

  // syncing from this zone?
  if (!zone.syncs_from(source.name)) {
    out << indented{width} << "does not sync from zone\n";
    return 0;
  }

  if (!pipe.source.bucket) {
    ldpp_dout(dpp, -1) << __func__ << "(): missing source bucket" << dendl;
    return -EINVAL;
  }

  RGWBucketInfo source_bucket_info;
  rgw_bucket source_bucket;
  int r = init_bucket(*pipe.source.bucket, source_bucket_info, source_bucket);
  if (r < 0) {
    ldpp_dout(dpp, -1) << "failed to read source bucket info: " << cpp_strerror(r) << dendl;
    return r;
  }

  pipe.source.bucket = source_bucket;
  pipe.dest.bucket = bucket_info.bucket;

  std::vector<rgw_bucket_shard_sync_info> status;
  r = rgw_bucket_sync_status(dpp, store, pipe, bucket_info, &source_bucket_info, &status);
  if (r < 0) {
    ldpp_dout(dpp, -1) << "failed to read bucket sync status: " << cpp_strerror(r) << dendl;
    return r;
  }

  out << indented{width, "source bucket"} << source_bucket_info.bucket.get_key() << std::endl;

  int num_full = 0;
  int num_inc = 0;
  uint64_t full_complete = 0;
  const size_t total_shards = status.size();

  using BucketSyncState = rgw_bucket_shard_sync_info::SyncState;
  for (size_t shard_id = 0; shard_id < total_shards; shard_id++) {
    auto& m = status[shard_id];
    if (m.state == BucketSyncState::StateFullSync) {
      num_full++;
      full_complete += m.full_marker.count;
    } else if (m.state == BucketSyncState::StateIncrementalSync) {
      num_inc++;
    }
  }

  out << indented{width} << "full sync: " << num_full << "/" << total_shards << " shards\n";
  if (num_full > 0) {
    out << indented{width} << "full sync: " << full_complete << " objects completed\n";
  }
  out << indented{width} << "incremental sync: " << num_inc << "/" << total_shards << " shards\n";

  BucketIndexShardsManager remote_markers;
  r = rgw_read_remote_bilog_info(dpp, conn, source_bucket, remote_markers, null_yield);
  if (r < 0) {
    ldpp_dout(dpp, -1) << "failed to read remote log: " << cpp_strerror(r) << dendl;
    return r;
  }

  std::set<int> shards_behind;
  for (auto& r : remote_markers.get()) {
    auto shard_id = r.first;
    auto& m = status[shard_id];
    if (r.second.empty()) {
      continue; // empty bucket index shard
    }
    auto pos = BucketIndexShardsManager::get_shard_marker(m.inc_marker.position);
    if (m.state != BucketSyncState::StateIncrementalSync || pos != r.second) {
      shards_behind.insert(shard_id);
    }
  }
  if (!shards_behind.empty()) {
    out << indented{width} << "bucket is behind on " << shards_behind.size() << " shards\n";
    out << indented{width} << "behind shards: [" << shards_behind << "]\n" ;
  } else if (!num_full) {
    out << indented{width} << "bucket is caught up with source\n";
  }
  return 0;
}

void encode_json(const char *name, const RGWBucketSyncFlowManager::pipe_set& pset, Formatter *f)
{
  Formatter::ObjectSection top_section(*f, name);
  Formatter::ArraySection as(*f, "entries");

  for (auto& pipe_handler : pset) {
    Formatter::ObjectSection hs(*f, "handler");
    encode_json("source", pipe_handler.source, f);
    encode_json("dest", pipe_handler.dest, f);
  }
}

static std::vector<string> convert_bucket_set_to_str_vec(const std::set<rgw_bucket>& bs)
{
  std::vector<string> result;
  result.reserve(bs.size());
  for (auto& b : bs) {
    result.push_back(b.get_key());
  }
  return result;
}

static void get_hint_entities(const std::set<rgw_zone_id>& zones, const std::set<rgw_bucket>& buckets,
			      std::set<rgw_sync_bucket_entity> *hint_entities)
{
  for (auto& zone_id : zones) {
    for (auto& b : buckets) {
      RGWBucketInfo hint_bucket_info;
      rgw_bucket hint_bucket;
      int ret = init_bucket(b, hint_bucket_info, hint_bucket);
      if (ret < 0) {
	ldpp_dout(dpp(), 20) << "could not init bucket info for hint bucket=" << b << " ... skipping" << dendl;
	continue;
      }

      hint_entities->insert(rgw_sync_bucket_entity(zone_id, hint_bucket));
    }
  }
}

static rgw_zone_id resolve_zone_id(const string& s)
{
  rgw_zone_id result;

  RGWZone *zone;
  if (store->svc()->zone->find_zone(s, &zone)) {
    return rgw_zone_id(s);
  }
  if (store->svc()->zone->find_zone_id_by_name(s, &result)) {
    return result;
  }
  return rgw_zone_id(s);
}

rgw_zone_id validate_zone_id(const rgw_zone_id& zone_id)
{
  return resolve_zone_id(zone_id.id);
}

static int sync_info(std::optional<rgw_zone_id> opt_target_zone, std::optional<rgw_bucket> opt_bucket, Formatter *formatter)
{
  rgw_zone_id zone_id = opt_target_zone.value_or(store->svc()->zone->zone_id());

  auto zone_policy_handler = store->svc()->zone->get_sync_policy_handler(zone_id);

  RGWBucketSyncPolicyHandlerRef bucket_handler;

  std::optional<rgw_bucket> eff_bucket = opt_bucket;

  auto handler = zone_policy_handler;

  if (eff_bucket) {
    rgw_bucket bucket;
    RGWBucketInfo bucket_info;
    map<string, bufferlist> bucket_attrs;

    int ret = init_bucket(*eff_bucket, bucket_info, bucket, &bucket_attrs);
    if (ret < 0 && ret != -ENOENT) {
      cerr << "ERROR: init_bucket failed: " << cpp_strerror(-ret) << std::endl;
      return ret;
    }

    if (ret >= 0) {
      bucket_handler.reset(handler->alloc_child(bucket_info, std::move(bucket_attrs)));
    } else {
      cerr << "WARNING: bucket not found, simulating result" << std::endl;
      bucket_handler.reset(handler->alloc_child(*eff_bucket, nullopt));
    }

    ret = bucket_handler->init(dpp(), null_yield);
    if (ret < 0) {
      cerr << "ERROR: failed to init bucket sync policy handler: " << cpp_strerror(-ret) << " (ret=" << ret << ")" << std::endl;
      return ret;
    }

    handler = bucket_handler;
  }

  std::set<rgw_sync_bucket_pipe> sources;
  std::set<rgw_sync_bucket_pipe> dests;

  handler->get_pipes(&sources, &dests, std::nullopt);

  auto source_hints_vec = convert_bucket_set_to_str_vec(handler->get_source_hints());
  auto target_hints_vec = convert_bucket_set_to_str_vec(handler->get_target_hints());

  std::set<rgw_sync_bucket_pipe> resolved_sources;
  std::set<rgw_sync_bucket_pipe> resolved_dests;

  rgw_sync_bucket_entity self_entity(zone_id, opt_bucket);

  set<rgw_zone_id> source_zones;
  set<rgw_zone_id> target_zones;

  zone_policy_handler->reflect(nullptr, nullptr,
                               nullptr, nullptr,
                               &source_zones,
                               &target_zones,
                               false); /* relaxed: also get all zones that we allow to sync to/from */

  std::set<rgw_sync_bucket_entity> hint_entities;

  get_hint_entities(source_zones, handler->get_source_hints(), &hint_entities);
  get_hint_entities(target_zones, handler->get_target_hints(), &hint_entities);

  for (auto& hint_entity : hint_entities) {
    if (!hint_entity.zone ||
	!hint_entity.bucket) {
      continue; /* shouldn't really happen */
    }

    auto zid = validate_zone_id(*hint_entity.zone);
    auto& hint_bucket = *hint_entity.bucket;

    RGWBucketSyncPolicyHandlerRef hint_bucket_handler;
    int r = store->ctl()->bucket->get_sync_policy_handler(zid, hint_bucket, &hint_bucket_handler, null_yield, dpp());
    if (r < 0) {
      ldpp_dout(dpp(), 20) << "could not get bucket sync policy handler for hint bucket=" << hint_bucket << " ... skipping" << dendl;
      continue;
    }

    hint_bucket_handler->get_pipes(&resolved_dests,
                                   &resolved_sources,
                                   self_entity); /* flipping resolved dests and sources as these are
                                                    relative to the remote entity */
  }

  {
    Formatter::ObjectSection os(*formatter, "result");
    encode_json("sources", sources, formatter);
    encode_json("dests", dests, formatter);
    {
      Formatter::ObjectSection hints_section(*formatter, "hints");
      encode_json("sources", source_hints_vec, formatter);
      encode_json("dests", target_hints_vec, formatter);
    }
    {
      Formatter::ObjectSection resolved_hints_section(*formatter, "resolved-hints-1");
      encode_json("sources", resolved_sources, formatter);
      encode_json("dests", resolved_dests, formatter);
    }
    {
      Formatter::ObjectSection resolved_hints_section(*formatter, "resolved-hints");
      encode_json("sources", handler->get_resolved_source_hints(), formatter);
      encode_json("dests", handler->get_resolved_dest_hints(), formatter);
    }
  }

  formatter->flush(cout);

  return 0;
}

static int bucket_sync_info(rgw::sal::RGWRadosStore *store, const RGWBucketInfo& info,
                              std::ostream& out)
{
  const RGWRealm& realm = store->svc()->zone->get_realm();
  const RGWZoneGroup& zonegroup = store->svc()->zone->get_zonegroup();
  const RGWZone& zone = store->svc()->zone->get_zone();
  constexpr int width = 15;

  out << indented{width, "realm"} << realm.get_id() << " (" << realm.get_name() << ")\n";
  out << indented{width, "zonegroup"} << zonegroup.get_id() << " (" << zonegroup.get_name() << ")\n";
  out << indented{width, "zone"} << zone.id << " (" << zone.name << ")\n";
  out << indented{width, "bucket"} << info.bucket << "\n\n";

  if (!store->ctl()->bucket->bucket_imports_data(info.bucket, null_yield, dpp())) {
    out << "Sync is disabled for bucket " << info.bucket.name << '\n';
    return 0;
  }

  RGWBucketSyncPolicyHandlerRef handler;

  int r = store->ctl()->bucket->get_sync_policy_handler(std::nullopt, info.bucket, &handler, null_yield, dpp());
  if (r < 0) {
    ldpp_dout(dpp(), -1) << "ERROR: failed to get policy handler for bucket (" << info.bucket << "): r=" << r << ": " << cpp_strerror(-r) << dendl;
    return r;
  }

  auto& sources = handler->get_sources();

  for (auto& m : sources) {
    auto& zone = m.first;
    out << indented{width, "source zone"} << zone << std::endl;
    for (auto& pipe_handler : m.second) {
      out << indented{width, "bucket"} << *pipe_handler.source.bucket << std::endl;
    }
  }

  return 0;
}

static int bucket_sync_status(rgw::sal::RGWRadosStore *store, const RGWBucketInfo& info,
                              const rgw_zone_id& source_zone_id,
			      std::optional<rgw_bucket>& opt_source_bucket,
                              std::ostream& out)
{
  const RGWRealm& realm = store->svc()->zone->get_realm();
  const RGWZoneGroup& zonegroup = store->svc()->zone->get_zonegroup();
  const RGWZone& zone = store->svc()->zone->get_zone();
  constexpr int width = 15;

  out << indented{width, "realm"} << realm.get_id() << " (" << realm.get_name() << ")\n";
  out << indented{width, "zonegroup"} << zonegroup.get_id() << " (" << zonegroup.get_name() << ")\n";
  out << indented{width, "zone"} << zone.id << " (" << zone.name << ")\n";
  out << indented{width, "bucket"} << info.bucket << "\n\n";

  if (!store->ctl()->bucket->bucket_imports_data(info.bucket, null_yield, dpp())) {
    out << "Sync is disabled for bucket " << info.bucket.name << " or bucket has no sync sources" << std::endl;
    return 0;
  }

  RGWBucketSyncPolicyHandlerRef handler;

  int r = store->ctl()->bucket->get_sync_policy_handler(std::nullopt, info.bucket, &handler, null_yield, dpp());
  if (r < 0) {
    ldpp_dout(dpp(), -1) << "ERROR: failed to get policy handler for bucket (" << info.bucket << "): r=" << r << ": " << cpp_strerror(-r) << dendl;
    return r;
  }

  auto sources = handler->get_all_sources();

  auto& zone_conn_map = store->svc()->zone->get_zone_conn_map();
  set<rgw_zone_id> zone_ids;

  if (!source_zone_id.empty()) {
    auto z = zonegroup.zones.find(source_zone_id);
    if (z == zonegroup.zones.end()) {
      ldpp_dout(dpp(), -1) << "Source zone not found in zonegroup "
          << zonegroup.get_name() << dendl;
      return -EINVAL;
    }
    auto c = zone_conn_map.find(source_zone_id);
    if (c == zone_conn_map.end()) {
      ldpp_dout(dpp(), -1) << "No connection to zone " << z->second.name << dendl;
      return -EINVAL;
    }
    zone_ids.insert(source_zone_id);
  } else {
    for (const auto& entry : zonegroup.zones) {
      zone_ids.insert(entry.second.id);
    }
  }

  for (auto& zone_id : zone_ids) {
    auto z = zonegroup.zones.find(zone_id.id);
    if (z == zonegroup.zones.end()) { /* should't happen */
      continue;
    }
    auto c = zone_conn_map.find(zone_id.id);
    if (c == zone_conn_map.end()) { /* should't happen */
      continue;
    }

    for (auto& entry : sources) {
      auto& pipe = entry.second;
      if (opt_source_bucket &&
	  pipe.source.bucket != opt_source_bucket) {
	continue;
      }
      if (pipe.source.zone.value_or(rgw_zone_id()) == z->second.id) {
	bucket_source_sync_status(dpp(), store, zone, z->second,
				  c->second,
				  info, pipe,
				  width, out);
      }
    }
  }

  return 0;
}

static void parse_tier_config_param(const string& s, map<string, string, ltstr_nocase>& out)
{
  int level = 0;
  string cur_conf;
  list<string> confs;
  for (auto c : s) {
    if (c == ',') {
      if (level == 0) {
        confs.push_back(cur_conf);
        cur_conf.clear();
        continue;
      }
    }
    if (c == '{') {
      ++level;
    } else if (c == '}') {
      --level;
    }
    cur_conf += c;
  }
  if (!cur_conf.empty()) {
    confs.push_back(cur_conf);
  }

  for (auto c : confs) {
    ssize_t pos = c.find("=");
    if (pos < 0) {
      out[c] = "";
    } else {
      out[c.substr(0, pos)] = c.substr(pos + 1);
    }
  }
}

static int check_pool_support_omap(const rgw_pool& pool)
{
  librados::IoCtx io_ctx;
  int ret = store->getRados()->get_rados_handle()->ioctx_create(pool.to_str().c_str(), io_ctx);
  if (ret < 0) {
     // the pool may not exist at this moment, we have no way to check if it supports omap.
     return 0;
  }

  ret = io_ctx.omap_clear("__omap_test_not_exist_oid__");
  if (ret == -EOPNOTSUPP) {
    io_ctx.close();
    return ret;
  }
  io_ctx.close();
  return 0;
}

int check_reshard_bucket_params(rgw::sal::RGWRadosStore *store,
				const string& bucket_name,
				const string& tenant,
				const string& bucket_id,
				bool num_shards_specified,
				int num_shards,
				int yes_i_really_mean_it,
				rgw_bucket& bucket,
				RGWBucketInfo& bucket_info,
				map<string, bufferlist>& attrs)
{
  if (bucket_name.empty()) {
    cerr << "ERROR: bucket not specified" << std::endl;
    return -EINVAL;
  }

  if (!num_shards_specified) {
    cerr << "ERROR: --num-shards not specified" << std::endl;
    return -EINVAL;
  }

  if (num_shards > (int)store->getRados()->get_max_bucket_shards()) {
    cerr << "ERROR: num_shards too high, max value: " << store->getRados()->get_max_bucket_shards() << std::endl;
    return -EINVAL;
  }

  if (num_shards < 0) {
    cerr << "ERROR: num_shards must be non-negative integer" << std::endl;
    return -EINVAL;
  }

  int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket, &attrs);
  if (ret < 0) {
    cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
    return ret;
  }

  if (bucket_info.reshard_status != cls_rgw_reshard_status::NOT_RESHARDING) {
    // if in_progress or done then we have an old BucketInfo
    cerr << "ERROR: the bucket is currently undergoing resharding and "
      "cannot be added to the reshard list at this time" << std::endl;
    return -EBUSY;
  }

  int num_source_shards = (bucket_info.layout.current_index.layout.normal.num_shards > 0 ? bucket_info.layout.current_index.layout.normal.num_shards : 1);

  if (num_shards <= num_source_shards && !yes_i_really_mean_it) {
    cerr << "num shards is less or equal to current shards count" << std::endl
	 << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
    return -EINVAL;
  }
  return 0;
}

static int scan_totp(CephContext *cct, ceph::real_time& now, rados::cls::otp::otp_info_t& totp, vector<string>& pins,
                     time_t *pofs)
{
#define MAX_TOTP_SKEW_HOURS (24 * 7)
  time_t start_time = ceph::real_clock::to_time_t(now);
  time_t time_ofs = 0, time_ofs_abs = 0;
  time_t step_size = totp.step_size;
  if (step_size == 0) {
    step_size = OATH_TOTP_DEFAULT_TIME_STEP_SIZE;
  }
  uint32_t count = 0;
  int sign = 1;

  uint32_t max_skew = MAX_TOTP_SKEW_HOURS * 3600;

  while (time_ofs_abs < max_skew) {
    int rc = oath_totp_validate2(totp.seed_bin.c_str(), totp.seed_bin.length(),
                             start_time, 
                             step_size,
                             time_ofs,
                             1,
                             nullptr,
                             pins[0].c_str());
    if (rc != OATH_INVALID_OTP) {
      rc = oath_totp_validate2(totp.seed_bin.c_str(), totp.seed_bin.length(),
                               start_time, 
                               step_size,
                               time_ofs - step_size, /* smaller time_ofs moves time forward */
                               1,
                               nullptr,
                               pins[1].c_str());
      if (rc != OATH_INVALID_OTP) {
        *pofs = time_ofs - step_size + step_size * totp.window / 2;
        ldpp_dout(dpp(), 20) << "found at time=" << start_time - time_ofs << " time_ofs=" << time_ofs << dendl;
        return 0;
      }
    }
    sign = -sign;
    time_ofs_abs = (++count) * step_size;
    time_ofs = sign * time_ofs_abs;
  }

  return -ENOENT;
}

static int trim_sync_error_log(int shard_id, const string& marker, int delay_ms)
{
  auto oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX,
                                               shard_id);
  // call cls_log_trim() until it returns -ENODATA
  for (;;) {
    int ret = store->svc()->cls->timelog.trim(dpp(), oid, {}, {}, {}, marker, nullptr,
					      null_yield);
    if (ret == -ENODATA) {
      return 0;
    }
    if (ret < 0) {
      return ret;
    }
    if (delay_ms) {
      std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
    }
  }
  // unreachable
}

const string& get_tier_type(rgw::sal::RGWRadosStore *store) {
  return store->svc()->zone->get_zone().tier_type;
}

static bool symmetrical_flow_opt(const string& opt)
{
  return (opt == "symmetrical" || opt == "symmetric");
}

static bool directional_flow_opt(const string& opt)
{
  return (opt == "directional" || opt == "direction");
}

template <class T>
static bool require_opt(std::optional<T> opt, bool extra_check = true)
{
  if (!opt || !extra_check) {
    return false;
  }
  return true;
}

template <class T>
static bool require_non_empty_opt(std::optional<T> opt, bool extra_check = true)
{
  if (!opt || opt->empty() || !extra_check) {
    return false;
  }
  return true;
}

template <class T>
static void show_result(T& obj,
                        Formatter *formatter,
                        ostream& os)
{
  encode_json("obj", obj, formatter);

  formatter->flush(cout);
}

void init_optional_bucket(std::optional<rgw_bucket>& opt_bucket,
                          std::optional<string>& opt_tenant,
                          std::optional<string>& opt_bucket_name,
                          std::optional<string>& opt_bucket_id)
{
  if (opt_tenant || opt_bucket_name || opt_bucket_id) {
    opt_bucket.emplace();
    if (opt_tenant) {
      opt_bucket->tenant = *opt_tenant;
    }
    if (opt_bucket_name) {
      opt_bucket->name = *opt_bucket_name;
    }
    if (opt_bucket_id) {
      opt_bucket->bucket_id = *opt_bucket_id;
    }
  }
}

class SyncPolicyContext
{
  RGWZoneGroup zonegroup;

  std::optional<rgw_bucket> bucket;
  RGWBucketInfo bucket_info;
  map<string, bufferlist> bucket_attrs;

  rgw_sync_policy_info *policy{nullptr};

  std::optional<rgw_user> owner;

public:
  SyncPolicyContext(const string& zonegroup_id,
                    const string& zonegroup_name,
                    std::optional<rgw_bucket> _bucket) : zonegroup(zonegroup_id, zonegroup_name),
                                                         bucket(_bucket) {}

  int init() {
    int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
    if (ret < 0) {
      cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
      return ret;
    }

    if (!bucket) {
      policy = &zonegroup.sync_policy;
      return 0;
    }

    ret = init_bucket(*bucket, bucket_info, *bucket, &bucket_attrs);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return ret;
    }

    owner = bucket_info.owner;

    if (!bucket_info.sync_policy) {
      rgw_sync_policy_info new_policy;
      bucket_info.set_sync_policy(std::move(new_policy));
    }

    policy = &(*bucket_info.sync_policy);

    return 0;
  }

  int write_policy() {
    if (!bucket) {
      int ret = zonegroup.update(dpp(), null_yield);
      if (ret < 0) {
        cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      return 0;
    }

    int ret = store->getRados()->put_bucket_instance_info(bucket_info, false, real_time(), &bucket_attrs, dpp());
    if (ret < 0) {
      cerr << "failed to store bucket info: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    return 0;
  }

  rgw_sync_policy_info& get_policy() {
    return *policy;
  }

  std::optional<rgw_user>& get_owner() {
    return owner;
  }
};

void resolve_zone_id_opt(std::optional<string>& zone_name, std::optional<rgw_zone_id>& zone_id)
{
  if (!zone_name || zone_id) {
    return;
  }
  zone_id.emplace();
  if (!store->svc()->zone->find_zone_id_by_name(*zone_name, &(*zone_id))) {
    cerr << "WARNING: cannot find source zone id for name=" << *zone_name << std::endl;
    zone_id = rgw_zone_id(*zone_name);
  }
}
void resolve_zone_ids_opt(std::optional<vector<string> >& names, std::optional<vector<rgw_zone_id> >& ids)
{
  if (!names || ids) {
    return;
  }
  ids.emplace();
  for (auto& name : *names) {
    rgw_zone_id zid;
    if (!store->svc()->zone->find_zone_id_by_name(name, &zid)) {
      cerr << "WARNING: cannot find source zone id for name=" << name << std::endl;
      zid = rgw_zone_id(name);
    }
    ids->push_back(zid);
  }
}

static vector<rgw_zone_id> zone_ids_from_str(const string& val)
{
  vector<rgw_zone_id> result;
  vector<string> v;
  get_str_vec(val, v);
  for (auto& z : v) {
    result.push_back(rgw_zone_id(z));
  }
  return result;
}

class JSONFormatter_PrettyZone : public JSONFormatter {
  class Handler : public JSONEncodeFilter::Handler<rgw_zone_id> {
    void encode_json(const char *name, const void *pval, ceph::Formatter *f) const override {
      auto zone_id = *(static_cast<const rgw_zone_id *>(pval));
      string zone_name;
      RGWZone *zone;
      if (store->svc()->zone->find_zone(zone_id, &zone)) {
        zone_name = zone->name;
      } else {
        cerr << "WARNING: cannot find zone name for id=" << zone_id << std::endl;
        zone_name = zone_id.id;
      }

      ::encode_json(name, zone_name, f);
    }
  } zone_id_type_handler;

  JSONEncodeFilter encode_filter;
public:
  JSONFormatter_PrettyZone(bool pretty_format) : JSONFormatter(pretty_format) {
    encode_filter.register_type(&zone_id_type_handler);
  }

  void *get_external_feature_handler(const std::string& feature) override {
    if (feature != "JSONEncodeFilter") {
      return nullptr;
    }
    return &encode_filter;
  }
};

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, (const char **)argv, args);
  if (args.empty()) {
    cerr << argv[0] << ": -h or --help for usage" << std::endl;
    exit(1);
  }
  if (ceph_argparse_need_usage(args)) {
    usage();
    exit(0);
  }

  auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
                         CODE_ENVIRONMENT_UTILITY, 0);

  // for region -> zonegroup conversion (must happen before common_init_finish())
  if (!g_conf()->rgw_region.empty() && g_conf()->rgw_zonegroup.empty()) {
    g_conf().set_val_or_die("rgw_zonegroup", g_conf()->rgw_region.c_str());
  }

  common_init_finish(g_ceph_context);

  rgw_user user_id;
  string tenant;
  string user_ns;
  rgw_user new_user_id;
  std::string access_key, secret_key, user_email, display_name;
  std::string bucket_name, pool_name, object;
  rgw_pool pool;
  std::string date, subuser, access, format;
  std::string start_date, end_date;
  std::string key_type_str;
  std::string period_id, period_epoch, remote, url;
  std::string master_zone;
  std::string realm_name, realm_id, realm_new_name;
  std::string zone_name, zone_id, zone_new_name;
  std::string zonegroup_name, zonegroup_id, zonegroup_new_name;
  std::string api_name;
  std::string role_name, path, assume_role_doc, policy_name, perm_policy_doc, path_prefix;
  std::string redirect_zone;
  bool redirect_zone_set = false;
  list<string> endpoints;
  int tmp_int;
  int sync_from_all_specified = false;
  bool sync_from_all = false;
  list<string> sync_from;
  list<string> sync_from_rm;
  int is_master_int;
  int set_default = 0;
  bool is_master = false;
  bool is_master_set = false;
  int read_only_int;
  bool read_only = false;
  int is_read_only_set = false;
  int commit = false;
  int staging = false;
  int key_type = KEY_TYPE_UNDEFINED;
  rgw_bucket bucket;
  uint32_t perm_mask = 0;
  RGWUserInfo info;
  OPT opt_cmd = OPT::NO_CMD;
  int gen_access_key = 0;
  int gen_secret_key = 0;
  bool set_perm = false;
  bool set_temp_url_key = false;
  map<int, string> temp_url_keys;
  string bucket_id;
  string new_bucket_name;
  std::unique_ptr<Formatter> formatter;
  std::unique_ptr<Formatter> zone_formatter;
  int purge_data = false;
  int pretty_format = false;
  int show_log_entries = true;
  int show_log_sum = true;
  int skip_zero_entries = false;  // log show
  int purge_keys = false;
  int yes_i_really_mean_it = false;
  int delete_child_objects = false;
  int fix = false;
  int remove_bad = false;
  int check_head_obj_locator = false;
  int max_buckets = -1;
  bool max_buckets_specified = false;
  map<string, bool> categories;
  string caps;
  int check_objects = false;
  RGWUserAdminOpState user_op;
  RGWBucketAdminOpState bucket_op;
  string infile;
  string metadata_key;
  RGWObjVersionTracker objv_tracker;
  string marker;
  string start_marker;
  string end_marker;
  int max_entries = -1;
  bool max_entries_specified = false;
  int admin = false;
  bool admin_specified = false;
  int system = false;
  bool system_specified = false;
  int shard_id = -1;
  bool specified_shard_id = false;
  string client_id;
  string op_id;
  string op_mask_str;
  string quota_scope;
  string object_version;
  string placement_id;
  std::optional<string> opt_storage_class;
  list<string> tags;
  list<string> tags_add;
  list<string> tags_rm;

  int64_t max_objects = -1;
  int64_t max_size = -1;
  bool have_max_objects = false;
  bool have_max_size = false;
  int include_all = false;
  int allow_unordered = false;

  int sync_stats = false;
  int reset_stats = false;
  int bypass_gc = false;
  int warnings_only = false;
  int inconsistent_index = false;

  int verbose = false;

  int extra_info = false;

  uint64_t min_rewrite_size = 4 * 1024 * 1024;
  uint64_t max_rewrite_size = ULLONG_MAX;
  uint64_t min_rewrite_stripe_size = 0;

  BIIndexType bi_index_type = BIIndexType::Plain;
  std::optional<log_type> opt_log_type;

  string job_id;
  int num_shards = 0;
  bool num_shards_specified = false;
  std::optional<int> bucket_index_max_shards;
  int max_concurrent_ios = 32;
  uint64_t orphan_stale_secs = (24 * 3600);
  int detail = false;

  std::string val;
  std::ostringstream errs;
  string err;

  string source_zone_name;
  rgw_zone_id source_zone; /* zone id */

  string tier_type;
  bool tier_type_specified = false;

  map<string, string, ltstr_nocase> tier_config_add;
  map<string, string, ltstr_nocase> tier_config_rm;

  boost::optional<string> index_pool;
  boost::optional<string> data_pool;
  boost::optional<string> data_extra_pool;
  rgw::BucketIndexType placement_index_type = rgw::BucketIndexType::Normal;
  bool index_type_specified = false;

  boost::optional<std::string> compression_type;

  string totp_serial;
  string totp_seed;
  string totp_seed_type = "hex";
  vector<string> totp_pin;
  int totp_seconds = 0;
  int totp_window = 0;
  int trim_delay_ms = 0;

  string topic_name;
  string sub_name;
  string event_id;

  std::optional<std::string> str_script_ctx;
  std::optional<std::string> script_package;
  int allow_compilation = false;

  std::optional<string> opt_group_id;
  std::optional<string> opt_status;
  std::optional<string> opt_flow_type;
  std::optional<vector<string> > opt_zone_names;
  std::optional<vector<rgw_zone_id> > opt_zone_ids;
  std::optional<string> opt_flow_id;
  std::optional<string> opt_source_zone_name;
  std::optional<rgw_zone_id> opt_source_zone_id;
  std::optional<string> opt_dest_zone_name;
  std::optional<rgw_zone_id> opt_dest_zone_id;
  std::optional<vector<string> > opt_source_zone_names;
  std::optional<vector<rgw_zone_id> > opt_source_zone_ids;
  std::optional<vector<string> > opt_dest_zone_names;
  std::optional<vector<rgw_zone_id> > opt_dest_zone_ids;
  std::optional<string> opt_pipe_id;
  std::optional<rgw_bucket> opt_bucket;
  std::optional<string> opt_tenant;
  std::optional<string> opt_bucket_name;
  std::optional<string> opt_bucket_id;
  std::optional<rgw_bucket> opt_source_bucket;
  std::optional<string> opt_source_tenant;
  std::optional<string> opt_source_bucket_name;
  std::optional<string> opt_source_bucket_id;
  std::optional<rgw_bucket> opt_dest_bucket;
  std::optional<string> opt_dest_tenant;
  std::optional<string> opt_dest_bucket_name;
  std::optional<string> opt_dest_bucket_id;
  std::optional<string> opt_effective_zone_name;
  std::optional<rgw_zone_id> opt_effective_zone_id;

  std::optional<string> opt_prefix;
  std::optional<string> opt_prefix_rm;

  std::optional<int> opt_priority;
  std::optional<string> opt_mode;
  std::optional<rgw_user> opt_dest_owner;
  ceph::timespan opt_retry_delay_ms = std::chrono::milliseconds(2000);
  ceph::timespan opt_timeout_sec = std::chrono::seconds(60);

  SimpleCmd cmd(all_cmds, cmd_aliases);

  std::optional<std::string> rgw_obj_fs; // radoslist field separator

  for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
    if (ceph_argparse_double_dash(args, i)) {
      break;
    } else if (ceph_argparse_witharg(args, i, &val, "-i", "--uid", (char*)NULL)) {
      user_id.from_str(val);
      if (user_id.empty()) {
        cerr << "no value for uid" << std::endl;
        exit(1);
      }
    } else if (ceph_argparse_witharg(args, i, &val, "-i", "--new-uid", (char*)NULL)) {
      new_user_id.from_str(val);
    } else if (ceph_argparse_witharg(args, i, &val, "--tenant", (char*)NULL)) {
      tenant = val;
      opt_tenant = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--user_ns", (char*)NULL)) {
      user_ns = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--access-key", (char*)NULL)) {
      access_key = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--subuser", (char*)NULL)) {
      subuser = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--secret", "--secret-key", (char*)NULL)) {
      secret_key = val;
    } else if (ceph_argparse_witharg(args, i, &val, "-e", "--email", (char*)NULL)) {
      user_email = val;
      user_op.user_email_specified=true;
    } else if (ceph_argparse_witharg(args, i, &val, "-n", "--display-name", (char*)NULL)) {
      display_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "-b", "--bucket", (char*)NULL)) {
      bucket_name = val;
      opt_bucket_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "-p", "--pool", (char*)NULL)) {
      pool_name = val;
      pool = rgw_pool(pool_name);
    } else if (ceph_argparse_witharg(args, i, &val, "-o", "--object", (char*)NULL)) {
      object = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--object-version", (char*)NULL)) {
      object_version = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--client-id", (char*)NULL)) {
      client_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--op-id", (char*)NULL)) {
      op_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--op-mask", (char*)NULL)) {
      op_mask_str = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--key-type", (char*)NULL)) {
      key_type_str = val;
      if (key_type_str.compare("swift") == 0) {
        key_type = KEY_TYPE_SWIFT;
      } else if (key_type_str.compare("s3") == 0) {
        key_type = KEY_TYPE_S3;
      } else {
        cerr << "bad key type: " << key_type_str << std::endl;
        exit(1);
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--job-id", (char*)NULL)) {
      job_id = val;
    } else if (ceph_argparse_binary_flag(args, i, &gen_access_key, NULL, "--gen-access-key", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &gen_secret_key, NULL, "--gen-secret", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &show_log_entries, NULL, "--show-log-entries", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &show_log_sum, NULL, "--show-log-sum", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &skip_zero_entries, NULL, "--skip-zero-entries", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &admin, NULL, "--admin", (char*)NULL)) {
      admin_specified = true;
    } else if (ceph_argparse_binary_flag(args, i, &system, NULL, "--system", (char*)NULL)) {
      system_specified = true;
    } else if (ceph_argparse_binary_flag(args, i, &verbose, NULL, "--verbose", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &staging, NULL, "--staging", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &commit, NULL, "--commit", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-size", (char*)NULL)) {
      min_rewrite_size = (uint64_t)atoll(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--max-rewrite-size", (char*)NULL)) {
      max_rewrite_size = (uint64_t)atoll(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-stripe-size", (char*)NULL)) {
      min_rewrite_stripe_size = (uint64_t)atoll(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--max-buckets", (char*)NULL)) {
      max_buckets = (int)strict_strtol(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse max buckets: " << err << std::endl;
        return EINVAL;
      }
      max_buckets_specified = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--max-entries", (char*)NULL)) {
      max_entries = (int)strict_strtol(val.c_str(), 10, &err);
      max_entries_specified = true;
      if (!err.empty()) {
        cerr << "ERROR: failed to parse max entries: " << err << std::endl;
        return EINVAL;
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--max-size", (char*)NULL)) {
      max_size = strict_iec_cast<long long>(val.c_str(), &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse max size: " << err << std::endl;
        return EINVAL;
      }
      have_max_size = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--max-objects", (char*)NULL)) {
      max_objects = (int64_t)strict_strtoll(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse max objects: " << err << std::endl;
        return EINVAL;
      }
      have_max_objects = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--date", "--time", (char*)NULL)) {
      date = val;
      if (end_date.empty())
        end_date = date;
    } else if (ceph_argparse_witharg(args, i, &val, "--start-date", "--start-time", (char*)NULL)) {
      start_date = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--end-date", "--end-time", (char*)NULL)) {
      end_date = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--num-shards", (char*)NULL)) {
      num_shards = (int)strict_strtol(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse num shards: " << err << std::endl;
        return EINVAL;
      }
      num_shards_specified = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--bucket-index-max-shards", (char*)NULL)) {
      bucket_index_max_shards = (int)strict_strtol(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse bucket-index-max-shards: " << err << std::endl;
        return EINVAL;
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--max-concurrent-ios", (char*)NULL)) {
      max_concurrent_ios = (int)strict_strtol(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse max concurrent ios: " << err << std::endl;
        return EINVAL;
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--orphan-stale-secs", (char*)NULL)) {
      orphan_stale_secs = (uint64_t)strict_strtoll(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse orphan stale secs: " << err << std::endl;
        return EINVAL;
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--shard-id", (char*)NULL)) {
      shard_id = (int)strict_strtol(val.c_str(), 10, &err);
      if (!err.empty()) {
        cerr << "ERROR: failed to parse shard id: " << err << std::endl;
        return EINVAL;
      }
      specified_shard_id = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--access", (char*)NULL)) {
      access = val;
      perm_mask = rgw_str_to_perm(access.c_str());
      set_perm = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key", (char*)NULL)) {
      temp_url_keys[0] = val;
      set_temp_url_key = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key2", "--temp-url-key-2", (char*)NULL)) {
      temp_url_keys[1] = val;
      set_temp_url_key = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--bucket-id", (char*)NULL)) {
      bucket_id = val;
      opt_bucket_id = val;
      if (bucket_id.empty()) {
        cerr << "no value for bucket-id" << std::endl;
        exit(1);
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--bucket-new-name", (char*)NULL)) {
      new_bucket_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--format", (char*)NULL)) {
      format = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--categories", (char*)NULL)) {
      string cat_str = val;
      list<string> cat_list;
      list<string>::iterator iter;
      get_str_list(cat_str, cat_list);
      for (iter = cat_list.begin(); iter != cat_list.end(); ++iter) {
	categories[*iter] = true;
      }
    } else if (ceph_argparse_binary_flag(args, i, &delete_child_objects, NULL, "--purge-objects", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &pretty_format, NULL, "--pretty-format", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &purge_data, NULL, "--purge-data", (char*)NULL)) {
      delete_child_objects = purge_data;
    } else if (ceph_argparse_binary_flag(args, i, &purge_keys, NULL, "--purge-keys", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &yes_i_really_mean_it, NULL, "--yes-i-really-mean-it", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &fix, NULL, "--fix", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &remove_bad, NULL, "--remove-bad", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &check_head_obj_locator, NULL, "--check-head-obj-locator", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &check_objects, NULL, "--check-objects", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &sync_stats, NULL, "--sync-stats", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &reset_stats, NULL, "--reset-stats", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &include_all, NULL, "--include-all", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &allow_unordered, NULL, "--allow-unordered", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &extra_info, NULL, "--extra-info", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &bypass_gc, NULL, "--bypass-gc", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &warnings_only, NULL, "--warnings-only", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_binary_flag(args, i, &inconsistent_index, NULL, "--inconsistent-index", (char*)NULL)) {
     // do nothing
    } else if (ceph_argparse_witharg(args, i, &val, "--caps", (char*)NULL)) {
      caps = val;
    } else if (ceph_argparse_witharg(args, i, &val, "-i", "--infile", (char*)NULL)) {
      infile = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--metadata-key", (char*)NULL)) {
      metadata_key = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--marker", (char*)NULL)) {
      marker = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--start-marker", (char*)NULL)) {
      start_marker = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--end-marker", (char*)NULL)) {
      end_marker = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--quota-scope", (char*)NULL)) {
      quota_scope = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--index-type", (char*)NULL)) {
      string index_type_str = val;
      bi_index_type = get_bi_index_type(index_type_str);
      if (bi_index_type == BIIndexType::Invalid) {
        cerr << "ERROR: invalid bucket index entry type" << std::endl;
        return EINVAL;
      }
    } else if (ceph_argparse_witharg(args, i, &val, "--log-type", (char*)NULL)) {
      string log_type_str = val;
      auto l = get_log_type(log_type_str);
      if (l == static_cast<log_type>(0xff)) {
        cerr << "ERROR: invalid log type" << std::endl;
        return EINVAL;
      }
      opt_log_type = l;
    } else if (ceph_argparse_binary_flag(args, i, &is_master_int, NULL, "--master", (char*)NULL)) {
      is_master = (bool)is_master_int;
      is_master_set = true;
    } else if (ceph_argparse_binary_flag(args, i, &set_default, NULL, "--default", (char*)NULL)) {
      /* do nothing */
    } else if (ceph_argparse_witharg(args, i, &val, "--redirect-zone", (char*)NULL)) {
      redirect_zone = val;
      redirect_zone_set = true;
    } else if (ceph_argparse_binary_flag(args, i, &read_only_int, NULL, "--read-only", (char*)NULL)) {
      read_only = (bool)read_only_int;
      is_read_only_set = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--master-zone", (char*)NULL)) {
      master_zone = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--period", (char*)NULL)) {
      period_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--epoch", (char*)NULL)) {
      period_epoch = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--remote", (char*)NULL)) {
      remote = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--url", (char*)NULL)) {
      url = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--realm-id", (char*)NULL)) {
      realm_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--realm-new-name", (char*)NULL)) {
      realm_new_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-id", (char*)NULL)) {
      zonegroup_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-new-name", (char*)NULL)) {
      zonegroup_new_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--placement-id", (char*)NULL)) {
      placement_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--storage-class", (char*)NULL)) {
      opt_storage_class = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--tags", (char*)NULL)) {
      get_str_list(val, ",", tags);
    } else if (ceph_argparse_witharg(args, i, &val, "--tags-add", (char*)NULL)) {
      get_str_list(val, ",", tags_add);
    } else if (ceph_argparse_witharg(args, i, &val, "--tags-rm", (char*)NULL)) {
      get_str_list(val, ",", tags_rm);
    } else if (ceph_argparse_witharg(args, i, &val, "--api-name", (char*)NULL)) {
      api_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--zone-id", (char*)NULL)) {
      zone_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--zone-new-name", (char*)NULL)) {
      zone_new_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--endpoints", (char*)NULL)) {
      get_str_list(val, endpoints);
    } else if (ceph_argparse_witharg(args, i, &val, "--sync-from", (char*)NULL)) {
      get_str_list(val, sync_from);
    } else if (ceph_argparse_witharg(args, i, &val, "--sync-from-rm", (char*)NULL)) {
      get_str_list(val, sync_from_rm);
    } else if (ceph_argparse_binary_flag(args, i, &tmp_int, NULL, "--sync-from-all", (char*)NULL)) {
      sync_from_all = (bool)tmp_int;
      sync_from_all_specified = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--source-zone", (char*)NULL)) {
      source_zone_name = val;
      opt_source_zone_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--source-zone-id", (char*)NULL)) {
      opt_source_zone_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-zone", (char*)NULL)) {
      opt_dest_zone_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-zone-id", (char*)NULL)) {
      opt_dest_zone_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--tier-type", (char*)NULL)) {
      tier_type = val;
      tier_type_specified = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--tier-config", (char*)NULL)) {
      parse_tier_config_param(val, tier_config_add);
    } else if (ceph_argparse_witharg(args, i, &val, "--tier-config-rm", (char*)NULL)) {
      parse_tier_config_param(val, tier_config_rm);
    } else if (ceph_argparse_witharg(args, i, &val, "--index-pool", (char*)NULL)) {
      index_pool = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--data-pool", (char*)NULL)) {
      data_pool = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--data-extra-pool", (char*)NULL)) {
      data_extra_pool = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--placement-index-type", (char*)NULL)) {
      if (val == "normal") {
        placement_index_type = rgw::BucketIndexType::Normal;
      } else if (val == "indexless") {
        placement_index_type = rgw::BucketIndexType::Indexless;
      } else {
        placement_index_type = (rgw::BucketIndexType)strict_strtol(val.c_str(), 10, &err);
        if (!err.empty()) {
          cerr << "ERROR: failed to parse index type index: " << err << std::endl;
          return EINVAL;
        }
      }
      index_type_specified = true;
    } else if (ceph_argparse_witharg(args, i, &val, "--compression", (char*)NULL)) {
      compression_type = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--role-name", (char*)NULL)) {
      role_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--path", (char*)NULL)) {
      path = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--assume-role-policy-doc", (char*)NULL)) {
      assume_role_doc = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--policy-name", (char*)NULL)) {
      policy_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--policy-doc", (char*)NULL)) {
      perm_policy_doc = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--path-prefix", (char*)NULL)) {
      path_prefix = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--totp-serial", (char*)NULL)) {
      totp_serial = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--totp-pin", (char*)NULL)) {
      totp_pin.push_back(val);
    } else if (ceph_argparse_witharg(args, i, &val, "--totp-seed", (char*)NULL)) {
      totp_seed = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--totp-seed-type", (char*)NULL)) {
      totp_seed_type = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--totp-seconds", (char*)NULL)) {
      totp_seconds = atoi(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--totp-window", (char*)NULL)) {
      totp_window = atoi(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--trim-delay-ms", (char*)NULL)) {
      trim_delay_ms = atoi(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--topic", (char*)NULL)) {
      topic_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--subscription", (char*)NULL)) {
      sub_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--event-id", (char*)NULL)) {
      event_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--group-id", (char*)NULL)) {
      opt_group_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--status", (char*)NULL)) {
      opt_status = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--flow-type", (char*)NULL)) {
      opt_flow_type = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--zones", "--zone-names", (char*)NULL)) {
      vector<string> v;
      get_str_vec(val, v);
      opt_zone_names = std::move(v);
    } else if (ceph_argparse_witharg(args, i, &val, "--zone-ids", (char*)NULL)) {
      opt_zone_ids = zone_ids_from_str(val);
    } else if (ceph_argparse_witharg(args, i, &val, "--source-zones", "--source-zone-names", (char*)NULL)) {
      vector<string> v;
      get_str_vec(val, v);
      opt_source_zone_names = std::move(v);
    } else if (ceph_argparse_witharg(args, i, &val, "--source-zone-ids", (char*)NULL)) {
      opt_source_zone_ids = zone_ids_from_str(val);
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-zones", "--dest-zone-names", (char*)NULL)) {
      vector<string> v;
      get_str_vec(val, v);
      opt_dest_zone_names = std::move(v);
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-zone-ids", (char*)NULL)) {
      opt_dest_zone_ids = zone_ids_from_str(val);
    } else if (ceph_argparse_witharg(args, i, &val, "--flow-id", (char*)NULL)) {
      opt_flow_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--pipe-id", (char*)NULL)) {
      opt_pipe_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--source-tenant", (char*)NULL)) {
      opt_source_tenant = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--source-bucket", (char*)NULL)) {
      opt_source_bucket_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--source-bucket-id", (char*)NULL)) {
      opt_source_bucket_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-tenant", (char*)NULL)) {
      opt_dest_tenant = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-bucket", (char*)NULL)) {
      opt_dest_bucket_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-bucket-id", (char*)NULL)) {
      opt_dest_bucket_id = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--effective-zone-name", "--effective-zone", (char*)NULL)) {
      opt_effective_zone_name = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--effective-zone-id", (char*)NULL)) {
      opt_effective_zone_id = rgw_zone_id(val);
    } else if (ceph_argparse_witharg(args, i, &val, "--prefix", (char*)NULL)) {
      opt_prefix = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--prefix-rm", (char*)NULL)) {
      opt_prefix_rm = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--priority", (char*)NULL)) {
      opt_priority = atoi(val.c_str());
    } else if (ceph_argparse_witharg(args, i, &val, "--mode", (char*)NULL)) {
      opt_mode = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--dest-owner", (char*)NULL)) {
      opt_dest_owner.emplace(val);
      opt_dest_owner = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--retry-delay-ms", (char*)NULL)) {
      opt_retry_delay_ms = std::chrono::milliseconds(atoi(val.c_str()));
    } else if (ceph_argparse_witharg(args, i, &val, "--timeout-sec", (char*)NULL)) {
      opt_timeout_sec = std::chrono::seconds(atoi(val.c_str()));
    } else if (ceph_argparse_binary_flag(args, i, &detail, NULL, "--detail", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_witharg(args, i, &val, "--context", (char*)NULL)) {
      str_script_ctx = val;
    } else if (ceph_argparse_witharg(args, i, &val, "--package", (char*)NULL)) {
      script_package = val;
    } else if (ceph_argparse_binary_flag(args, i, &allow_compilation, NULL, "--allow-compilation", (char*)NULL)) {
      // do nothing
    } else if (ceph_argparse_witharg(args, i, &val, "--rgw-obj-fs", (char*)NULL)) {
      rgw_obj_fs = val;
    } else if (strncmp(*i, "-", 1) == 0) {
      cerr << "ERROR: invalid flag " << *i << std::endl;
      return EINVAL;
    } else {
      ++i;
    }
  }

  if (args.empty()) {
    usage();
    exit(1);
  }
  else {
    std::vector<string> extra_args;
    std::vector<string> expected;

    std::any _opt_cmd;

    if (!cmd.find_command(args, &_opt_cmd, &extra_args, &err, &expected)) {
      if (!expected.empty()) {
        cerr << err << std::endl;
        cerr << "Expected one of the following:" << std::endl;
        for (auto& exp : expected) {
          if (exp == "*" || exp == "[*]") {
            continue;
          }
          cerr << "  " << exp << std::endl;
        }
      } else {
        cerr << "Command not found:";
        for (auto& arg : args) {
          cerr << " " << arg;
        }
        cerr << std::endl;
      }
      exit(1);
    }

    opt_cmd = std::any_cast<OPT>(_opt_cmd);

    /* some commands may have an optional extra param */
    if (!extra_args.empty()) {
      switch (opt_cmd) {
        case OPT::METADATA_GET:
        case OPT::METADATA_PUT:
        case OPT::METADATA_RM:
        case OPT::METADATA_LIST:
          metadata_key = extra_args[0];
          break;
        default:
          break;
      }
    }

    init_optional_bucket(opt_bucket, opt_tenant,
                         opt_bucket_name, opt_bucket_id);
    init_optional_bucket(opt_source_bucket, opt_source_tenant,
                         opt_source_bucket_name, opt_source_bucket_id);
    init_optional_bucket(opt_dest_bucket, opt_dest_tenant,
                         opt_dest_bucket_name, opt_dest_bucket_id);

    if (tenant.empty()) {
      tenant = user_id.tenant;
    } else {
      if (user_id.empty() && opt_cmd != OPT::ROLE_CREATE
                          && opt_cmd != OPT::ROLE_DELETE
                          && opt_cmd != OPT::ROLE_GET
                          && opt_cmd != OPT::ROLE_MODIFY
                          && opt_cmd != OPT::ROLE_LIST
                          && opt_cmd != OPT::ROLE_POLICY_PUT
                          && opt_cmd != OPT::ROLE_POLICY_LIST
                          && opt_cmd != OPT::ROLE_POLICY_GET
                          && opt_cmd != OPT::ROLE_POLICY_DELETE
                          && opt_cmd != OPT::RESHARD_ADD
                          && opt_cmd != OPT::RESHARD_CANCEL
                          && opt_cmd != OPT::RESHARD_STATUS) {
        cerr << "ERROR: --tenant is set, but there's no user ID" << std::endl;
        return EINVAL;
      }
      user_id.tenant = tenant;
    }
    if (user_ns.empty()) {
      user_ns = user_id.ns;
    } else {
      user_id.ns = user_ns;
    }

    if (!new_user_id.empty() && !tenant.empty()) {
      new_user_id.tenant = tenant;
    }

    /* check key parameter conflict */
    if ((!access_key.empty()) && gen_access_key) {
        cerr << "ERROR: key parameter conflict, --access-key & --gen-access-key" << std::endl;
        return EINVAL;
    }
    if ((!secret_key.empty()) && gen_secret_key) {
        cerr << "ERROR: key parameter conflict, --secret & --gen-secret" << std::endl;
        return EINVAL;
    }
  }

  // default to pretty json
  if (format.empty()) {
    format = "json";
    pretty_format = true;
  }

  if (format ==  "xml")
    formatter = make_unique<XMLFormatter>(new XMLFormatter(pretty_format));
  else if (format == "json")
    formatter = make_unique<JSONFormatter>(new JSONFormatter(pretty_format));
  else {
    cerr << "unrecognized format: " << format << std::endl;
    exit(1);
  }

  zone_formatter = std::make_unique<JSONFormatter_PrettyZone>(new JSONFormatter_PrettyZone(pretty_format));

  realm_name = g_conf()->rgw_realm;
  zone_name = g_conf()->rgw_zone;
  zonegroup_name = g_conf()->rgw_zonegroup;

  RGWStreamFlusher f(formatter.get(), cout);

  // not a raw op if 'period update' needs to commit to master
  bool raw_period_update = opt_cmd == OPT::PERIOD_UPDATE && !commit;
  // not a raw op if 'period pull' needs to read zone/period configuration
  bool raw_period_pull = opt_cmd == OPT::PERIOD_PULL && !url.empty();

  std::set<OPT> raw_storage_ops_list = {OPT::ZONEGROUP_ADD, OPT::ZONEGROUP_CREATE, OPT::ZONEGROUP_DELETE,
			 OPT::ZONEGROUP_GET, OPT::ZONEGROUP_LIST,
                         OPT::ZONEGROUP_SET, OPT::ZONEGROUP_DEFAULT,
			 OPT::ZONEGROUP_RENAME, OPT::ZONEGROUP_MODIFY,
			 OPT::ZONEGROUP_REMOVE,
			 OPT::ZONEGROUP_PLACEMENT_ADD, OPT::ZONEGROUP_PLACEMENT_RM,
			 OPT::ZONEGROUP_PLACEMENT_MODIFY, OPT::ZONEGROUP_PLACEMENT_LIST,
			 OPT::ZONEGROUP_PLACEMENT_GET,
			 OPT::ZONEGROUP_PLACEMENT_DEFAULT,
			 OPT::ZONE_CREATE, OPT::ZONE_DELETE,
                         OPT::ZONE_GET, OPT::ZONE_SET, OPT::ZONE_RENAME,
                         OPT::ZONE_LIST, OPT::ZONE_MODIFY, OPT::ZONE_DEFAULT,
			 OPT::ZONE_PLACEMENT_ADD, OPT::ZONE_PLACEMENT_RM,
			 OPT::ZONE_PLACEMENT_MODIFY, OPT::ZONE_PLACEMENT_LIST,
			 OPT::ZONE_PLACEMENT_GET,
			 OPT::REALM_CREATE,
			 OPT::PERIOD_DELETE, OPT::PERIOD_GET,
			 OPT::PERIOD_GET_CURRENT, OPT::PERIOD_LIST,
			 OPT::GLOBAL_QUOTA_GET, OPT::GLOBAL_QUOTA_SET,
			 OPT::GLOBAL_QUOTA_ENABLE, OPT::GLOBAL_QUOTA_DISABLE,
			 OPT::REALM_DELETE, OPT::REALM_GET, OPT::REALM_LIST,
			 OPT::REALM_LIST_PERIODS,
			 OPT::REALM_GET_DEFAULT,
			 OPT::REALM_RENAME, OPT::REALM_SET,
			 OPT::REALM_DEFAULT, OPT::REALM_PULL};

  std::set<OPT> readonly_ops_list = {
                         OPT::USER_INFO,
			 OPT::USER_STATS,
			 OPT::BUCKETS_LIST,
			 OPT::BUCKET_LIMIT_CHECK,
			 OPT::BUCKET_STATS,
			 OPT::BUCKET_SYNC_CHECKPOINT,
			 OPT::BUCKET_SYNC_INFO,
			 OPT::BUCKET_SYNC_STATUS,
			 OPT::BUCKET_SYNC_MARKERS,
			 OPT::LOG_LIST,
			 OPT::LOG_SHOW,
			 OPT::USAGE_SHOW,
			 OPT::OBJECT_STAT,
			 OPT::BI_GET,
			 OPT::BI_LIST,
			 OPT::OLH_GET,
			 OPT::OLH_READLOG,
			 OPT::GC_LIST,
			 OPT::LC_LIST,
			 OPT::ORPHANS_LIST_JOBS,
			 OPT::ZONEGROUP_GET,
			 OPT::ZONEGROUP_LIST,
			 OPT::ZONEGROUP_PLACEMENT_LIST,
			 OPT::ZONEGROUP_PLACEMENT_GET,
			 OPT::ZONE_GET,
			 OPT::ZONE_LIST,
			 OPT::ZONE_PLACEMENT_LIST,
			 OPT::ZONE_PLACEMENT_GET,
			 OPT::METADATA_GET,
			 OPT::METADATA_LIST,
			 OPT::METADATA_SYNC_STATUS,
			 OPT::MDLOG_LIST,
			 OPT::MDLOG_STATUS,
			 OPT::SYNC_ERROR_LIST,
			 OPT::SYNC_GROUP_GET,
			 OPT::SYNC_POLICY_GET,
			 OPT::BILOG_LIST,
			 OPT::BILOG_STATUS,
			 OPT::DATA_SYNC_STATUS,
			 OPT::DATALOG_LIST,
			 OPT::DATALOG_STATUS,
			 OPT::REALM_GET,
			 OPT::REALM_GET_DEFAULT,
			 OPT::REALM_LIST,
			 OPT::REALM_LIST_PERIODS,
			 OPT::PERIOD_GET,
			 OPT::PERIOD_GET_CURRENT,
			 OPT::PERIOD_LIST,
			 OPT::GLOBAL_QUOTA_GET,
			 OPT::SYNC_INFO,
			 OPT::SYNC_STATUS,
			 OPT::ROLE_GET,
			 OPT::ROLE_LIST,
			 OPT::ROLE_POLICY_LIST,
			 OPT::ROLE_POLICY_GET,
			 OPT::RESHARD_LIST,
			 OPT::RESHARD_STATUS,
			 OPT::PUBSUB_TOPICS_LIST,
			 OPT::PUBSUB_TOPIC_GET,
			 OPT::PUBSUB_SUB_GET,
			 OPT::PUBSUB_SUB_PULL,
			 OPT::SCRIPT_GET,
    };

    std::set<OPT> gc_ops_list = {
			 OPT::GC_LIST,
			 OPT::GC_PROCESS,
			 OPT::OBJECT_RM,
			 OPT::BUCKET_RM,  // --purge-objects
			 OPT::USER_RM,    // --purge-data
			 OPT::OBJECTS_EXPIRE,
			 OPT::OBJECTS_EXPIRE_STALE_RM,
			 OPT::LC_PROCESS,
             OPT::BUCKET_SYNC_RUN,
             OPT::DATA_SYNC_RUN,
    };

  bool raw_storage_op = (raw_storage_ops_list.find(opt_cmd) != raw_storage_ops_list.end() ||
                         raw_period_update || raw_period_pull);
  bool need_cache = readonly_ops_list.find(opt_cmd) == readonly_ops_list.end();
  bool need_gc = (gc_ops_list.find(opt_cmd) != gc_ops_list.end()) && !bypass_gc;

    if (raw_storage_op) {
    store = RGWStoreManager::get_raw_storage(dpp(), g_ceph_context);
  } else {
    store = RGWStoreManager::get_storage(dpp(), g_ceph_context, false, false, false, false, false,
      need_cache && g_conf()->rgw_cache_enabled, need_gc);
  }
  if (!store) {
    cerr << "couldn't init storage provider" << std::endl;
    return 5; //EIO
  }

  if (!source_zone_name.empty()) {
    if (!store->svc()->zone->find_zone_id_by_name(source_zone_name, &source_zone)) {
      cerr << "WARNING: cannot find source zone id for name=" << source_zone_name << std::endl;
      source_zone = source_zone_name;
    }
  }

  rgw_http_client_init(g_ceph_context);

  struct rgw_curl_setup {
    rgw_curl_setup() {
      rgw::curl::setup_curl(boost::none);
    }
    ~rgw_curl_setup() {
      rgw::curl::cleanup_curl();
    }
  } curl_cleanup;

  oath_init();

  StoreDestructor store_destructor(store);

  if (raw_storage_op) {
    switch (opt_cmd) {
    case OPT::PERIOD_DELETE:
      {
	if (period_id.empty()) {
	  cerr << "missing period id" << std::endl;
	  return EINVAL;
	}
	RGWPeriod period(period_id);
	int ret = period.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "period.init failed: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = period.delete_obj(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "ERROR: couldn't delete period: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

      }
      break;
    case OPT::PERIOD_GET:
      {
	epoch_t epoch = 0;
	if (!period_epoch.empty()) {
	  epoch = atoi(period_epoch.c_str());
	}
        if (staging) {
          RGWRealm realm(realm_id, realm_name);
          int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
          if (ret < 0 ) {
            cerr << "Error initializing realm " << cpp_strerror(-ret) << std::endl;
            return -ret;
          }
          realm_id = realm.get_id();
          realm_name = realm.get_name();
          period_id = RGWPeriod::get_staging_id(realm_id);
          epoch = 1;
        }
	RGWPeriod period(period_id, epoch);
	int ret = period.init(dpp(), g_ceph_context, store->svc()->sysobj, realm_id,
			      null_yield, realm_name);
	if (ret < 0) {
	  cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	encode_json("period", period, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::PERIOD_GET_CURRENT:
      {
        int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
	if (ret < 0) {
	  return -ret;
	}
	formatter->open_object_section("period_get_current");
	encode_json("current_period", period_id, formatter.get());
	formatter->close_section();
	formatter->flush(cout);
      }
      break;
    case OPT::PERIOD_LIST:
      {
	list<string> periods;
	int ret = store->svc()->zone->list_periods(dpp(), periods);
	if (ret < 0) {
	  cerr << "failed to list periods: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	formatter->open_object_section("periods_list");
	encode_json("periods", periods, formatter.get());
	formatter->close_section();
	formatter->flush(cout);
      }
      break;
    case OPT::PERIOD_UPDATE:
      {
        int ret = update_period(realm_id, realm_name, period_id, period_epoch,
                                commit, remote, url, access_key, secret_key,
                                formatter.get(), yes_i_really_mean_it);
	if (ret < 0) {
	  return -ret;
	}
      }
      break;
    case OPT::PERIOD_PULL:
      {
        boost::optional<RGWRESTConn> conn;
        RGWRESTConn *remote_conn = nullptr;
        if (url.empty()) {
          // load current period for endpoints
          RGWRealm realm(realm_id, realm_name);
          int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
          if (ret < 0) {
            cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
            return -ret;
          }
          RGWPeriod current_period(realm.get_current_period());
          ret = current_period.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
          if (ret < 0) {
            cerr << "failed to init current period: " << cpp_strerror(-ret) << std::endl;
            return -ret;
          }
          if (remote.empty()) {
            // use realm master zone as remote
            remote = current_period.get_master_zone().id;
          }
          conn = get_remote_conn(store, current_period.get_map(), remote);
          if (!conn) {
            cerr << "failed to find a zone or zonegroup for remote "
                << remote << std::endl;
            return -ENOENT;
          }
          remote_conn = &*conn;
        }

        RGWPeriod period;
        int ret = do_period_pull(remote_conn, url, access_key, secret_key,
                                 realm_id, realm_name, period_id, period_epoch,
                                 &period);
        if (ret < 0) {
          cerr << "period pull failed: " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        encode_json("period", period, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::GLOBAL_QUOTA_GET:
    case OPT::GLOBAL_QUOTA_SET:
    case OPT::GLOBAL_QUOTA_ENABLE:
    case OPT::GLOBAL_QUOTA_DISABLE:
      {
        if (realm_id.empty()) {
          RGWRealm realm(g_ceph_context, store->svc()->sysobj);
          if (!realm_name.empty()) {
            // look up realm_id for the given realm_name
            int ret = realm.read_id(dpp(), realm_name, realm_id, null_yield);
            if (ret < 0) {
              cerr << "ERROR: failed to read realm for " << realm_name
                  << ": " << cpp_strerror(-ret) << std::endl;
              return -ret;
            }
          } else {
            // use default realm_id when none is given
            int ret = realm.read_default_id(dpp(), realm_id, null_yield);
            if (ret < 0 && ret != -ENOENT) { // on ENOENT, use empty realm_id
              cerr << "ERROR: failed to read default realm: "
                  << cpp_strerror(-ret) << std::endl;
              return -ret;
            }
          }
        }

        RGWPeriodConfig period_config;
        int ret = period_config.read(dpp(), store->svc()->sysobj, realm_id, null_yield);
        if (ret < 0 && ret != -ENOENT) {
          cerr << "ERROR: failed to read period config: "
              << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        formatter->open_object_section("period_config");
        if (quota_scope == "bucket") {
          set_quota_info(period_config.bucket_quota, opt_cmd,
                         max_size, max_objects,
                         have_max_size, have_max_objects);
          encode_json("bucket quota", period_config.bucket_quota, formatter.get());
        } else if (quota_scope == "user") {
          set_quota_info(period_config.user_quota, opt_cmd,
                         max_size, max_objects,
                         have_max_size, have_max_objects);
          encode_json("user quota", period_config.user_quota, formatter.get());
        } else if (quota_scope.empty() && opt_cmd == OPT::GLOBAL_QUOTA_GET) {
          // if no scope is given for GET, print both
          encode_json("bucket quota", period_config.bucket_quota, formatter.get());
          encode_json("user quota", period_config.user_quota, formatter.get());
        } else {
          cerr << "ERROR: invalid quota scope specification. Please specify "
              "either --quota-scope=bucket, or --quota-scope=user" << std::endl;
          return EINVAL;
        }
        formatter->close_section();

        if (opt_cmd != OPT::GLOBAL_QUOTA_GET) {
          // write the modified period config
          ret = period_config.write(dpp(), store->svc()->sysobj, realm_id, null_yield);
          if (ret < 0) {
            cerr << "ERROR: failed to write period config: "
                << cpp_strerror(-ret) << std::endl;
            return -ret;
          }
          if (!realm_id.empty()) {
            cout << "Global quota changes saved. Use 'period update' to apply "
                "them to the staging period, and 'period commit' to commit the "
                "new period." << std::endl;
          } else {
            cout << "Global quota changes saved. They will take effect as "
                "the gateways are restarted." << std::endl;
          }
        }

        formatter->flush(cout);
      }
      break;
    case OPT::REALM_CREATE:
      {
	if (realm_name.empty()) {
	  cerr << "missing realm name" << std::endl;
	  return EINVAL;
	}

	RGWRealm realm(realm_name, g_ceph_context, store->svc()->sysobj);
	int ret = realm.create(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "ERROR: couldn't create realm " << realm_name << ": " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        if (set_default) {
          ret = realm.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

	encode_json("realm", realm, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::REALM_DELETE:
      {
	RGWRealm realm(realm_id, realm_name);
	if (realm_name.empty() && realm_id.empty()) {
	  cerr << "missing realm name or id" << std::endl;
	  return EINVAL;
	}
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "realm.init failed: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = realm.delete_obj(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "ERROR: couldn't : " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

      }
      break;
    case OPT::REALM_GET:
      {
	RGWRealm realm(realm_id, realm_name);
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  if (ret == -ENOENT && realm_name.empty() && realm_id.empty()) {
	    cerr << "missing realm name or id, or default realm not found" << std::endl;
	  } else {
	    cerr << "realm.init failed: " << cpp_strerror(-ret) << std::endl;
          }
	  return -ret;
	}
	encode_json("realm", realm, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::REALM_GET_DEFAULT:
      {
	RGWRealm realm(g_ceph_context, store->svc()->sysobj);
	string default_id;
	int ret = realm.read_default_id(dpp(), default_id, null_yield);
	if (ret == -ENOENT) {
	  cout << "No default realm is set" << std::endl;
	  return -ret;
	} else if (ret < 0) {
	  cerr << "Error reading default realm:" << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	cout << "default realm: " << default_id << std::endl;
      }
      break;
    case OPT::REALM_LIST:
      {
	RGWRealm realm(g_ceph_context, store->svc()->sysobj);
	string default_id;
	int ret = realm.read_default_id(dpp(), default_id, null_yield);
	if (ret < 0 && ret != -ENOENT) {
	  cerr << "could not determine default realm: " << cpp_strerror(-ret) << std::endl;
	}
	list<string> realms;
	ret = store->svc()->zone->list_realms(dpp(), realms);
	if (ret < 0) {
	  cerr << "failed to list realms: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	formatter->open_object_section("realms_list");
	encode_json("default_info", default_id, formatter.get());
	encode_json("realms", realms, formatter.get());
	formatter->close_section();
	formatter->flush(cout);
      }
      break;
    case OPT::REALM_LIST_PERIODS:
      {
        int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
	if (ret < 0) {
	  return -ret;
	}
	list<string> periods;
	ret = store->svc()->zone->list_periods(dpp(), period_id, periods, null_yield);
	if (ret < 0) {
	  cerr << "list periods failed: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	formatter->open_object_section("realm_periods_list");
	encode_json("current_period", period_id, formatter.get());
	encode_json("periods", periods, formatter.get());
	formatter->close_section();
	formatter->flush(cout);
      }
      break;

    case OPT::REALM_RENAME:
      {
	RGWRealm realm(realm_id, realm_name);
	if (realm_new_name.empty()) {
	  cerr << "missing realm new name" << std::endl;
	  return EINVAL;
	}
	if (realm_name.empty() && realm_id.empty()) {
	  cerr << "missing realm name or id" << std::endl;
	  return EINVAL;
	}
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "realm.init failed: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = realm.rename(dpp(), realm_new_name, null_yield);
	if (ret < 0) {
	  cerr << "realm.rename failed: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
        cout << "Realm name updated. Note that this change only applies to "
            "the current cluster, so this command must be run separately "
            "on each of the realm's other clusters." << std::endl;
      }
      break;
    case OPT::REALM_SET:
      {
	if (realm_id.empty() && realm_name.empty()) {
	  cerr << "no realm name or id provided" << std::endl;
	  return EINVAL;
	}
	RGWRealm realm(realm_id, realm_name);
	bool new_realm = false;
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0 && ret != -ENOENT) {
	  cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	} else if (ret == -ENOENT) {
	  new_realm = true;
	}
	ret = read_decode_json(infile, realm);
	if (ret < 0) {
	  return 1;
	}
	if (!realm_name.empty() && realm.get_name() != realm_name) {
	  cerr << "mismatch between --rgw-realm " << realm_name << " and json input file name " <<
	    realm.get_name() << std::endl;
	  return EINVAL;
	}
	/* new realm */
	if (new_realm) {
	  cout << "clearing period and epoch for new realm" << std::endl;
	  realm.clear_current_period_and_epoch();
	  ret = realm.create(dpp(), null_yield);
	  if (ret < 0) {
	    cerr << "ERROR: couldn't create new realm: " << cpp_strerror(-ret) << std::endl;
	    return 1;
	  }
	} else {
	  ret = realm.update(dpp(), null_yield);
	  if (ret < 0) {
	    cerr << "ERROR: couldn't store realm info: " << cpp_strerror(-ret) << std::endl;
	    return 1;
	  }
	}

        if (set_default) {
          ret = realm.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }
	encode_json("realm", realm, formatter.get());
	formatter->flush(cout);
      }
      break;

    case OPT::REALM_DEFAULT:
      {
	RGWRealm realm(realm_id, realm_name);
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = realm.set_as_default(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to set realm as default: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
      }
      break;
    case OPT::REALM_PULL:
      {
        if (url.empty()) {
          cerr << "A --url must be provided." << std::endl;
          return EINVAL;
        }
        RGWEnv env;
        req_info info(g_ceph_context, &env);
        info.method = "GET";
        info.request_uri = "/admin/realm";

        map<string, string> &params = info.args.get_params();
        if (!realm_id.empty())
          params["id"] = realm_id;
        if (!realm_name.empty())
          params["name"] = realm_name;

        bufferlist bl;
        JSONParser p;
        int ret = send_to_url(url, access_key, secret_key, info, bl, p);
        if (ret < 0) {
          cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
          if (ret == -EACCES) {
            cerr << "If the realm has been changed on the master zone, the "
                "master zone's gateway may need to be restarted to recognize "
                "this user." << std::endl;
          }
          return -ret;
        }
        RGWRealm realm;
        realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield, false);
        try {
          decode_json_obj(realm, &p);
        } catch (const JSONDecoder::err& e) {
          cerr << "failed to decode JSON response: " << e.what() << std::endl;
          return EINVAL;
        }
        RGWPeriod period;
        auto& current_period = realm.get_current_period();
        if (!current_period.empty()) {
          // pull the latest epoch of the realm's current period
          ret = do_period_pull(nullptr, url, access_key, secret_key,
                               realm_id, realm_name, current_period, "",
                               &period);
          if (ret < 0) {
            cerr << "could not fetch period " << current_period << std::endl;
            return -ret;
          }
        }
        ret = realm.create(dpp(), null_yield, false);
        if (ret < 0 && ret != -EEXIST) {
          cerr << "Error storing realm " << realm.get_id() << ": "
            << cpp_strerror(ret) << std::endl;
          return -ret;
        } else if (ret ==-EEXIST) {
	  ret = realm.update(dpp(), null_yield);
	  if (ret < 0) {
	    cerr << "Error storing realm " << realm.get_id() << ": "
		 << cpp_strerror(ret) << std::endl;
	  }
	}

        if (set_default) {
          ret = realm.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

        encode_json("realm", realm, formatter.get());
        formatter->flush(cout);
      }
      break;

    case OPT::ZONEGROUP_ADD:
      {
	if (zonegroup_id.empty() && zonegroup_name.empty()) {
	  cerr << "no zonegroup name or id provided" << std::endl;
	  return EINVAL;
	}

	RGWZoneGroup zonegroup(zonegroup_id,zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to initialize zonegroup " << zonegroup_name << " id " << zonegroup_id << " :"
	       << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	RGWZoneParams zone(zone_id, zone_name);
	ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
        if (zone.realm_id != zonegroup.realm_id) {
          zone.realm_id = zonegroup.realm_id;
          ret = zone.update(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
            return -ret;
          }
        }

        string *ptier_type = (tier_type_specified ? &tier_type : nullptr);

        for (auto a : tier_config_add) {
          int r = zone.tier_config.set(a.first, a.second);
          if (r < 0) {
            cerr << "ERROR: failed to set configurable: " << a << std::endl;
            return EINVAL;
          }
        }

        bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
        string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr);

        ret = zonegroup.add_zone(dpp(), zone,
                                 (is_master_set ? &is_master : NULL),
                                 (is_read_only_set ? &read_only : NULL),
                                 endpoints, ptier_type,
                                 psync_from_all, sync_from, sync_from_rm,
                                 predirect_zone, bucket_index_max_shards,
				 store->svc()->sync_modules->get_manager(),
				 null_yield);
	if (ret < 0) {
	  cerr << "failed to add zone " << zone_name << " to zonegroup " << zonegroup.get_name() << ": "
	       << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        encode_json("zonegroup", zonegroup, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_CREATE:
      {
	if (zonegroup_name.empty()) {
	  cerr << "Missing zonegroup name" << std::endl;
	  return EINVAL;
	}
	RGWRealm realm(realm_id, realm_name);
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	RGWZoneGroup zonegroup(zonegroup_name, is_master, g_ceph_context, store->svc()->sysobj, realm.get_id(), endpoints);
        zonegroup.api_name = (api_name.empty() ? zonegroup_name : api_name);
	ret = zonegroup.create(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to create zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        if (set_default) {
          ret = zonegroup.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

	encode_json("zonegroup", zonegroup, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_DEFAULT:
      {
	if (zonegroup_id.empty() && zonegroup_name.empty()) {
	  cerr << "no zonegroup name or id provided" << std::endl;
	  return EINVAL;
	}

	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	ret = zonegroup.set_as_default(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to set zonegroup as default: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
      }
      break;
    case OPT::ZONEGROUP_DELETE:
      {
	if (zonegroup_id.empty() && zonegroup_name.empty()) {
	  cerr << "no zonegroup name or id provided" << std::endl;
	  return EINVAL;
	}
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj,
				 null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = zonegroup.delete_obj(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "ERROR: couldn't delete zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
      }
      break;
    case OPT::ZONEGROUP_GET:
      {
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	encode_json("zonegroup", zonegroup, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_LIST:
      {
	RGWZoneGroup zonegroup;
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj,
				 null_yield, false);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	list<string> zonegroups;
	ret = store->svc()->zone->list_zonegroups(dpp(), zonegroups);
	if (ret < 0) {
	  cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	string default_zonegroup;
	ret = zonegroup.read_default_id(dpp(), default_zonegroup, null_yield);
	if (ret < 0 && ret != -ENOENT) {
	  cerr << "could not determine default zonegroup: " << cpp_strerror(-ret) << std::endl;
	}
	formatter->open_object_section("zonegroups_list");
	encode_json("default_info", default_zonegroup, formatter.get());
	encode_json("zonegroups", zonegroups, formatter.get());
	formatter->close_section();
	formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_MODIFY:
      {
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        bool need_update = false;

        if (!master_zone.empty()) {
          zonegroup.master_zone = master_zone;
          need_update = true;
        }

	if (is_master_set) {
	  zonegroup.update_master(dpp(), is_master, null_yield);
          need_update = true;
        }

        if (!endpoints.empty()) {
          zonegroup.endpoints = endpoints;
          need_update = true;
        }

        if (!api_name.empty()) {
          zonegroup.api_name = api_name;
          need_update = true;
        }

        if (!realm_id.empty()) {
          zonegroup.realm_id = realm_id;
          need_update = true;
        } else if (!realm_name.empty()) {
          // get realm id from name
          RGWRealm realm{g_ceph_context, store->svc()->sysobj};
          ret = realm.read_id(dpp(), realm_name, zonegroup.realm_id, null_yield);
          if (ret < 0) {
            cerr << "failed to find realm by name " << realm_name << std::endl;
            return -ret;
          }
          need_update = true;
        }

        if (bucket_index_max_shards) {
          for (auto& [name, zone] : zonegroup.zones) {
            zone.bucket_index_max_shards = *bucket_index_max_shards;
          }
          need_update = true;
        }

        if (need_update) {
	  ret = zonegroup.update(dpp(), null_yield);
	  if (ret < 0) {
	    cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
	    return -ret;
	  }
	}

        if (set_default) {
          ret = zonegroup.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

        encode_json("zonegroup", zonegroup, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_SET:
      {
	RGWRealm realm(realm_id, realm_name);
	int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	bool default_realm_not_exist = (ret == -ENOENT && realm_id.empty() && realm_name.empty());

	if (ret < 0 && !default_realm_not_exist ) {
	  cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	RGWZoneGroup zonegroup;
	ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj,
			     null_yield, false);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = read_decode_json(infile, zonegroup);
	if (ret < 0) {
	  return 1;
	}
	if (zonegroup.realm_id.empty() && !default_realm_not_exist) {
	  zonegroup.realm_id = realm.get_id();
	}
	ret = zonegroup.create(dpp(), null_yield);
	if (ret < 0 && ret != -EEXIST) {
	  cerr << "ERROR: couldn't create zonegroup info: " << cpp_strerror(-ret) << std::endl;
	  return 1;
	} else if (ret == -EEXIST) {
	  ret = zonegroup.update(dpp(), null_yield);
	  if (ret < 0) {
	    cerr << "ERROR: couldn't store zonegroup info: " << cpp_strerror(-ret) << std::endl;
	    return 1;
	  }
	}

        if (set_default) {
          ret = zonegroup.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

	encode_json("zonegroup", zonegroup, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_REMOVE:
      {
        RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
        int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
        if (ret < 0) {
          cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        if (zone_id.empty()) {
          if (zone_name.empty()) {
            cerr << "no --zone-id or --rgw-zone name provided" << std::endl;
            return EINVAL;
          }
          // look up zone id by name
          for (auto& z : zonegroup.zones) {
            if (zone_name == z.second.name) {
              zone_id = z.second.id;
              break;
            }
          }
          if (zone_id.empty()) {
            cerr << "zone name " << zone_name << " not found in zonegroup "
                << zonegroup.get_name() << std::endl;
            return ENOENT;
          }
        }

        ret = zonegroup.remove_zone(dpp(), zone_id, null_yield);
        if (ret < 0) {
          cerr << "failed to remove zone: " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        encode_json("zonegroup", zonegroup, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_RENAME:
      {
	if (zonegroup_new_name.empty()) {
	  cerr << " missing zonegroup new name" << std::endl;
	  return EINVAL;
	}
	if (zonegroup_id.empty() && zonegroup_name.empty()) {
	  cerr << "no zonegroup name or id provided" << std::endl;
	  return EINVAL;
	}
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = zonegroup.rename(dpp(), zonegroup_new_name, null_yield);
	if (ret < 0) {
	  cerr << "failed to rename zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
      }
      break;
    case OPT::ZONEGROUP_PLACEMENT_LIST:
      {
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj,
				 null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	encode_json("placement_targets", zonegroup.placement_targets, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_PLACEMENT_GET:
      {
	if (placement_id.empty()) {
	  cerr << "ERROR: --placement-id not specified" << std::endl;
	  return EINVAL;
	}

	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	auto p = zonegroup.placement_targets.find(placement_id);
	if (p == zonegroup.placement_targets.end()) {
	  cerr << "failed to find a zonegroup placement target named '" << placement_id << "'" << std::endl;
	  return -ENOENT;
	}
	encode_json("placement_targets", p->second, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONEGROUP_PLACEMENT_ADD:
    case OPT::ZONEGROUP_PLACEMENT_MODIFY:
    case OPT::ZONEGROUP_PLACEMENT_RM:
    case OPT::ZONEGROUP_PLACEMENT_DEFAULT:
      {
        if (placement_id.empty()) {
          cerr << "ERROR: --placement-id not specified" << std::endl;
          return EINVAL;
        }

        rgw_placement_rule rule;
        rule.from_str(placement_id);

        if (!rule.storage_class.empty() && opt_storage_class &&
            rule.storage_class != *opt_storage_class) {
          cerr << "ERROR: provided contradicting storage class configuration" << std::endl;
          return EINVAL;
        } else if (rule.storage_class.empty()) {
          rule.storage_class = opt_storage_class.value_or(string());
        }

	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_ADD ||
            opt_cmd == OPT::ZONEGROUP_PLACEMENT_MODIFY) {
          RGWZoneGroupPlacementTarget& target = zonegroup.placement_targets[placement_id];
          if (!tags.empty()) {
            target.tags.clear();
            for (auto& t : tags) {
              target.tags.insert(t);
            }
          }
          target.name = placement_id;
          for (auto& t : tags_rm) {
            target.tags.erase(t);
          }
          for (auto& t : tags_add) {
            target.tags.insert(t);
          }
          target.storage_classes.insert(rule.get_storage_class());
        } else if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_RM) {
          if (!opt_storage_class ||
              opt_storage_class->empty()) {
            zonegroup.placement_targets.erase(placement_id);
          } else {
            auto iter = zonegroup.placement_targets.find(placement_id);
            if (iter != zonegroup.placement_targets.end()) {
              RGWZoneGroupPlacementTarget& info = zonegroup.placement_targets[placement_id];
              info.storage_classes.erase(*opt_storage_class);
            }
          }
        } else if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_DEFAULT) {
          if (!zonegroup.placement_targets.count(placement_id)) {
            cerr << "failed to find a zonegroup placement target named '"
                << placement_id << "'" << std::endl;
            return -ENOENT;
          }
          zonegroup.default_placement = rule;
        }

        zonegroup.post_process_params(dpp(), null_yield);
        ret = zonegroup.update(dpp(), null_yield);
        if (ret < 0) {
          cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        encode_json("placement_targets", zonegroup.placement_targets, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::ZONE_CREATE:
      {
        if (zone_name.empty()) {
	  cerr << "zone name not provided" << std::endl;
	  return EINVAL;
        }
	int ret;
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	/* if the user didn't provide zonegroup info , create stand alone zone */
	if (!zonegroup_id.empty() || !zonegroup_name.empty()) {
	  ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	  if (ret < 0) {
	    cerr << "unable to initialize zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl;
	    return -ret;
	  }
	  if (realm_id.empty() && realm_name.empty()) {
	    realm_id = zonegroup.realm_id;
	  }
	}

	RGWZoneParams zone(zone_id, zone_name);
	ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield, false);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        zone.system_key.id = access_key;
        zone.system_key.key = secret_key;
	zone.realm_id = realm_id;
        for (auto a : tier_config_add) {
          int r = zone.tier_config.set(a.first, a.second);
          if (r < 0) {
            cerr << "ERROR: failed to set configurable: " << a << std::endl;
            return EINVAL;
          }
        }

	ret = zone.create(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to create zone " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	if (!zonegroup_id.empty() || !zonegroup_name.empty()) {
          string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
          bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
          string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr);
	  ret = zonegroup.add_zone(dpp(), zone,
                                   (is_master_set ? &is_master : NULL),
                                   (is_read_only_set ? &read_only : NULL),
                                   endpoints,
                                   ptier_type,
                                   psync_from_all,
                                   sync_from, sync_from_rm,
                                   predirect_zone, bucket_index_max_shards,
				   store->svc()->sync_modules->get_manager(),
				   null_yield);
	  if (ret < 0) {
	    cerr << "failed to add zone " << zone_name << " to zonegroup " << zonegroup.get_name()
		 << ": " << cpp_strerror(-ret) << std::endl;
	    return -ret;
	  }
	}

        if (set_default) {
          ret = zone.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

	encode_json("zone", zone, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONE_DEFAULT:
      {
	RGWZoneGroup zonegroup(zonegroup_id,zonegroup_name);
	int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "WARNING: failed to initialize zonegroup " << zonegroup_name << std::endl;
	}
	if (zone_id.empty() && zone_name.empty()) {
	  cerr << "no zone name or id provided" << std::endl;
	  return EINVAL;
	}
	RGWZoneParams zone(zone_id, zone_name);
	ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = zone.set_as_default(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to set zone as default: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
      }
      break;
    case OPT::ZONE_DELETE:
      {
	if (zone_id.empty() && zone_name.empty()) {
	  cerr << "no zone name or id provided" << std::endl;
	  return EINVAL;
	}
	RGWZoneParams zone(zone_id, zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        list<string> zonegroups;
	ret = store->svc()->zone->list_zonegroups(dpp(), zonegroups);
	if (ret < 0) {
	  cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        for (list<string>::iterator iter = zonegroups.begin(); iter != zonegroups.end(); ++iter) {
          RGWZoneGroup zonegroup(string(), *iter);
          int ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
          if (ret < 0) {
            cerr << "WARNING: failed to initialize zonegroup " << zonegroup_name << std::endl;
            continue;
          }
          ret = zonegroup.remove_zone(dpp(), zone.get_id(), null_yield);
          if (ret < 0 && ret != -ENOENT) {
            cerr << "failed to remove zone " << zone_name << " from zonegroup " << zonegroup.get_name() << ": "
              << cpp_strerror(-ret) << std::endl;
          }
        }

	ret = zone.delete_obj(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to delete zone " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
      }
      break;
    case OPT::ZONE_GET:
      {
	RGWZoneParams zone(zone_id, zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	encode_json("zone", zone, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONE_SET:
      {
	RGWZoneParams zone(zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield,
			    false);
	if (ret < 0) {
	  return -ret;
	}

        ret = zone.read(dpp(), null_yield);
        if (ret < 0 && ret != -ENOENT) {
	  cerr << "zone.read() returned ret=" << ret << std::endl;
          return -ret;
        }

        string orig_id = zone.get_id();

	ret = read_decode_json(infile, zone);
	if (ret < 0) {
	  return 1;
	}

	if(zone.realm_id.empty()) {
	  RGWRealm realm(realm_id, realm_name);
	  int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	  if (ret < 0 && ret != -ENOENT) {
	    cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
	    return -ret;
	  }
	  zone.realm_id = realm.get_id();
	}

	if( !zone_name.empty() && !zone.get_name().empty() && zone.get_name() != zone_name) {
	  cerr << "Error: zone name" << zone_name << " is different than the zone name " << zone.get_name() << " in the provided json " << std::endl;
	  return EINVAL;
	}

        if (zone.get_name().empty()) {
          zone.set_name(zone_name);
          if (zone.get_name().empty()) {
            cerr << "no zone name specified" << std::endl;
            return EINVAL;
          }
        }

        zone_name = zone.get_name();

        if (zone.get_id().empty()) {
          zone.set_id(orig_id);
        }

	if (zone.get_id().empty()) {
	  cerr << "no zone name id the json provided, assuming old format" << std::endl;
	  if (zone_name.empty()) {
	    cerr << "missing zone name"  << std::endl;
	    return EINVAL;
	  }
	  zone.set_name(zone_name);
	  zone.set_id(zone_name);
	}

	cerr << "zone id " << zone.get_id();
	ret = zone.fix_pool_names(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "ERROR: couldn't fix zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = zone.write(dpp(), false, null_yield);
	if (ret < 0) {
	  cerr << "ERROR: couldn't create zone: " << cpp_strerror(-ret) << std::endl;
	  return 1;
	}

        if (set_default) {
          ret = zone.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

	encode_json("zone", zone, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONE_LIST:
      {
	list<string> zones;
	int ret = store->svc()->zone->list_zones(dpp(), zones);
	if (ret < 0) {
	  cerr << "failed to list zones: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	RGWZoneParams zone;
	ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield, false);
	if (ret < 0) {
	  cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	string default_zone;
	ret = zone.read_default_id(dpp(), default_zone, null_yield);
	if (ret < 0 && ret != -ENOENT) {
	  cerr << "could not determine default zone: " << cpp_strerror(-ret) << std::endl;
	}
	formatter->open_object_section("zones_list");
	encode_json("default_info", default_zone, formatter.get());
	encode_json("zones", zones, formatter.get());
	formatter->close_section();
	formatter->flush(cout);
      }
      break;
    case OPT::ZONE_MODIFY:
      {
	RGWZoneParams zone(zone_id, zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
        if (ret < 0) {
	  cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        bool need_zone_update = false;
        if (!access_key.empty()) {
          zone.system_key.id = access_key;
          need_zone_update = true;
        }

        if (!secret_key.empty()) {
          zone.system_key.key = secret_key;
          need_zone_update = true;
        }

        if (!realm_id.empty()) {
          zone.realm_id = realm_id;
          need_zone_update = true;
        } else if (!realm_name.empty()) {
          // get realm id from name
          RGWRealm realm{g_ceph_context, store->svc()->sysobj};
          ret = realm.read_id(dpp(), realm_name, zone.realm_id, null_yield);
          if (ret < 0) {
            cerr << "failed to find realm by name " << realm_name << std::endl;
            return -ret;
          }
          need_zone_update = true;
        }

        if (tier_config_add.size() > 0) {
          for (auto add : tier_config_add) {
            int r = zone.tier_config.set(add.first, add.second);
            if (r < 0) {
              cerr << "ERROR: failed to set configurable: " << add << std::endl;
              return EINVAL;
            }
          }
          need_zone_update = true;
        }

        for (auto rm : tier_config_rm) {
          if (!rm.first.empty()) { /* otherwise will remove the entire config */
            zone.tier_config.erase(rm.first);
            need_zone_update = true;
          }
        }

        if (need_zone_update) {
          ret = zone.update(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
            return -ret;
          }
        }

	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
        string *ptier_type = (tier_type_specified ? &tier_type : nullptr);

        bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
        string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr);

        ret = zonegroup.add_zone(dpp(), zone,
                                 (is_master_set ? &is_master : NULL),
                                 (is_read_only_set ? &read_only : NULL),
                                 endpoints, ptier_type,
                                 psync_from_all, sync_from, sync_from_rm,
                                 predirect_zone, bucket_index_max_shards,
				 store->svc()->sync_modules->get_manager(),
				 null_yield);
	if (ret < 0) {
	  cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

	ret = zonegroup.update(dpp(), null_yield);
	if (ret < 0) {
	  cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        if (set_default) {
          ret = zone.set_as_default(dpp(), null_yield);
          if (ret < 0) {
            cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
          }
        }

        encode_json("zone", zone, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::ZONE_RENAME:
      {
	if (zone_new_name.empty()) {
	  cerr << " missing zone new name" << std::endl;
	  return EINVAL;
	}
	if (zone_id.empty() && zone_name.empty()) {
	  cerr << "no zone name or id provided" << std::endl;
	  return EINVAL;
	}
	RGWZoneParams zone(zone_id,zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	ret = zone.rename(dpp(), zone_new_name, null_yield);
	if (ret < 0) {
	  cerr << "failed to rename zone " << zone_name << " to " << zone_new_name << ": " << cpp_strerror(-ret)
	       << std::endl;
	  return -ret;
	}
	RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "WARNING: failed to initialize zonegroup " << zonegroup_name << std::endl;
	} else {
	  ret = zonegroup.rename_zone(dpp(), zone, null_yield);
	  if (ret < 0) {
	    cerr << "Error in zonegroup rename for " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
	    return -ret;
	  }
	}
      }
      break;
    case OPT::ZONE_PLACEMENT_ADD:
    case OPT::ZONE_PLACEMENT_MODIFY:
    case OPT::ZONE_PLACEMENT_RM:
      {
        if (placement_id.empty()) {
          cerr << "ERROR: --placement-id not specified" << std::endl;
          return EINVAL;
        }
        // validate compression type
        if (compression_type && *compression_type != "random"
            && !Compressor::get_comp_alg_type(*compression_type)) {
          std::cerr << "Unrecognized compression type" << std::endl;
          return EINVAL;
        }

	RGWZoneParams zone(zone_id, zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
        if (ret < 0) {
	  cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}

        if (opt_cmd == OPT::ZONE_PLACEMENT_ADD ||
	    opt_cmd == OPT::ZONE_PLACEMENT_MODIFY) {
	  RGWZoneGroup zonegroup(zonegroup_id, zonegroup_name);
	  ret = zonegroup.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	  if (ret < 0) {
	    cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
	    return -ret;
	  }

	  auto ptiter = zonegroup.placement_targets.find(placement_id);
	  if (ptiter == zonegroup.placement_targets.end()) {
	    cerr << "ERROR: placement id '" << placement_id << "' is not configured in zonegroup placement targets" << std::endl;
	    return EINVAL;
	  }

	  string storage_class = rgw_placement_rule::get_canonical_storage_class(opt_storage_class.value_or(string()));
	  if (ptiter->second.storage_classes.find(storage_class) == ptiter->second.storage_classes.end()) {
	    cerr << "ERROR: storage class '" << storage_class << "' is not defined in zonegroup '" << placement_id << "' placement target" << std::endl;
	    return EINVAL;
	  }

          RGWZonePlacementInfo& info = zone.placement_pools[placement_id];

	  string opt_index_pool = index_pool.value_or(string());
	  string opt_data_pool = data_pool.value_or(string());

	  if (!opt_index_pool.empty()) {
	    info.index_pool = opt_index_pool;
	  }

	  if (info.index_pool.empty()) {
            cerr << "ERROR: index pool not configured, need to specify --index-pool" << std::endl;
            return EINVAL;
	  }

	  if (opt_data_pool.empty()) {
	    const RGWZoneStorageClass *porig_sc{nullptr};
	    if (info.storage_classes.find(storage_class, &porig_sc)) {
	      if (porig_sc->data_pool) {
		opt_data_pool = porig_sc->data_pool->to_str();
	      }
	    }
	    if (opt_data_pool.empty()) {
	      cerr << "ERROR: data pool not configured, need to specify --data-pool" << std::endl;
	      return EINVAL;
	    }
	  }

          rgw_pool dp = opt_data_pool;
          info.storage_classes.set_storage_class(storage_class, &dp, compression_type.get_ptr());

          if (data_extra_pool) {
            info.data_extra_pool = *data_extra_pool;
          }
          if (index_type_specified) {
	    info.index_type = placement_index_type;
          }

          ret = check_pool_support_omap(info.get_data_extra_pool());
          if (ret < 0) {
             cerr << "ERROR: the data extra (non-ec) pool '" << info.get_data_extra_pool() 
                 << "' does not support omap" << std::endl;
             return ret;
          }
        } else if (opt_cmd == OPT::ZONE_PLACEMENT_RM) {
          if (!opt_storage_class ||
              opt_storage_class->empty()) {
            zone.placement_pools.erase(placement_id);
          } else {
            auto iter = zone.placement_pools.find(placement_id);
            if (iter != zone.placement_pools.end()) {
              RGWZonePlacementInfo& info = zone.placement_pools[placement_id];
              info.storage_classes.remove_storage_class(*opt_storage_class);
            }
          }
        }

        ret = zone.update(dpp(), null_yield);
        if (ret < 0) {
          cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        encode_json("zone", zone, formatter.get());
        formatter->flush(cout);
      }
      break;
    case OPT::ZONE_PLACEMENT_LIST:
      {
	RGWZoneParams zone(zone_id, zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	encode_json("placement_pools", zone.placement_pools, formatter.get());
	formatter->flush(cout);
      }
      break;
    case OPT::ZONE_PLACEMENT_GET:
      {
	if (placement_id.empty()) {
	  cerr << "ERROR: --placement-id not specified" << std::endl;
	  return EINVAL;
	}

	RGWZoneParams zone(zone_id, zone_name);
	int ret = zone.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
	if (ret < 0) {
	  cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
	  return -ret;
	}
	auto p = zone.placement_pools.find(placement_id);
	if (p == zone.placement_pools.end()) {
	  cerr << "ERROR: zone placement target '" << placement_id << "' not found" << std::endl;
	  return -ENOENT;
	}
	encode_json("placement_pools", p->second, formatter.get());
	formatter->flush(cout);
      }
    default:
      break;
    }
    return 0;
  }

  resolve_zone_id_opt(opt_effective_zone_name, opt_effective_zone_id);
  resolve_zone_id_opt(opt_source_zone_name, opt_source_zone_id);
  resolve_zone_id_opt(opt_dest_zone_name, opt_dest_zone_id);
  resolve_zone_ids_opt(opt_zone_names, opt_zone_ids);
  resolve_zone_ids_opt(opt_source_zone_names, opt_source_zone_ids);
  resolve_zone_ids_opt(opt_dest_zone_names, opt_dest_zone_ids);

  bool non_master_cmd = (!store->svc()->zone->is_meta_master() && !yes_i_really_mean_it);
  std::set<OPT> non_master_ops_list = {OPT::USER_CREATE, OPT::USER_RM, 
                                        OPT::USER_MODIFY, OPT::USER_ENABLE,
                                        OPT::USER_SUSPEND, OPT::SUBUSER_CREATE,
                                        OPT::SUBUSER_MODIFY, OPT::SUBUSER_RM,
                                        OPT::BUCKET_LINK, OPT::BUCKET_UNLINK,
                                        OPT::BUCKET_RESHARD, OPT::BUCKET_RM,
                                        OPT::BUCKET_CHOWN, OPT::METADATA_PUT,
                                        OPT::METADATA_RM, OPT::RESHARD_CANCEL,
                                        OPT::RESHARD_ADD, OPT::MFA_CREATE,
                                        OPT::MFA_REMOVE, OPT::MFA_RESYNC,
                                        OPT::CAPS_ADD, OPT::CAPS_RM};

  bool print_warning_message = (non_master_ops_list.find(opt_cmd) != non_master_ops_list.end() &&
                                non_master_cmd);

  if (print_warning_message) {
      cerr << "Please run the command on master zone. Performing this operation on non-master zone leads to inconsistent metadata between zones" << std::endl;
      cerr << "Are you sure you want to go ahead? (requires --yes-i-really-mean-it)" << std::endl;
      return EINVAL;
  }

  if (!user_id.empty()) {
    user_op.set_user_id(user_id);
    bucket_op.set_user_id(user_id);
  }

  if (!display_name.empty())
    user_op.set_display_name(display_name);

  if (!user_email.empty())
    user_op.set_user_email(user_email);

  if (!user_id.empty()) {
    user_op.set_new_user_id(new_user_id);
  }

  if (!access_key.empty())
    user_op.set_access_key(access_key);

  if (!secret_key.empty())
    user_op.set_secret_key(secret_key);

  if (!subuser.empty())
    user_op.set_subuser(subuser);

  if (!caps.empty())
    user_op.set_caps(caps);

  user_op.set_purge_data(purge_data);

  if (purge_keys)
    user_op.set_purge_keys();

  if (gen_access_key)
    user_op.set_generate_key();

  if (gen_secret_key)
    user_op.set_gen_secret(); // assume that a key pair should be created

  if (max_buckets_specified)
    user_op.set_max_buckets(max_buckets);

  if (admin_specified)
     user_op.set_admin(admin);

  if (system_specified)
    user_op.set_system(system);

  if (set_perm)
    user_op.set_perm(perm_mask);

  if (set_temp_url_key) {
    map<int, string>::iterator iter = temp_url_keys.begin();
    for (; iter != temp_url_keys.end(); ++iter) {
      user_op.set_temp_url_key(iter->second, iter->first);
    }
  }

  if (!op_mask_str.empty()) {
    uint32_t op_mask;
    int ret = rgw_parse_op_type_list(op_mask_str, &op_mask);
    if (ret < 0) {
      cerr << "failed to parse op_mask: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    user_op.set_op_mask(op_mask);
  }

  if (key_type != KEY_TYPE_UNDEFINED)
    user_op.set_key_type(key_type);

  // set suspension operation parameters
  if (opt_cmd == OPT::USER_ENABLE)
    user_op.set_suspension(false);
  else if (opt_cmd == OPT::USER_SUSPEND)
    user_op.set_suspension(true);

  if (!placement_id.empty() ||
      (opt_storage_class && !opt_storage_class->empty())) {
    rgw_placement_rule target_rule;
    target_rule.name = placement_id;
    target_rule.storage_class = *opt_storage_class;
    if (!store->svc()->zone->get_zone_params().valid_placement(target_rule)) {
      cerr << "NOTICE: invalid dest placement: " << target_rule.to_str() << std::endl;
      return EINVAL;
    }
    user_op.set_default_placement(target_rule);
  }

  if (!tags.empty()) {
    user_op.set_placement_tags(tags);
  }

  // RGWUser to use for user operations
  RGWUser user;
  int ret = 0;
  if (!(user_id.empty() && access_key.empty()) || !subuser.empty()) {
    ret = user.init(dpp(), store, user_op, null_yield);
    if (ret < 0) {
      cerr << "user.init failed: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  /* populate bucket operation */
  bucket_op.set_bucket_name(bucket_name);
  bucket_op.set_object(object);
  bucket_op.set_check_objects(check_objects);
  bucket_op.set_delete_children(delete_child_objects);
  bucket_op.set_fix_index(fix);
  bucket_op.set_max_aio(max_concurrent_ios);

  // required to gather errors from operations
  std::string err_msg;

  bool output_user_info = true;

  switch (opt_cmd) {
  case OPT::USER_INFO:
    if (user_id.empty() && access_key.empty()) {
      cerr << "ERROR: --uid or --access-key required" << std::endl;
      return EINVAL;
    }
    break;
  case OPT::USER_CREATE:
    if (!user_op.has_existing_user()) {
      user_op.set_generate_key(); // generate a new key by default
    }
    ret = user.add(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not create user: " << err_msg << std::endl;
      if (ret == -ERR_INVALID_TENANT_NAME)
	ret = -EINVAL;

      return -ret;
    }
    if (!subuser.empty()) {
      ret = user.subusers.add(dpp(), user_op, null_yield, &err_msg);
      if (ret < 0) {
        cerr << "could not create subuser: " << err_msg << std::endl;
        return -ret;
      }
    }
    break;
  case OPT::USER_RM:
    ret = user.remove(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not remove user: " << err_msg << std::endl;
      return -ret;
    }

    output_user_info = false;
    break;
  case OPT::USER_RENAME:
    if (yes_i_really_mean_it) {
      user_op.set_overwrite_new_user(true);
    }
    ret = user.rename(user_op, null_yield, dpp(), &err_msg);
    if (ret < 0) {
      if (ret == -EEXIST) {
        err_msg += ". to overwrite this user, add --yes-i-really-mean-it";
      }
      cerr << "could not rename user: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::USER_ENABLE:
  case OPT::USER_SUSPEND:
  case OPT::USER_MODIFY:
    ret = user.modify(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not modify user: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::SUBUSER_CREATE:
    ret = user.subusers.add(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not create subuser: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::SUBUSER_MODIFY:
    ret = user.subusers.modify(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not modify subuser: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::SUBUSER_RM:
    ret = user.subusers.remove(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not remove subuser: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::CAPS_ADD:
    ret = user.caps.add(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not add caps: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::CAPS_RM:
    ret = user.caps.remove(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not remove caps: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::KEY_CREATE:
    ret = user.keys.add(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not create key: " << err_msg << std::endl;
      return -ret;
    }

    break;
  case OPT::KEY_RM:
    ret = user.keys.remove(dpp(), user_op, null_yield, &err_msg);
    if (ret < 0) {
      cerr << "could not remove key: " << err_msg << std::endl;
      return -ret;
    }
    break;
  case OPT::PERIOD_PUSH:
    {
      RGWEnv env;
      req_info info(g_ceph_context, &env);
      info.method = "POST";
      info.request_uri = "/admin/realm/period";

      map<string, string> &params = info.args.get_params();
      if (!realm_id.empty())
        params["realm_id"] = realm_id;
      if (!realm_name.empty())
        params["realm_name"] = realm_name;
      if (!period_id.empty())
        params["period_id"] = period_id;
      if (!period_epoch.empty())
        params["epoch"] = period_epoch;

      // load the period
      RGWPeriod period(period_id);
      int ret = period.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
      if (ret < 0) {
        cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      // json format into a bufferlist
      JSONFormatter jf(false);
      encode_json("period", period, &jf);
      bufferlist bl;
      jf.flush(bl);

      JSONParser p;
      ret = send_to_remote_or_url(nullptr, url, access_key, secret_key,
                                  info, bl, p);
      if (ret < 0) {
        cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
    }
    return 0;
  case OPT::PERIOD_UPDATE:
    {
      int ret = update_period(realm_id, realm_name, period_id, period_epoch,
                              commit, remote, url, access_key, secret_key,
                              formatter.get(), yes_i_really_mean_it);
      if (ret < 0) {
	return -ret;
      }
    }
    return 0;
  case OPT::PERIOD_COMMIT:
    {
      // read realm and staging period
      RGWRealm realm(realm_id, realm_name);
      int ret = realm.init(dpp(), g_ceph_context, store->svc()->sysobj, null_yield);
      if (ret < 0) {
        cerr << "Error initializing realm: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      RGWPeriod period(RGWPeriod::get_staging_id(realm.get_id()), 1);
      ret = period.init(dpp(), g_ceph_context, store->svc()->sysobj, realm.get_id(), null_yield);
      if (ret < 0) {
        cerr << "period init failed: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      ret = commit_period(realm, period, remote, url, access_key, secret_key,
                          yes_i_really_mean_it);
      if (ret < 0) {
        cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }

      encode_json("period", period, formatter.get());
      formatter->flush(cout);
    }
    return 0;
  case OPT::ROLE_CREATE:
    {
      if (role_name.empty()) {
        cerr << "ERROR: role name is empty" << std::endl;
        return -EINVAL;
      }

      if (assume_role_doc.empty()) {
        cerr << "ERROR: assume role policy document is empty" << std::endl;
        return -EINVAL;
      }
      bufferlist bl = bufferlist::static_from_string(assume_role_doc);
      try {
        const rgw::IAM::Policy p(g_ceph_context, tenant, bl);
      } catch (rgw::IAM::PolicyParseException& e) {
        cerr << "failed to parse policy: " << e.what() << std::endl;
        return -EINVAL;
      }
      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, path, assume_role_doc, tenant);
      ret = role.create(dpp(), true, null_yield);
      if (ret < 0) {
        return -ret;
      }
      show_role_info(role, formatter.get());
      return 0;
    }
  case OPT::ROLE_DELETE:
    {
      if (role_name.empty()) {
        cerr << "ERROR: empty role name" << std::endl;
        return -EINVAL;
      }
      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      ret = role.delete_obj(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      cout << "role: " << role_name << " successfully deleted" << std::endl;
      return 0;
    }
  case OPT::ROLE_GET:
    {
      if (role_name.empty()) {
        cerr << "ERROR: empty role name" << std::endl;
        return -EINVAL;
      }
      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      ret = role.get(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      show_role_info(role, formatter.get());
      return 0;
    }
  case OPT::ROLE_MODIFY:
    {
      if (role_name.empty()) {
        cerr << "ERROR: role name is empty" << std::endl;
        return -EINVAL;
      }

      if (assume_role_doc.empty()) {
        cerr << "ERROR: assume role policy document is empty" << std::endl;
        return -EINVAL;
      }

      bufferlist bl = bufferlist::static_from_string(assume_role_doc);
      try {
        const rgw::IAM::Policy p(g_ceph_context, tenant, bl);
      } catch (rgw::IAM::PolicyParseException& e) {
        cerr << "failed to parse policy: " << e.what() << std::endl;
        return -EINVAL;
      }

      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      ret = role.get(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      role.update_trust_policy(assume_role_doc);
      ret = role.update(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      cout << "Assume role policy document updated successfully for role: " << role_name << std::endl;
      return 0;
    }
  case OPT::ROLE_LIST:
    {
      vector<RGWRole> result;
      ret = RGWRole::get_roles_by_path_prefix(dpp(), store->getRados(), g_ceph_context, path_prefix, tenant, result, null_yield);
      if (ret < 0) {
        return -ret;
      }
      show_roles_info(result, formatter.get());
      return 0;
    }
  case OPT::ROLE_POLICY_PUT:
    {
      if (role_name.empty()) {
        cerr << "role name is empty" << std::endl;
        return -EINVAL;
      }

      if (policy_name.empty()) {
        cerr << "policy name is empty" << std::endl;
        return -EINVAL;
      }

      if (perm_policy_doc.empty()) {
        cerr << "permission policy document is empty" << std::endl;
        return -EINVAL;
      }

      bufferlist bl = bufferlist::static_from_string(perm_policy_doc);
      try {
        const rgw::IAM::Policy p(g_ceph_context, tenant, bl);
      } catch (rgw::IAM::PolicyParseException& e) {
        cerr << "failed to parse perm policy: " << e.what() << std::endl;
        return -EINVAL;
      }

      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      ret = role.get(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      role.set_perm_policy(policy_name, perm_policy_doc);
      ret = role.update(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      cout << "Permission policy attached successfully" << std::endl;
      return 0;
    }
  case OPT::ROLE_POLICY_LIST:
    {
      if (role_name.empty()) {
        cerr << "ERROR: Role name is empty" << std::endl;
        return -EINVAL;
      }
      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      ret = role.get(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      std::vector<string> policy_names = role.get_role_policy_names();
      show_policy_names(policy_names, formatter.get());
      return 0;
    }
  case OPT::ROLE_POLICY_GET:
    {
      if (role_name.empty()) {
        cerr << "ERROR: role name is empty" << std::endl;
        return -EINVAL;
      }

      if (policy_name.empty()) {
        cerr << "ERROR: policy name is empty" << std::endl;
        return -EINVAL;
      }
      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      int ret = role.get(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      string perm_policy;
      ret = role.get_role_policy(policy_name, perm_policy);
      if (ret < 0) {
        return -ret;
      }
      show_perm_policy(perm_policy, formatter.get());
      return 0;
    }
  case OPT::ROLE_POLICY_DELETE:
    {
      if (role_name.empty()) {
        cerr << "ERROR: role name is empty" << std::endl;
        return -EINVAL;
      }

      if (policy_name.empty()) {
        cerr << "ERROR: policy name is empty" << std::endl;
        return -EINVAL;
      }
      RGWRole role(g_ceph_context, store->getRados()->pctl, role_name, tenant);
      ret = role.get(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      ret = role.delete_policy(policy_name);
      if (ret < 0) {
        return -ret;
      }
      ret = role.update(dpp(), null_yield);
      if (ret < 0) {
        return -ret;
      }
      cout << "Policy: " << policy_name << " successfully deleted for role: "
           << role_name << std::endl;
      return 0;
  }
  default:
    output_user_info = false;
  }

  // output the result of a user operation
  if (output_user_info) {
    ret = user.info(info, &err_msg);
    if (ret < 0) {
      cerr << "could not fetch user info: " << err_msg << std::endl;
      return -ret;
    }
    show_user_info(info, formatter.get());
  }

  if (opt_cmd == OPT::POLICY) {
    if (format == "xml") {
      int ret = RGWBucketAdminOp::dump_s3_policy(store, bucket_op, cout, dpp());
      if (ret < 0) {
        cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
    } else {
      int ret = RGWBucketAdminOp::get_policy(store, bucket_op, f, dpp());
      if (ret < 0) {
        cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
    }
  }

  if (opt_cmd == OPT::BUCKET_LIMIT_CHECK) {
    void *handle;
    std::list<std::string> user_ids;
    metadata_key = "user";
    int max = 1000;

    bool truncated;

    if (! user_id.empty()) {
      user_ids.push_back(user_id.id);
      ret =
	RGWBucketAdminOp::limit_check(store, bucket_op, user_ids, f,
				      null_yield, dpp(), warnings_only);
    } else {
      /* list users in groups of max-keys, then perform user-bucket
       * limit-check on each group */
     ret = store->ctl()->meta.mgr->list_keys_init(dpp(), metadata_key, &handle);
      if (ret < 0) {
	cerr << "ERROR: buckets limit check can't get user metadata_key: "
	     << cpp_strerror(-ret) << std::endl;
	return -ret;
      }

      do {
	ret = store->ctl()->meta.mgr->list_keys_next(handle, max, user_ids,
					      &truncated);
	if (ret < 0 && ret != -ENOENT) {
	  cerr << "ERROR: buckets limit check lists_keys_next(): "
	       << cpp_strerror(-ret) << std::endl;
	  break;
	} else {
	  /* ok, do the limit checks for this group */
	  ret =
	    RGWBucketAdminOp::limit_check(store, bucket_op, user_ids, f,
					  null_yield, dpp(), warnings_only);
	  if (ret < 0)
	    break;
	}
	user_ids.clear();
      } while (truncated);
      store->ctl()->meta.mgr->list_keys_complete(handle);
    }
    return -ret;
  } /* OPT::BUCKET_LIMIT_CHECK */

  if (opt_cmd == OPT::BUCKETS_LIST) {
    if (bucket_name.empty()) {
      if (!user_id.empty()) {
        if (!user_op.has_existing_user()) {
          cerr << "ERROR: could not find user: " << user_id << std::endl;
          return -ENOENT;
        }
      }
      RGWBucketAdminOp::info(store, bucket_op, f, null_yield, dpp());
    } else {
      RGWBucketInfo bucket_info;
      int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
      if (ret < 0) {
        cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      formatter->open_array_section("entries");

      bool truncated = false;
      int count = 0;

      static constexpr int MAX_PAGINATE_SIZE = 10000;
      static constexpr int DEFAULT_MAX_ENTRIES = 1000;

      if (max_entries < 0) {
	max_entries = DEFAULT_MAX_ENTRIES;
      }
      const int paginate_size = std::min(max_entries, MAX_PAGINATE_SIZE);

      string prefix;
      string delim;
      vector<rgw_bucket_dir_entry> result;
      map<string, bool> common_prefixes;
      string ns;

      RGWRados::Bucket target(store->getRados(), bucket_info);
      RGWRados::Bucket::List list_op(&target);

      list_op.params.prefix = prefix;
      list_op.params.delim = delim;
      list_op.params.marker = rgw_obj_key(marker);
      list_op.params.ns = ns;
      list_op.params.enforce_ns = false;
      list_op.params.list_versions = true;
      list_op.params.allow_unordered = bool(allow_unordered);

      do {
        const int remaining = max_entries - count;
        ret = list_op.list_objects(dpp(), std::min(remaining, paginate_size),
				   &result, &common_prefixes, &truncated,
				   null_yield);
        if (ret < 0) {
          cerr << "ERROR: store->list_objects(): " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        count += result.size();

        for (const auto& entry : result) {
          encode_json("entry", entry, formatter.get());
        }
        formatter->flush(cout);
      } while (truncated && count < max_entries);

      formatter->close_section();
      formatter->flush(cout);
    } /* have bucket_name */
  } /* OPT::BUCKETS_LIST */

  if (opt_cmd == OPT::BUCKET_RADOS_LIST) {
    RGWRadosList lister(store,
			max_concurrent_ios, orphan_stale_secs, tenant);
    if (rgw_obj_fs) {
      lister.set_field_separator(*rgw_obj_fs);
    }

    if (bucket_name.empty()) {
      ret = lister.run(dpp());
    } else {
      ret = lister.run(dpp(), bucket_name);
    }

    if (ret < 0) {
      std::cerr <<
	"ERROR: bucket radoslist failed to finish before " <<
	"encountering error: " << cpp_strerror(-ret) << std::endl;
      std::cerr << "************************************"
	"************************************" << std::endl;
      std::cerr << "WARNING: THE RESULTS ARE NOT RELIABLE AND SHOULD NOT " <<
	"BE USED IN DELETING ORPHANS" << std::endl;
      std::cerr << "************************************"
	"************************************" << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BUCKET_STATS) {
    if (bucket_name.empty() && !bucket_id.empty()) {
      rgw_bucket bucket;
      if (!rgw_find_bucket_by_id(dpp(), store->ctx(), store->ctl()->meta.mgr, marker, bucket_id, &bucket)) {
        cerr << "failure: no such bucket id" << std::endl;
        return -ENOENT;
      }
      bucket_op.set_tenant(bucket.tenant);
      bucket_op.set_bucket_name(bucket.name);
    }
    bucket_op.set_fetch_stats(true);

    int r = RGWBucketAdminOp::info(store, bucket_op, f, null_yield, dpp());
    if (r < 0) {
      cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
      return -r;
    }
  }

  if (opt_cmd == OPT::BUCKET_LINK) {
    bucket_op.set_bucket_id(bucket_id);
    bucket_op.set_new_bucket_name(new_bucket_name);
    string err;
    int r = RGWBucketAdminOp::link(store, bucket_op, dpp(), &err);
    if (r < 0) {
      cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
      return -r;
    }
  }

  if (opt_cmd == OPT::BUCKET_UNLINK) {
    int r = RGWBucketAdminOp::unlink(store, bucket_op, dpp());
    if (r < 0) {
      cerr << "failure: " << cpp_strerror(-r) << std::endl;
      return -r;
    }
  }

  if (opt_cmd == OPT::BUCKET_CHOWN) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket name not specified" << std::endl;
      return EINVAL;
    }

    bucket_op.set_bucket_name(bucket_name);
    bucket_op.set_new_bucket_name(new_bucket_name);
    string err;
    string marker;

    int r = RGWBucketAdminOp::chown(store, bucket_op, marker, dpp(), &err);
    if (r < 0) {
      cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
      return -r;
    }
  }

  if (opt_cmd == OPT::LOG_LIST) {
    // filter by date?
    if (date.size() && date.size() != 10) {
      cerr << "bad date format for '" << date << "', expect YYYY-MM-DD" << std::endl;
      return EINVAL;
    }

    formatter->reset();
    formatter->open_array_section("logs");
    RGWAccessHandle h;
    int r = store->getRados()->log_list_init(dpp(), date, &h);
    if (r == -ENOENT) {
      // no logs.
    } else {
      if (r < 0) {
        cerr << "log list: error " << r << std::endl;
        return -r;
      }
      while (true) {
        string name;
        int r = store->getRados()->log_list_next(h, &name);
        if (r == -ENOENT)
          break;
        if (r < 0) {
          cerr << "log list: error " << r << std::endl;
          return -r;
        }
        formatter->dump_string("object", name);
      }
    }
    formatter->close_section();
    formatter->flush(cout);
    cout << std::endl;
  }

  if (opt_cmd == OPT::LOG_SHOW || opt_cmd == OPT::LOG_RM) {
    if (object.empty() && (date.empty() || bucket_name.empty() || bucket_id.empty())) {
      cerr << "specify an object or a date, bucket and bucket-id" << std::endl;
      exit(1);
    }

    string oid;
    if (!object.empty()) {
      oid = object;
    } else {
      oid = date;
      oid += "-";
      oid += bucket_id;
      oid += "-";
      oid += bucket_name;
    }

    if (opt_cmd == OPT::LOG_SHOW) {
      RGWAccessHandle h;

      int r = store->getRados()->log_show_init(dpp(), oid, &h);
      if (r < 0) {
	cerr << "error opening log " << oid << ": " << cpp_strerror(-r) << std::endl;
	return -r;
      }

      formatter->reset();
      formatter->open_object_section("log");

      struct rgw_log_entry entry;

      // peek at first entry to get bucket metadata
      r = store->getRados()->log_show_next(h, &entry);
      if (r < 0) {
	cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl;
	return -r;
      }
      formatter->dump_string("bucket_id", entry.bucket_id);
      formatter->dump_string("bucket_owner", entry.bucket_owner.to_str());
      formatter->dump_string("bucket", entry.bucket);

      uint64_t agg_time = 0;
      uint64_t agg_bytes_sent = 0;
      uint64_t agg_bytes_received = 0;
      uint64_t total_entries = 0;

      if (show_log_entries)
        formatter->open_array_section("log_entries");

      do {
        using namespace std::chrono;
        uint64_t total_time = duration_cast<milliseconds>(entry.total_time).count();

        agg_time += total_time;
        agg_bytes_sent += entry.bytes_sent;
        agg_bytes_received += entry.bytes_received;
        total_entries++;

        if (skip_zero_entries && entry.bytes_sent == 0 &&
            entry.bytes_received == 0)
          goto next;

        if (show_log_entries) {

	  rgw_format_ops_log_entry(entry, formatter.get());
	  formatter->flush(cout);
        }
next:
	r = store->getRados()->log_show_next(h, &entry);
      } while (r > 0);

      if (r < 0) {
      	cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl;
	return -r;
      }
      if (show_log_entries)
        formatter->close_section();

      if (show_log_sum) {
        formatter->open_object_section("log_sum");
	formatter->dump_int("bytes_sent", agg_bytes_sent);
	formatter->dump_int("bytes_received", agg_bytes_received);
	formatter->dump_int("total_time", agg_time);
	formatter->dump_int("total_entries", total_entries);
        formatter->close_section();
      }
      formatter->close_section();
      formatter->flush(cout);
      cout << std::endl;
    }
    if (opt_cmd == OPT::LOG_RM) {
      int r = store->getRados()->log_remove(dpp(), oid);
      if (r < 0) {
	cerr << "error removing log " << oid << ": " << cpp_strerror(-r) << std::endl;
	return -r;
      }
    }
  }

  if (opt_cmd == OPT::POOL_ADD) {
    if (pool_name.empty()) {
      cerr << "need to specify pool to add!" << std::endl;
      exit(1);
    }

    int ret = store->svc()->zone->add_bucket_placement(dpp(), pool, null_yield);
    if (ret < 0)
      cerr << "failed to add bucket placement: " << cpp_strerror(-ret) << std::endl;
  }

  if (opt_cmd == OPT::POOL_RM) {
    if (pool_name.empty()) {
      cerr << "need to specify pool to remove!" << std::endl;
      exit(1);
    }

    int ret = store->svc()->zone->remove_bucket_placement(dpp(), pool, null_yield);
    if (ret < 0)
      cerr << "failed to remove bucket placement: " << cpp_strerror(-ret) << std::endl;
  }

  if (opt_cmd == OPT::POOLS_LIST) {
    set<rgw_pool> pools;
    int ret = store->svc()->zone->list_placement_set(dpp(), pools, null_yield);
    if (ret < 0) {
      cerr << "could not list placement set: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    formatter->reset();
    formatter->open_array_section("pools");
    for (auto siter = pools.begin(); siter != pools.end(); ++siter) {
      formatter->open_object_section("pool");
      formatter->dump_string("name",  siter->to_str());
      formatter->close_section();
    }
    formatter->close_section();
    formatter->flush(cout);
    cout << std::endl;
  }

  if (opt_cmd == OPT::USAGE_SHOW) {
    uint64_t start_epoch = 0;
    uint64_t end_epoch = (uint64_t)-1;

    int ret;

    if (!start_date.empty()) {
      ret = utime_t::parse_date(start_date, &start_epoch, NULL);
      if (ret < 0) {
        cerr << "ERROR: failed to parse start date" << std::endl;
        return 1;
      }
    }
    if (!end_date.empty()) {
      ret = utime_t::parse_date(end_date, &end_epoch, NULL);
      if (ret < 0) {
        cerr << "ERROR: failed to parse end date" << std::endl;
        return 1;
      }
    }


    ret = RGWUsage::show(dpp(), store->getRados(), user_id, bucket_name, start_epoch, end_epoch,
			 show_log_entries, show_log_sum, &categories,
			 f);
    if (ret < 0) {
      cerr << "ERROR: failed to show usage" << std::endl;
      return 1;
    }
  }

  if (opt_cmd == OPT::USAGE_TRIM) {
    if (user_id.empty() && bucket_name.empty() &&
	start_date.empty() && end_date.empty() && !yes_i_really_mean_it) {
      cerr << "usage trim without user/date/bucket specified will remove *all* users data" << std::endl;
      cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
      return 1;
    }
    int ret;
    uint64_t start_epoch = 0;
    uint64_t end_epoch = (uint64_t)-1;


    if (!start_date.empty()) {
      ret = utime_t::parse_date(start_date, &start_epoch, NULL);
      if (ret < 0) {
        cerr << "ERROR: failed to parse start date" << std::endl;
        return 1;
      }
    }

    if (!end_date.empty()) {
      ret = utime_t::parse_date(end_date, &end_epoch, NULL);
      if (ret < 0) {
        cerr << "ERROR: failed to parse end date" << std::endl;
        return 1;
      }
    }

    ret = RGWUsage::trim(dpp(), store->getRados(), user_id, bucket_name, start_epoch, end_epoch);
    if (ret < 0) {
      cerr << "ERROR: read_usage() returned ret=" << ret << std::endl;
      return 1;
    }
  }

  if (opt_cmd == OPT::USAGE_CLEAR) {
    if (!yes_i_really_mean_it) {
      cerr << "usage clear would remove *all* users usage data for all time" << std::endl;
      cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
      return 1;
    }

    ret = RGWUsage::clear(dpp(), store->getRados());
    if (ret < 0) {
      return ret;
    }
  }


  if (opt_cmd == OPT::OLH_GET || opt_cmd == OPT::OLH_READLOG) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    if (object.empty()) {
      cerr << "ERROR: object not specified" << std::endl;
      return EINVAL;
    }
  }

  if (opt_cmd == OPT::OLH_GET) {
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    RGWOLHInfo olh;
    rgw_obj obj(bucket, object);
    ret = store->getRados()->get_olh(dpp(), bucket_info, obj, &olh);
    if (ret < 0) {
      cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    encode_json("olh", olh, formatter.get());
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::OLH_READLOG) {
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    map<uint64_t, vector<rgw_bucket_olh_log_entry> > log;
    bool is_truncated;

    RGWObjectCtx rctx(store);
    rgw_obj obj(bucket, object);

    RGWObjState *state;

    ret = store->getRados()->get_obj_state(dpp(), &rctx, bucket_info, obj, &state, false, null_yield); /* don't follow olh */
    if (ret < 0) {
      return -ret;
    }

    ret = store->getRados()->bucket_index_read_olh_log(dpp(), bucket_info, *state, obj, 0, &log, &is_truncated);
    if (ret < 0) {
      cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    formatter->open_object_section("result");
    encode_json("is_truncated", is_truncated, formatter.get());
    encode_json("log", log, formatter.get());
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::BI_GET) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket name not specified" << std::endl;
      return EINVAL;
    }
    if (object.empty()) {
      cerr << "ERROR: object not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    rgw_obj obj(bucket, object);
    if (!object_version.empty()) {
      obj.key.set_instance(object_version);
    }

    rgw_cls_bi_entry entry;

    ret = store->getRados()->bi_get(dpp(), bucket_info, obj, bi_index_type, &entry);
    if (ret < 0) {
      cerr << "ERROR: bi_get(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    encode_json("entry", entry, formatter.get());
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::BI_PUT) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket name not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    rgw_cls_bi_entry entry;
    cls_rgw_obj_key key;
    ret = read_decode_json(infile, entry, &key);
    if (ret < 0) {
      return 1;
    }

    rgw_obj obj(bucket, key);

    ret = store->getRados()->bi_put(dpp(), bucket, obj, entry);
    if (ret < 0) {
      cerr << "ERROR: bi_put(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BI_LIST) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket name not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    list<rgw_cls_bi_entry> entries;
    bool is_truncated;
    if (max_entries < 0) {
      max_entries = 1000;
    }

    int max_shards = (bucket_info.layout.current_index.layout.normal.num_shards > 0 ? bucket_info.layout.current_index.layout.normal.num_shards : 1);

    formatter->open_array_section("entries");

    int i = (specified_shard_id ? shard_id : 0);
    for (; i < max_shards; i++) {
      RGWRados::BucketShard bs(store->getRados());
      int shard_id = (bucket_info.layout.current_index.layout.normal.num_shards > 0  ? i : -1);

      int ret = bs.init(bucket, shard_id, bucket_info.layout.current_index, nullptr /* no RGWBucketInfo */, dpp());
      marker.clear();

      if (ret < 0) {
        cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << shard_id << "): " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }

      do {
        entries.clear();
	// if object is specified, we use that as a filter to only retrieve some some entries
        ret = store->getRados()->bi_list(bs, object, marker, max_entries, &entries, &is_truncated);
        if (ret < 0) {
          cerr << "ERROR: bi_list(): " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        list<rgw_cls_bi_entry>::iterator iter;
        for (iter = entries.begin(); iter != entries.end(); ++iter) {
          rgw_cls_bi_entry& entry = *iter;
          encode_json("entry", entry, formatter.get());
          marker = entry.idx;
        }
        formatter->flush(cout);
      } while (is_truncated);
      formatter->flush(cout);

      if (specified_shard_id)
        break;
    }
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::BI_PURGE) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket name not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    RGWBucketInfo cur_bucket_info;
    rgw_bucket cur_bucket;
    ret = init_bucket(tenant, bucket_name, string(), cur_bucket_info, cur_bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init current bucket info for bucket_name=" << bucket_name << ": " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    if (cur_bucket_info.bucket.bucket_id == bucket_info.bucket.bucket_id && !yes_i_really_mean_it) {
      cerr << "specified bucket instance points to a current bucket instance" << std::endl;
      cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
      return EINVAL;
    }

    int max_shards = (bucket_info.layout.current_index.layout.normal.num_shards > 0 ? bucket_info.layout.current_index.layout.normal.num_shards : 1);

    for (int i = 0; i < max_shards; i++) {
      RGWRados::BucketShard bs(store->getRados());
      int shard_id = (bucket_info.layout.current_index.layout.normal.num_shards > 0  ? i : -1);
      int ret = bs.init(bucket, shard_id, bucket_info.layout.current_index, nullptr /* no RGWBucketInfo */, dpp());
      if (ret < 0) {
        cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << shard_id << "): " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }

      ret = store->getRados()->bi_remove(bs);
      if (ret < 0) {
        cerr << "ERROR: failed to remove bucket index object: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
    }
  }

  if (opt_cmd == OPT::OBJECT_PUT) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    if (object.empty()) {
      cerr << "ERROR: object not specified" << std::endl;
      return EINVAL;
    }

    RGWDataAccess data_access(store);
    rgw_obj_key key(object, object_version);

    RGWDataAccess::BucketRef b;
    RGWDataAccess::ObjectRef obj;

    int ret = data_access.get_bucket(dpp(), tenant, bucket_name, bucket_id, &b, null_yield);
    if (ret < 0) {
      cerr << "ERROR: failed to init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    ret = b->get_object(key, &obj);
    if (ret < 0) {
      cerr << "ERROR: failed to get object: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    bufferlist bl;
    ret = read_input(infile, bl);
    if (ret < 0) {
      cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
    }

    map<string, bufferlist> attrs;
    ret = obj->put(bl, attrs, dpp(), null_yield);
    if (ret < 0) {
      cerr << "ERROR: put object returned error: " << cpp_strerror(-ret) << std::endl;
    }
  }

  if (opt_cmd == OPT::OBJECT_RM) {
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    rgw_obj_key key(object, object_version);
    ret = rgw_remove_object(dpp(), store, bucket_info, bucket, key);

    if (ret < 0) {
      cerr << "ERROR: object remove returned: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::OBJECT_REWRITE) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    if (object.empty()) {
      cerr << "ERROR: object not specified" << std::endl;
      return EINVAL;
    }

    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    rgw::sal::RGWRadosBucket rbucket(store, bucket);
    rgw::sal::RGWRadosObject obj(store, object, &rbucket);
    obj.set_instance(object_version);
    bool need_rewrite = true;
    if (min_rewrite_stripe_size > 0) {
      ret = check_min_obj_stripe_size(store, bucket_info, &obj, min_rewrite_stripe_size, &need_rewrite);
      if (ret < 0) {
        ldpp_dout(dpp(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << ret << dendl;
      }
    }
    if (need_rewrite) {
      ret = store->getRados()->rewrite_obj(bucket_info, &obj, dpp(), null_yield);
      if (ret < 0) {
        cerr << "ERROR: object rewrite returned: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
    } else {
      ldpp_dout(dpp(), 20) << "skipped object" << dendl;
    }
  }

  if (opt_cmd == OPT::OBJECTS_EXPIRE) {
    if (!store->getRados()->process_expire_objects(dpp())) {
      cerr << "ERROR: process_expire_objects() processing returned error." << std::endl;
      return 1;
    }
  }

  if (opt_cmd == OPT::OBJECTS_EXPIRE_STALE_LIST) {
    ret = RGWBucketAdminOp::fix_obj_expiry(store, bucket_op, f, dpp(), true);
    if (ret < 0) {
      cerr << "ERROR: listing returned " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::OBJECTS_EXPIRE_STALE_RM) {
    ret = RGWBucketAdminOp::fix_obj_expiry(store, bucket_op, f, dpp(), false);
    if (ret < 0) {
      cerr << "ERROR: removing returned " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BUCKET_REWRITE) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }

    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    uint64_t start_epoch = 0;
    uint64_t end_epoch = 0;

    if (!end_date.empty()) {
      int ret = utime_t::parse_date(end_date, &end_epoch, NULL);
      if (ret < 0) {
        cerr << "ERROR: failed to parse end date" << std::endl;
        return EINVAL;
      }
    }
    if (!start_date.empty()) {
      int ret = utime_t::parse_date(start_date, &start_epoch, NULL);
      if (ret < 0) {
        cerr << "ERROR: failed to parse start date" << std::endl;
        return EINVAL;
      }
    }

    bool is_truncated = true;
    bool cls_filtered = true;

    rgw_obj_index_key marker;
    string empty_prefix;
    string empty_delimiter;

    formatter->open_object_section("result");
    formatter->dump_string("bucket", bucket_name);
    formatter->open_array_section("objects");

    constexpr uint32_t NUM_ENTRIES = 1000;
    uint16_t expansion_factor = 1;
    while (is_truncated) {
      RGWRados::ent_map_t result;
      result.reserve(NUM_ENTRIES);

      int r = store->getRados()->cls_bucket_list_ordered(
	dpp(), bucket_info, RGW_NO_SHARD,
	marker, empty_prefix, empty_delimiter,
	NUM_ENTRIES, true, expansion_factor,
	result, &is_truncated, &cls_filtered, &marker,
	null_yield,
	rgw_bucket_object_check_filter);
      if (r < 0 && r != -ENOENT) {
        cerr << "ERROR: failed operation r=" << r << std::endl;
      } else if (r == -ENOENT) {
        break;
      }

      if (result.size() < NUM_ENTRIES / 8) {
	++expansion_factor;
      } else if (result.size() > NUM_ENTRIES * 7 / 8 &&
		 expansion_factor > 1) {
	--expansion_factor;
      }

      for (auto iter = result.begin(); iter != result.end(); ++iter) {
        rgw_obj_key key = iter->second.key;
        rgw_bucket_dir_entry& entry = iter->second;

        formatter->open_object_section("object");
        formatter->dump_string("name", key.name);
        formatter->dump_string("instance", key.instance);
        formatter->dump_int("size", entry.meta.size);
        utime_t ut(entry.meta.mtime);
        ut.gmtime(formatter->dump_stream("mtime"));

        if ((entry.meta.size < min_rewrite_size) ||
            (entry.meta.size > max_rewrite_size) ||
            (start_epoch > 0 && start_epoch > (uint64_t)ut.sec()) ||
            (end_epoch > 0 && end_epoch < (uint64_t)ut.sec())) {
          formatter->dump_string("status", "Skipped");
        } else {
	  rgw::sal::RGWRadosBucket rbucket(store, bucket);
	  rgw::sal::RGWRadosObject obj(store, key, &rbucket);

          bool need_rewrite = true;
          if (min_rewrite_stripe_size > 0) {
            r = check_min_obj_stripe_size(store, bucket_info, &obj, min_rewrite_stripe_size, &need_rewrite);
            if (r < 0) {
              ldpp_dout(dpp(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << r << dendl;
            }
          }
          if (!need_rewrite) {
            formatter->dump_string("status", "Skipped");
          } else {
            r = store->getRados()->rewrite_obj(bucket_info, &obj, dpp(), null_yield);
            if (r == 0) {
              formatter->dump_string("status", "Success");
            } else {
              formatter->dump_string("status", cpp_strerror(-r));
            }
          }
        }
        formatter->dump_int("flags", entry.flags);

        formatter->close_section();
        formatter->flush(cout);
      }
    }
    formatter->close_section();
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::BUCKET_RESHARD) {
    rgw_bucket bucket;
    RGWBucketInfo bucket_info;
    map<string, bufferlist> attrs;

    int ret = check_reshard_bucket_params(store,
					  bucket_name,
					  tenant,
					  bucket_id,
					  num_shards_specified,
					  num_shards,
					  yes_i_really_mean_it,
					  bucket,
					  bucket_info,
					  attrs);
    if (ret < 0) {
      return ret;
    }

    RGWBucketReshard br(store, bucket_info, attrs, nullptr /* no callback */);

#define DEFAULT_RESHARD_MAX_ENTRIES 1000
    if (max_entries < 1) {
      max_entries = DEFAULT_RESHARD_MAX_ENTRIES;
    }

    return br.execute(num_shards, max_entries, dpp(),
                      verbose, &cout, formatter.get());
  }

  if (opt_cmd == OPT::RESHARD_ADD) {
    rgw_bucket bucket;
    RGWBucketInfo bucket_info;
    map<string, bufferlist> attrs;

    int ret = check_reshard_bucket_params(store,
					  bucket_name,
					  tenant,
					  bucket_id,
					  num_shards_specified,
					  num_shards,
					  yes_i_really_mean_it,
					  bucket,
					  bucket_info,
					  attrs);
    if (ret < 0) {
      return ret;
    }

    int num_source_shards = (bucket_info.layout.current_index.layout.normal.num_shards > 0 ? bucket_info.layout.current_index.layout.normal.num_shards : 1);

    RGWReshard reshard(store, dpp());
    cls_rgw_reshard_entry entry;
    entry.time = real_clock::now();
    entry.tenant = tenant;
    entry.bucket_name = bucket_name;
    entry.bucket_id = bucket_info.bucket.bucket_id;
    entry.old_num_shards = num_source_shards;
    entry.new_num_shards = num_shards;

    return reshard.add(dpp(), entry);
  }

  if (opt_cmd == OPT::RESHARD_LIST) {
    int ret;
    int count = 0;
    if (max_entries < 0) {
      max_entries = 1000;
    }

    int num_logshards =
      store->ctx()->_conf.get_val<uint64_t>("rgw_reshard_num_logs");

    RGWReshard reshard(store, dpp());

    formatter->open_array_section("reshard");
    for (int i = 0; i < num_logshards; i++) {
      bool is_truncated = true;
      std::string marker;
      do {
	std::list<cls_rgw_reshard_entry> entries;
        ret = reshard.list(i, marker, max_entries - count, entries, &is_truncated);
        if (ret < 0) {
          cerr << "Error listing resharding buckets: " << cpp_strerror(-ret) << std::endl;
          return ret;
        }
        for (const auto& entry : entries) {
          encode_json("entry", entry, formatter.get());
        }
	if (is_truncated) {
	  entries.crbegin()->get_key(&marker); // last entry's key becomes marker
	}
        count += entries.size();
        formatter->flush(cout);
      } while (is_truncated && count < max_entries);

      if (count >= max_entries) {
        break;
      }
    }

    formatter->close_section();
    formatter->flush(cout);

    return 0;
  }

  if (opt_cmd == OPT::RESHARD_STATUS) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }

    rgw_bucket bucket;
    RGWBucketInfo bucket_info;
    map<string, bufferlist> attrs;
    ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket, &attrs);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    RGWBucketReshard br(store, bucket_info, attrs, nullptr /* no callback */);
    list<cls_rgw_bucket_instance_entry> status;
    int r = br.get_status(dpp(), &status);
    if (r < 0) {
      cerr << "ERROR: could not get resharding status for bucket " <<
	bucket_name << std::endl;
      return -r;
    }

    show_reshard_status(status, formatter.get());
  }

  if (opt_cmd == OPT::RESHARD_PROCESS) {
    RGWReshard reshard(store, true, &cout);

    int ret = reshard.process_all_logshards(dpp());
    if (ret < 0) {
      cerr << "ERROR: failed to process reshard logs, error=" << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::RESHARD_CANCEL) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }

    rgw_bucket bucket;
    RGWBucketInfo bucket_info;
    map<string, bufferlist> attrs;
    bool bucket_initable = true;
    ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket,
                      &attrs);
    if (ret < 0) {
      if (yes_i_really_mean_it) {
        bucket_initable = false;
      } else {
        cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) <<
          "; if you want to cancel the reshard request nonetheless, please "
          "use the --yes-i-really-mean-it option" << std::endl;
        return -ret;
      }
    }

    if (bucket_initable) {
      // we did not encounter an error, so let's work with the bucket
      RGWBucketReshard br(store, bucket_info, attrs,
                          nullptr /* no callback */);
      int ret = br.cancel(dpp());
      if (ret < 0) {
        if (ret == -EBUSY) {
          cerr << "There is ongoing resharding, please retry after " <<
            store->ctx()->_conf.get_val<uint64_t>(
              "rgw_reshard_bucket_lock_duration") <<
            " seconds " << std::endl;
        } else {
          cerr << "Error canceling bucket " << bucket_name <<
            " resharding: " << cpp_strerror(-ret) << std::endl;
        }
        return ret;
      }
    }

    RGWReshard reshard(store, dpp());

    cls_rgw_reshard_entry entry;
    entry.tenant = tenant;
    entry.bucket_name = bucket_name;
    //entry.bucket_id = bucket_id;

    ret = reshard.remove(dpp(), entry);
    if (ret < 0 && ret != -ENOENT) {
      cerr << "Error in updating reshard log with bucket " <<
        bucket_name << ": " << cpp_strerror(-ret) << std::endl;
      return ret;
    }
  } // OPT_RESHARD_CANCEL

  if (opt_cmd == OPT::OBJECT_UNLINK) {
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    list<rgw_obj_index_key> oid_list;
    rgw_obj_key key(object, object_version);
    rgw_obj_index_key index_key;
    key.get_index_key(&index_key);
    oid_list.push_back(index_key);
    ret = store->getRados()->remove_objs_from_index(dpp(), bucket_info, oid_list);
    if (ret < 0) {
      cerr << "ERROR: remove_obj_from_index() returned error: " << cpp_strerror(-ret) << std::endl;
      return 1;
    }
  }

  if (opt_cmd == OPT::OBJECT_STAT) {
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    rgw_obj obj(bucket, object);
    obj.key.set_instance(object_version);

    uint64_t obj_size;
    map<string, bufferlist> attrs;
    RGWObjectCtx obj_ctx(store);
    RGWRados::Object op_target(store->getRados(), bucket_info, obj_ctx, obj);
    RGWRados::Object::Read read_op(&op_target);

    read_op.params.attrs = &attrs;
    read_op.params.obj_size = &obj_size;

    ret = read_op.prepare(null_yield, dpp());
    if (ret < 0) {
      cerr << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << std::endl;
      return 1;
    }
    formatter->open_object_section("object_metadata");
    formatter->dump_string("name", object);
    formatter->dump_unsigned("size", obj_size);

    map<string, bufferlist>::iterator iter;
    map<string, bufferlist> other_attrs;
    for (iter = attrs.begin(); iter != attrs.end(); ++iter) {
      bufferlist& bl = iter->second;
      bool handled = false;
      if (iter->first == RGW_ATTR_MANIFEST) {
        handled = decode_dump<RGWObjManifest>("manifest", bl, formatter.get());
      } else if (iter->first == RGW_ATTR_ACL) {
        handled = decode_dump<RGWAccessControlPolicy>("policy", bl, formatter.get());
      } else if (iter->first == RGW_ATTR_ID_TAG) {
        handled = dump_string("tag", bl, formatter.get());
      } else if (iter->first == RGW_ATTR_ETAG) {
        handled = dump_string("etag", bl, formatter.get());
      } else if (iter->first == RGW_ATTR_COMPRESSION) {
        handled = decode_dump<RGWCompressionInfo>("compression", bl, formatter.get());
      } else if (iter->first == RGW_ATTR_DELETE_AT) {
        handled = decode_dump<utime_t>("delete_at", bl, formatter.get());
      }

      if (!handled)
        other_attrs[iter->first] = bl;
    }

    formatter->open_object_section("attrs");
    for (iter = other_attrs.begin(); iter != other_attrs.end(); ++iter) {
      dump_string(iter->first.c_str(), iter->second, formatter.get());
    }
    formatter->close_section();
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::BUCKET_CHECK) {
    if (check_head_obj_locator) {
      if (bucket_name.empty()) {
        cerr << "ERROR: need to specify bucket name" << std::endl;
        return EINVAL;
      }
      do_check_object_locator(tenant, bucket_name, fix, remove_bad, formatter.get());
    } else {
      RGWBucketAdminOp::check_index(store, bucket_op, f, null_yield, dpp());
    }
  }

  if (opt_cmd == OPT::BUCKET_RM) {
    if (!inconsistent_index) {
      RGWBucketAdminOp::remove_bucket(store, bucket_op, null_yield, dpp(), bypass_gc, true);
    } else {
      if (!yes_i_really_mean_it) {
	cerr << "using --inconsistent_index can corrupt the bucket index " << std::endl
	<< "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
	return 1;
      }
      RGWBucketAdminOp::remove_bucket(store, bucket_op, null_yield, dpp(), bypass_gc, false);
    }
  }

  if (opt_cmd == OPT::GC_LIST) {
    int index = 0;
    bool truncated;
    bool processing_queue = false;
    formatter->open_array_section("entries");

    do {
      list<cls_rgw_gc_obj_info> result;
      int ret = store->getRados()->list_gc_objs(&index, marker, 1000, !include_all, result, &truncated, processing_queue);
      if (ret < 0) {
	cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret) << std::endl;
	return 1;
      }


      list<cls_rgw_gc_obj_info>::iterator iter;
      for (iter = result.begin(); iter != result.end(); ++iter) {
	cls_rgw_gc_obj_info& info = *iter;
	formatter->open_object_section("chain_info");
	formatter->dump_string("tag", info.tag);
	formatter->dump_stream("time") << info.time;
	formatter->open_array_section("objs");
        list<cls_rgw_obj>::iterator liter;
	cls_rgw_obj_chain& chain = info.chain;
	for (liter = chain.objs.begin(); liter != chain.objs.end(); ++liter) {
	  cls_rgw_obj& obj = *liter;
          encode_json("obj", obj, formatter.get());
	}
	formatter->close_section(); // objs
	formatter->close_section(); // obj_chain
	formatter->flush(cout);
      }
    } while (truncated);
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::GC_PROCESS) {
    int ret = store->getRados()->process_gc(!include_all);
    if (ret < 0) {
      cerr << "ERROR: gc processing returned error: " << cpp_strerror(-ret) << std::endl;
      return 1;
    }
  }

  if (opt_cmd == OPT::LC_LIST) {
    formatter->open_array_section("lifecycle_list");
    vector<rgw::sal::Lifecycle::LCEntry> bucket_lc_map;
    string marker;
    int index{0};
#define MAX_LC_LIST_ENTRIES 100
    if (max_entries < 0) {
      max_entries = MAX_LC_LIST_ENTRIES;
    }
    do {
      int ret = store->getRados()->list_lc_progress(marker, max_entries,
						    bucket_lc_map, index);
      if (ret < 0) {
        cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret)
	     << std::endl;
        return 1;
      }
      for (const auto& entry : bucket_lc_map) {
        formatter->open_object_section("bucket_lc_info");
        formatter->dump_string("bucket", entry.bucket);
	char exp_buf[100];
	time_t t{time_t(entry.start_time)};
	if (std::strftime(
	      exp_buf, sizeof(exp_buf),
	      "%a, %d %b %Y %T %Z", std::gmtime(&t))) {
	  formatter->dump_string("started", exp_buf);
	}
        string lc_status = LC_STATUS[entry.status];
        formatter->dump_string("status", lc_status);
        formatter->close_section(); // objs
        formatter->flush(cout);
      }
    } while (!bucket_lc_map.empty());

    formatter->close_section(); //lifecycle list
    formatter->flush(cout);
  }


  if (opt_cmd == OPT::LC_GET) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }

    rgw_bucket bucket;
    RGWBucketInfo bucket_info;
    map<string, bufferlist> attrs;
    RGWLifecycleConfiguration config;
    ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket, &attrs);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    auto aiter = attrs.find(RGW_ATTR_LC);
    if (aiter == attrs.end()) {
      return -ENOENT;
    }

    bufferlist::const_iterator iter{&aiter->second};
    try {
      config.decode(iter);
    } catch (const buffer::error& e) {
      cerr << "ERROR: decode life cycle config failed" << std::endl;
      return -EIO;
    }

    encode_json("result", config, formatter.get());
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::LC_PROCESS) {
    int ret = store->getRados()->process_lc();
    if (ret < 0) {
      cerr << "ERROR: lc processing returned error: " << cpp_strerror(-ret) << std::endl;
      return 1;
    }
  }


  if (opt_cmd == OPT::LC_RESHARD_FIX) {
    ret = RGWBucketAdminOp::fix_lc_shards(store, bucket_op, f, dpp());
    if (ret < 0) {
      cerr << "ERROR: listing stale instances" << cpp_strerror(-ret) << std::endl;
    }

  }

  if (opt_cmd == OPT::ORPHANS_FIND) {
    if (!yes_i_really_mean_it) {
      cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; "
	   << "accidental removal of active objects cannot be reversed; "
	   << "do you really mean it? (requires --yes-i-really-mean-it)"
	   << std::endl;
      return EINVAL;
    } else {
      cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool"
	   << std::endl;
    }

    RGWOrphanSearch search(store, max_concurrent_ios, orphan_stale_secs);

    if (job_id.empty()) {
      cerr << "ERROR: --job-id not specified" << std::endl;
      return EINVAL;
    }
    if (pool_name.empty()) {
      cerr << "ERROR: --pool not specified" << std::endl;
      return EINVAL;
    }

    RGWOrphanSearchInfo info;

    info.pool = pool;
    info.job_name = job_id;
    info.num_shards = num_shards;

    int ret = search.init(dpp(), job_id, &info, detail);
    if (ret < 0) {
      cerr << "could not init search, ret=" << ret << std::endl;
      return -ret;
    }
    ret = search.run(dpp());
    if (ret < 0) {
      return -ret;
    }
  }

  if (opt_cmd == OPT::ORPHANS_FINISH) {
    if (!yes_i_really_mean_it) {
      cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; "
	   << "accidental removal of active objects cannot be reversed; "
	   << "do you really mean it? (requires --yes-i-really-mean-it)"
	   << std::endl;
      return EINVAL;
    } else {
      cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool"
	   << std::endl;
    }

    RGWOrphanSearch search(store, max_concurrent_ios, orphan_stale_secs);

    if (job_id.empty()) {
      cerr << "ERROR: --job-id not specified" << std::endl;
      return EINVAL;
    }
    int ret = search.init(dpp(), job_id, NULL);
    if (ret < 0) {
      if (ret == -ENOENT) {
        cerr << "job not found" << std::endl;
      }
      return -ret;
    }
    ret = search.finish();
    if (ret < 0) {
      return -ret;
    }
  }

  if (opt_cmd == OPT::ORPHANS_LIST_JOBS){
    if (!yes_i_really_mean_it) {
      cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; "
	   << "do you really mean it? (requires --yes-i-really-mean-it)"
	   << std::endl;
      return EINVAL;
    } else {
      cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool"
	   << std::endl;
    }

    RGWOrphanStore orphan_store(store);
    int ret = orphan_store.init(dpp());
    if (ret < 0){
      cerr << "connection to cluster failed!" << std::endl;
      return -ret;
    }

    map <string,RGWOrphanSearchState> m;
    ret = orphan_store.list_jobs(m);
    if (ret < 0) {
      cerr << "job list failed" << std::endl;
      return -ret;
    }
    formatter->open_array_section("entries");
    for (const auto &it: m){
      if (!extra_info){
	formatter->dump_string("job-id",it.first);
      } else {
	encode_json("orphan_search_state", it.second, formatter.get());
      }
    }
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::USER_CHECK) {
    check_bad_user_bucket_mapping(store, user_id, fix, null_yield, dpp());
  }

  if (opt_cmd == OPT::USER_STATS) {
    if (user_id.empty()) {
      cerr << "ERROR: uid not specified" << std::endl;
      return EINVAL;
    }

    if (reset_stats) {
      if (!bucket_name.empty()) {
	cerr << "ERROR: --reset-stats does not work on buckets and "
	  "bucket specified" << std::endl;
	return EINVAL;
      }
      if (sync_stats) {
	cerr << "ERROR: sync-stats includes the reset-stats functionality, "
	  "so at most one of the two should be specified" << std::endl;
	return EINVAL;
      }
      ret = store->ctl()->user->reset_stats(dpp(), user_id, null_yield);
      if (ret < 0) {
	cerr << "ERROR: could not reset user stats: " << cpp_strerror(-ret) <<
	  std::endl;
	return -ret;
      }
    }

    if (sync_stats) {
      if (!bucket_name.empty()) {
        RGWBucketInfo bucket_info;
        int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
        if (ret < 0) {
          cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }
        ret = store->ctl()->bucket->sync_user_stats(dpp(), user_id, bucket_info, null_yield);
        if (ret < 0) {
          cerr << "ERROR: could not sync bucket stats: " <<
	    cpp_strerror(-ret) << std::endl;
          return -ret;
        }
      } else {
        int ret = rgw_user_sync_all_stats(dpp(), store, user_id, null_yield);
        if (ret < 0) {
          cerr << "ERROR: could not sync user stats: " <<
	    cpp_strerror(-ret) << std::endl;
          return -ret;
        }
      }
    }

    constexpr bool omit_utilized_stats = false;
    RGWStorageStats stats(omit_utilized_stats);
    ceph::real_time last_stats_sync;
    ceph::real_time last_stats_update;
    int ret = store->ctl()->user->read_stats(dpp(), user_id, &stats, null_yield,
					     &last_stats_sync,
					     &last_stats_update);
    if (ret < 0) {
      if (ret == -ENOENT) { /* in case of ENOENT */
        cerr << "User has not been initialized or user does not exist" << std::endl;
      } else {
        cerr << "ERROR: can't read user: " << cpp_strerror(ret) << std::endl;
      }
      return -ret;
    }


    {
      Formatter::ObjectSection os(*formatter, "result");
      encode_json("stats", stats, formatter.get());
      utime_t last_sync_ut(last_stats_sync);
      encode_json("last_stats_sync", last_sync_ut, formatter.get());
      utime_t last_update_ut(last_stats_update);
      encode_json("last_stats_update", last_update_ut, formatter.get());
    }
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::METADATA_GET) {
    int ret = store->ctl()->meta.mgr->get(metadata_key, formatter.get(), null_yield, dpp());
    if (ret < 0) {
      cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    formatter->flush(cout);
  }

  if (opt_cmd == OPT::METADATA_PUT) {
    bufferlist bl;
    int ret = read_input(infile, bl);
    if (ret < 0) {
      cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    ret = store->ctl()->meta.mgr->put(metadata_key, bl, null_yield, dpp(), RGWMDLogSyncType::APPLY_ALWAYS, false);
    if (ret < 0) {
      cerr << "ERROR: can't put key: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::METADATA_RM) {
    int ret = store->ctl()->meta.mgr->remove(metadata_key, null_yield, dpp());
    if (ret < 0) {
      cerr << "ERROR: can't remove key: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::METADATA_LIST || opt_cmd == OPT::USER_LIST) {
    if (opt_cmd == OPT::USER_LIST) {
      metadata_key = "user";
    }
    void *handle;
    int max = 1000;
    int ret = store->ctl()->meta.mgr->list_keys_init(dpp(), metadata_key, marker, &handle);
    if (ret < 0) {
      cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    bool truncated;
    uint64_t count = 0;

    if (max_entries_specified) {
      formatter->open_object_section("result");
    }
    formatter->open_array_section("keys");

    uint64_t left;
    do {
      list<string> keys;
      left = (max_entries_specified ? max_entries - count : max);
      ret = store->ctl()->meta.mgr->list_keys_next(handle, left, keys, &truncated);
      if (ret < 0 && ret != -ENOENT) {
        cerr << "ERROR: lists_keys_next(): " << cpp_strerror(-ret) << std::endl;
        return -ret;
      } if (ret != -ENOENT) {
	for (list<string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) {
	  formatter->dump_string("key", *iter);
          ++count;
	}
	formatter->flush(cout);
      }
    } while (truncated && left > 0);

    formatter->close_section();

    if (max_entries_specified) {
      encode_json("truncated", truncated, formatter.get());
      encode_json("count", count, formatter.get());
      if (truncated) {
        encode_json("marker", store->ctl()->meta.mgr->get_marker(handle), formatter.get());
      }
      formatter->close_section();
    }
    formatter->flush(cout);

    store->ctl()->meta.mgr->list_keys_complete(handle);
  }

  if (opt_cmd == OPT::MDLOG_LIST) {
    if (!start_date.empty()) {
      std::cerr << "start-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_date.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_marker.empty()) {
      std::cerr << "end-marker not allowed." << std::endl;
      return -EINVAL;
    }
    if (!start_marker.empty()) {
      if (marker.empty()) {
	marker = start_marker;
      } else {
	std::cerr << "start-marker and marker not both allowed." << std::endl;
	return -EINVAL;
      }
    }

    int i = (specified_shard_id ? shard_id : 0);

    if (period_id.empty()) {
      int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
      if (ret < 0) {
        return -ret;
      }
      std::cerr << "No --period given, using current period="
          << period_id << std::endl;
    }
    RGWMetadataLog *meta_log = store->svc()->mdlog->get_log(period_id);

    formatter->open_array_section("entries");
    for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) {
      void *handle;
      list<cls_log_entry> entries;

      meta_log->init_list_entries(i, {}, {}, marker, &handle);
      bool truncated;
      do {
	  int ret = meta_log->list_entries(dpp(), handle, 1000, entries, NULL, &truncated);
        if (ret < 0) {
          cerr << "ERROR: meta_log->list_entries(): " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        for (list<cls_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
          cls_log_entry& entry = *iter;
          store->ctl()->meta.mgr->dump_log_entry(entry, formatter.get());
        }
        formatter->flush(cout);
      } while (truncated);

      meta_log->complete_list_entries(handle);

      if (specified_shard_id)
        break;
    }


    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::MDLOG_STATUS) {
    int i = (specified_shard_id ? shard_id : 0);

    if (period_id.empty()) {
      int ret = read_current_period_id(store, realm_id, realm_name, &period_id);
      if (ret < 0) {
        return -ret;
      }
      std::cerr << "No --period given, using current period="
          << period_id << std::endl;
    }
    RGWMetadataLog *meta_log = store->svc()->mdlog->get_log(period_id);

    formatter->open_array_section("entries");

    for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) {
      RGWMetadataLogInfo info;
      meta_log->get_info(dpp(), i, &info);

      ::encode_json("info", info, formatter.get());

      if (specified_shard_id)
        break;
    }


    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::MDLOG_AUTOTRIM) {
    // need a full history for purging old mdlog periods
    store->svc()->mdlog->init_oldest_log_period(null_yield, dpp());

    RGWCoroutinesManager crs(store->ctx(), store->getRados()->get_cr_registry());
    RGWHTTPManager http(store->ctx(), crs.get_completion_mgr());
    int ret = http.start();
    if (ret < 0) {
      cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }

    auto num_shards = g_conf()->rgw_md_log_max_shards;
    ret = crs.run(dpp(), create_admin_meta_log_trim_cr(dpp(), store, &http, num_shards));
    if (ret < 0) {
      cerr << "automated mdlog trim failed with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::MDLOG_TRIM) {
    if (!start_date.empty()) {
      std::cerr << "start-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_date.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!start_marker.empty()) {
      std::cerr << "start-marker not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_marker.empty()) {
      if (marker.empty()) {
	marker = end_marker;
      } else {
	std::cerr << "end-marker and marker not both allowed." << std::endl;
	return -EINVAL;
      }
    }

    if (!specified_shard_id) {
      cerr << "ERROR: shard-id must be specified for trim operation" << std::endl;
      return EINVAL;
    }

    if (marker.empty()) {
      cerr << "ERROR: marker must be specified for trim operation" << std::endl;
      return EINVAL;
    }

    if (period_id.empty()) {
      std::cerr << "missing --period argument" << std::endl;
      return EINVAL;
    }
    RGWMetadataLog *meta_log = store->svc()->mdlog->get_log(period_id);

    // trim until -ENODATA
    do {
      ret = meta_log->trim(dpp(), shard_id, {}, {}, {}, marker);
    } while (ret == 0);
    if (ret < 0 && ret != -ENODATA) {
      cerr << "ERROR: meta_log->trim(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::SYNC_INFO) {
    sync_info(opt_effective_zone_id, opt_bucket, zone_formatter.get());
  }

  if (opt_cmd == OPT::SYNC_STATUS) {
    sync_status(formatter.get());
  }

  if (opt_cmd == OPT::METADATA_SYNC_STATUS) {
    RGWMetaSyncStatusManager sync(store, store->svc()->rados->get_async_processor());

    int ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }

    rgw_meta_sync_status sync_status;
    ret = sync.read_sync_status(dpp(), &sync_status);
    if (ret < 0) {
      cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
      return -ret;
    }

    formatter->open_object_section("summary");
    encode_json("sync_status", sync_status, formatter.get());

    uint64_t full_total = 0;
    uint64_t full_complete = 0;

    for (auto marker_iter : sync_status.sync_markers) {
      full_total += marker_iter.second.total_entries;
      if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
        full_complete += marker_iter.second.pos;
      } else {
        full_complete += marker_iter.second.total_entries;
      }
    }

    formatter->open_object_section("full_sync");
    encode_json("total", full_total, formatter.get());
    encode_json("complete", full_complete, formatter.get());
    formatter->close_section();
    formatter->close_section();

    formatter->flush(cout);

  }

  if (opt_cmd == OPT::METADATA_SYNC_INIT) {
    RGWMetaSyncStatusManager sync(store, store->svc()->rados->get_async_processor());

    int ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }
    ret = sync.init_sync_status(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
      return -ret;
    }
  }


  if (opt_cmd == OPT::METADATA_SYNC_RUN) {
    RGWMetaSyncStatusManager sync(store, store->svc()->rados->get_async_processor());

    int ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }

    ret = sync.run(dpp(), null_yield);
    if (ret < 0) {
      cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::DATA_SYNC_STATUS) {
    if (source_zone.empty()) {
      cerr << "ERROR: source zone not specified" << std::endl;
      return EINVAL;
    }
    RGWDataSyncStatusManager sync(store, store->svc()->rados->get_async_processor(), source_zone, nullptr);

    int ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }

    rgw_data_sync_status sync_status;
    if (specified_shard_id) {
      set<string> pending_buckets;
      set<string> recovering_buckets;
      rgw_data_sync_marker sync_marker;
      ret = sync.read_shard_status(dpp(), shard_id, pending_buckets, recovering_buckets, &sync_marker, 
                                   max_entries_specified ? max_entries : 20);
      if (ret < 0 && ret != -ENOENT) {
        cerr << "ERROR: sync.read_shard_status() returned ret=" << ret << std::endl;
        return -ret;
      }
      formatter->open_object_section("summary");
      encode_json("shard_id", shard_id, formatter.get());
      encode_json("marker", sync_marker, formatter.get());
      encode_json("pending_buckets", pending_buckets, formatter.get());
      encode_json("recovering_buckets", recovering_buckets, formatter.get());
      formatter->close_section();
      formatter->flush(cout);
    } else {
      ret = sync.read_sync_status(dpp(), &sync_status);
      if (ret < 0 && ret != -ENOENT) {
        cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
        return -ret;
      }

      formatter->open_object_section("summary");
      encode_json("sync_status", sync_status, formatter.get());

      uint64_t full_total = 0;
      uint64_t full_complete = 0;

      for (auto marker_iter : sync_status.sync_markers) {
        full_total += marker_iter.second.total_entries;
        if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
          full_complete += marker_iter.second.pos;
        } else {
          full_complete += marker_iter.second.total_entries;
        }
      }

      formatter->open_object_section("full_sync");
      encode_json("total", full_total, formatter.get());
      encode_json("complete", full_complete, formatter.get());
      formatter->close_section();
      formatter->close_section();

      formatter->flush(cout);
    }
  }

  if (opt_cmd == OPT::DATA_SYNC_INIT) {
    if (source_zone.empty()) {
      cerr << "ERROR: source zone not specified" << std::endl;
      return EINVAL;
    }

    RGWDataSyncStatusManager sync(store, store->svc()->rados->get_async_processor(), source_zone, nullptr);

    int ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }

    ret = sync.init_sync_status(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::DATA_SYNC_RUN) {
    if (source_zone.empty()) {
      cerr << "ERROR: source zone not specified" << std::endl;
      return EINVAL;
    }

    RGWSyncModuleInstanceRef sync_module;
    int ret = store->svc()->sync_modules->get_manager()->create_instance(g_ceph_context, store->svc()->zone->get_zone().tier_type,
        store->svc()->zone->get_zone_params().tier_config, &sync_module);
    if (ret < 0) {
      ldpp_dout(dpp(), -1) << "ERROR: failed to init sync module instance, ret=" << ret << dendl;
      return ret;
    }

    RGWDataSyncStatusManager sync(store, store->svc()->rados->get_async_processor(), source_zone, nullptr, sync_module);

    ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }

    ret = sync.run(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BUCKET_SYNC_INIT) {
    if (source_zone.empty()) {
      cerr << "ERROR: source zone not specified" << std::endl;
      return EINVAL;
    }
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    rgw_bucket bucket;
    int ret = init_bucket_for_sync(tenant, bucket_name, bucket_id, bucket);
    if (ret < 0) {
      return -ret;
    }
    auto opt_sb = opt_source_bucket;
    if (opt_sb && opt_sb->bucket_id.empty()) {
      string sbid;
      rgw_bucket sbuck;
      int ret = init_bucket_for_sync(opt_sb->tenant, opt_sb->name, sbid, sbuck);
      if (ret < 0) {
        return -ret;
      }
      opt_sb = sbuck;
    }

    RGWBucketPipeSyncStatusManager sync(store, source_zone, opt_sb, bucket);

    ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }
    ret = sync.init_sync_status(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BUCKET_SYNC_CHECKPOINT) {
    std::optional<rgw_zone_id> opt_source_zone;
    if (!source_zone.empty()) {
      opt_source_zone = source_zone;
    }
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    rgw_bucket bucket;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      return -ret;
    }

    if (!store->ctl()->bucket->bucket_imports_data(bucket_info.bucket, null_yield, dpp())) {
      std::cout << "Sync is disabled for bucket " << bucket_name << std::endl;
      return 0;
    }

    RGWBucketSyncPolicyHandlerRef handler;
    ret = store->ctl()->bucket->get_sync_policy_handler(std::nullopt, bucket, &handler, null_yield, dpp());
    if (ret < 0) {
      std::cerr << "ERROR: failed to get policy handler for bucket ("
          << bucket_info.bucket << "): r=" << ret << ": " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    auto timeout_at = ceph::coarse_mono_clock::now() + opt_timeout_sec;
    ret = rgw_bucket_sync_checkpoint(dpp(), store, *handler, bucket_info,
                                     opt_source_zone, opt_source_bucket,
                                     opt_retry_delay_ms, timeout_at);
    if (ret < 0) {
      ldpp_dout(dpp(), -1) << "bucket sync checkpoint failed: " << cpp_strerror(ret) << dendl;
      return -ret;
    }
  }

  if ((opt_cmd == OPT::BUCKET_SYNC_DISABLE) || (opt_cmd == OPT::BUCKET_SYNC_ENABLE)) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    } 
    if (opt_cmd == OPT::BUCKET_SYNC_DISABLE) {
      bucket_op.set_sync_bucket(false);
    } else {
      bucket_op.set_sync_bucket(true);
    }
    bucket_op.set_tenant(tenant);
    string err_msg;
    ret = RGWBucketAdminOp::sync_bucket(store, bucket_op, dpp(), &err_msg);
    if (ret < 0) {
      cerr << err_msg << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BUCKET_SYNC_INFO) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    rgw_bucket bucket;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      return -ret;
    }
    bucket_sync_info(store, bucket_info, std::cout);
  }

  if (opt_cmd == OPT::BUCKET_SYNC_STATUS) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    rgw_bucket bucket;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      return -ret;
    }
    bucket_sync_status(store, bucket_info, source_zone, opt_source_bucket, std::cout);
  }

  if (opt_cmd == OPT::BUCKET_SYNC_MARKERS) {
    if (source_zone.empty()) {
      cerr << "ERROR: source zone not specified" << std::endl;
      return EINVAL;
    }
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    rgw_bucket bucket;
    int ret = init_bucket_for_sync(tenant, bucket_name, bucket_id, bucket);
    if (ret < 0) {
      return -ret;
    }
    RGWBucketPipeSyncStatusManager sync(store, source_zone, opt_source_bucket, bucket);

    ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }
    ret = sync.read_sync_status(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
      return -ret;
    }

    map<int, rgw_bucket_shard_sync_info>& sync_status = sync.get_sync_status();

    encode_json("sync_status", sync_status, formatter.get());
    formatter->flush(cout);
  }

 if (opt_cmd == OPT::BUCKET_SYNC_RUN) {
    if (source_zone.empty()) {
      cerr << "ERROR: source zone not specified" << std::endl;
      return EINVAL;
    }
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    rgw_bucket bucket;
    int ret = init_bucket_for_sync(tenant, bucket_name, bucket_id, bucket);
    if (ret < 0) {
      return -ret;
    }
    RGWBucketPipeSyncStatusManager sync(store, source_zone, opt_source_bucket, bucket);

    ret = sync.init(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
      return -ret;
    }

    ret = sync.run(dpp());
    if (ret < 0) {
      cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BILOG_LIST) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    formatter->open_array_section("entries");
    bool truncated;
    int count = 0;
    if (max_entries < 0)
      max_entries = 1000;

    do {
      list<rgw_bi_log_entry> entries;
      ret = store->svc()->bilog_rados->log_list(dpp(), bucket_info, shard_id, marker, max_entries - count, entries, &truncated);
      if (ret < 0) {
        cerr << "ERROR: list_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }

      count += entries.size();

      for (list<rgw_bi_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
        rgw_bi_log_entry& entry = *iter;
        encode_json("entry", entry, formatter.get());

        marker = entry.id;
      }
      formatter->flush(cout);
    } while (truncated && count < max_entries);

    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::SYNC_ERROR_LIST) {
    if (max_entries < 0) {
      max_entries = 1000;
    }
    if (!start_date.empty()) {
      std::cerr << "start-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_date.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_marker.empty()) {
      std::cerr << "end-marker not allowed." << std::endl;
      return -EINVAL;
    }
    if (!start_marker.empty()) {
      if (marker.empty()) {
	marker = start_marker;
      } else {
	std::cerr << "start-marker and marker not both allowed." << std::endl;
	return -EINVAL;
      }
    }

    bool truncated;

    if (shard_id < 0) {
      shard_id = 0;
    }

    formatter->open_array_section("entries");

    for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) {
      formatter->open_object_section("shard");
      encode_json("shard_id", shard_id, formatter.get());
      formatter->open_array_section("entries");

      int count = 0;
      string oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX, shard_id);

      do {
        list<cls_log_entry> entries;
        ret = store->svc()->cls->timelog.list(dpp(), oid, {}, {}, max_entries - count, entries, marker, &marker, &truncated,
					      null_yield);
	if (ret == -ENOENT) {
	  break;
        }
        if (ret < 0) {
          cerr << "ERROR: svc.cls->timelog.list(): " << cpp_strerror(-ret) << std::endl;
          return -ret;
        }

        count += entries.size();

        for (auto& cls_entry : entries) {
          rgw_sync_error_info log_entry;

          auto iter = cls_entry.data.cbegin();
          try {
            decode(log_entry, iter);
          } catch (buffer::error& err) {
            cerr << "ERROR: failed to decode log entry" << std::endl;
            continue;
          }
          formatter->open_object_section("entry");
          encode_json("id", cls_entry.id, formatter.get());
          encode_json("section", cls_entry.section, formatter.get());
          encode_json("name", cls_entry.name, formatter.get());
          encode_json("timestamp", cls_entry.timestamp, formatter.get());
          encode_json("info", log_entry, formatter.get());
          formatter->close_section();
          formatter->flush(cout);
        }
      } while (truncated && count < max_entries);

      formatter->close_section();
      formatter->close_section();

      if (specified_shard_id) {
        break;
      }
    }

    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::SYNC_ERROR_TRIM) {
    if (!start_date.empty()) {
      std::cerr << "start-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_date.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!start_marker.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_marker.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }

    if (shard_id < 0) {
      shard_id = 0;
    }

    for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) {
      ret = trim_sync_error_log(shard_id, marker, trim_delay_ms);
      if (ret < 0) {
        cerr << "ERROR: sync error trim: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      if (specified_shard_id) {
        break;
      }
    }
  }

  if (opt_cmd == OPT::SYNC_GROUP_CREATE ||
      opt_cmd == OPT::SYNC_GROUP_MODIFY) {
    CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_status), "ERROR: --status is not specified (options: forbidden, allowed, enabled)", EINVAL);

    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    if (opt_cmd == OPT::SYNC_GROUP_MODIFY) {
      auto iter = sync_policy.groups.find(*opt_group_id);
      if (iter == sync_policy.groups.end()) {
        cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
        return ENOENT;
      }
    }

    auto& group = sync_policy.groups[*opt_group_id];
    group.id = *opt_group_id;

    if (opt_status) {
      if (!group.set_status(*opt_status)) {
        cerr << "ERROR: unrecognized status (options: forbidden, allowed, enabled)" << std::endl;
        return EINVAL;
      }
    }

    ret = sync_policy_ctx.write_policy();
    if (ret < 0) {
      return -ret;
    }

    show_result(sync_policy, zone_formatter.get(), cout);
  }

  if (opt_cmd == OPT::SYNC_GROUP_GET) {
    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    auto& groups = sync_policy.groups;

    if (!opt_group_id) {
      show_result(groups, zone_formatter.get(), cout);
    } else {
      auto iter = sync_policy.groups.find(*opt_group_id);
      if (iter == sync_policy.groups.end()) {
        cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
        return ENOENT;
      }

      show_result(iter->second, zone_formatter.get(), cout);
    }
  }

  if (opt_cmd == OPT::SYNC_GROUP_REMOVE) {
    CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);

    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    sync_policy.groups.erase(*opt_group_id);

    ret = sync_policy_ctx.write_policy();
    if (ret < 0) {
      return -ret;
    }

    {
      Formatter::ObjectSection os(*zone_formatter.get(), "result");
      encode_json("sync_policy", sync_policy, zone_formatter.get());
    }

    zone_formatter->flush(cout);
  }

  if (opt_cmd == OPT::SYNC_GROUP_FLOW_CREATE) {
    CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_flow_id), "ERROR: --flow-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_flow_type),
                           "ERROR: --flow-type not specified (options: symmetrical, directional)", EINVAL);
    CHECK_TRUE((symmetrical_flow_opt(*opt_flow_type) ||
                            directional_flow_opt(*opt_flow_type)),
                           "ERROR: --flow-type invalid (options: symmetrical, directional)", EINVAL);

    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    auto iter = sync_policy.groups.find(*opt_group_id);
    if (iter == sync_policy.groups.end()) {
      cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
      return ENOENT;
    }

    auto& group = iter->second;

    if (symmetrical_flow_opt(*opt_flow_type)) {
      CHECK_TRUE(require_non_empty_opt(opt_zone_ids), "ERROR: --zones not provided for symmetrical flow, or is empty", EINVAL);

      rgw_sync_symmetric_group *flow_group;

      group.data_flow.find_or_create_symmetrical(*opt_flow_id, &flow_group);

      for (auto& z : *opt_zone_ids) {
        flow_group->zones.insert(z);
      }
    } else { /* directional */
      CHECK_TRUE(require_non_empty_opt(opt_source_zone_id), "ERROR: --source-zone not provided for directional flow rule, or is empty", EINVAL);
      CHECK_TRUE(require_non_empty_opt(opt_dest_zone_id), "ERROR: --dest-zone not provided for directional flow rule, or is empty", EINVAL);

      rgw_sync_directional_rule *flow_rule;

      group.data_flow.find_or_create_directional(*opt_source_zone_id, *opt_dest_zone_id, &flow_rule);
    }

    ret = sync_policy_ctx.write_policy();
    if (ret < 0) {
      return -ret;
    }

    show_result(sync_policy, zone_formatter.get(), cout);
  }

  if (opt_cmd == OPT::SYNC_GROUP_FLOW_REMOVE) {
    CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_flow_id), "ERROR: --flow-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_flow_type),
                           "ERROR: --flow-type not specified (options: symmetrical, directional)", EINVAL);
    CHECK_TRUE((symmetrical_flow_opt(*opt_flow_type) ||
                            directional_flow_opt(*opt_flow_type)),
                           "ERROR: --flow-type invalid (options: symmetrical, directional)", EINVAL);

    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    auto iter = sync_policy.groups.find(*opt_group_id);
    if (iter == sync_policy.groups.end()) {
      cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
      return ENOENT;
    }

    auto& group = iter->second;

    if (symmetrical_flow_opt(*opt_flow_type)) {
      group.data_flow.remove_symmetrical(*opt_flow_id, opt_zone_ids);
    } else { /* directional */
      CHECK_TRUE(require_non_empty_opt(opt_source_zone_id), "ERROR: --source-zone not provided for directional flow rule, or is empty", EINVAL);
      CHECK_TRUE(require_non_empty_opt(opt_dest_zone_id), "ERROR: --dest-zone not provided for directional flow rule, or is empty", EINVAL);

      group.data_flow.remove_directional(*opt_source_zone_id, *opt_dest_zone_id);
    }
    
    ret = sync_policy_ctx.write_policy();
    if (ret < 0) {
      return -ret;
    }

    show_result(sync_policy, zone_formatter.get(), cout);
  }

  if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE ||
      opt_cmd == OPT::SYNC_GROUP_PIPE_MODIFY) {
    CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_pipe_id), "ERROR: --pipe-id not specified", EINVAL);
    if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE) {
      CHECK_TRUE(require_non_empty_opt(opt_source_zone_ids), "ERROR: --source-zones not provided or is empty; should be list of zones or '*'", EINVAL);
      CHECK_TRUE(require_non_empty_opt(opt_dest_zone_ids), "ERROR: --dest-zones not provided or is empty; should be list of zones or '*'", EINVAL);
    }

    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    auto iter = sync_policy.groups.find(*opt_group_id);
    if (iter == sync_policy.groups.end()) {
      cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
      return ENOENT;
    }

    auto& group = iter->second;

    rgw_sync_bucket_pipes *pipe;

    if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE) {
      group.find_pipe(*opt_pipe_id, true, &pipe);
    } else {
      if (!group.find_pipe(*opt_pipe_id, false, &pipe)) {
        cerr << "ERROR: could not find pipe '" << *opt_pipe_id << "'" << std::endl;
        return ENOENT;
      }
    }

    pipe->source.add_zones(*opt_source_zone_ids);
    pipe->source.set_bucket(opt_source_tenant,
                            opt_source_bucket_name,
                            opt_source_bucket_id);
    pipe->dest.add_zones(*opt_dest_zone_ids);
    pipe->dest.set_bucket(opt_dest_tenant,
                            opt_dest_bucket_name,
                            opt_dest_bucket_id);

    pipe->params.source.filter.set_prefix(opt_prefix, !!opt_prefix_rm);
    pipe->params.source.filter.set_tags(tags_add, tags_rm);
    if (opt_dest_owner) {
      pipe->params.dest.set_owner(*opt_dest_owner);
    }
    if (opt_storage_class) {
      pipe->params.dest.set_storage_class(*opt_storage_class);
    }
    if (opt_priority) {
      pipe->params.priority = *opt_priority;
    }
    if (opt_mode) {
      if (*opt_mode == "system") {
        pipe->params.mode = rgw_sync_pipe_params::MODE_SYSTEM;
      } else if (*opt_mode == "user") {
        pipe->params.mode = rgw_sync_pipe_params::MODE_USER;
      } else {
        cerr << "ERROR: bad mode value: should be one of the following: system, user" << std::endl;
        return EINVAL;
      }
    }

    if (!user_id.empty()) {
      pipe->params.user = user_id;
    } else if (pipe->params.user.empty()) {
      auto owner = sync_policy_ctx.get_owner();
      if (owner) {
        pipe->params.user = *owner;
      }
    }

    ret = sync_policy_ctx.write_policy();
    if (ret < 0) {
      return -ret;
    }

    show_result(sync_policy, zone_formatter.get(), cout);
  }

  if (opt_cmd == OPT::SYNC_GROUP_PIPE_REMOVE) {
    CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
    CHECK_TRUE(require_opt(opt_pipe_id), "ERROR: --pipe-id not specified", EINVAL);

    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    auto iter = sync_policy.groups.find(*opt_group_id);
    if (iter == sync_policy.groups.end()) {
      cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
      return ENOENT;
    }

    auto& group = iter->second;

    rgw_sync_bucket_pipes *pipe;

    if (!group.find_pipe(*opt_pipe_id, false, &pipe)) {
      cerr << "ERROR: could not find pipe '" << *opt_pipe_id << "'" << std::endl;
      return ENOENT;
    }

    if (opt_source_zone_ids) {
      pipe->source.remove_zones(*opt_source_zone_ids);
    }

    pipe->source.remove_bucket(opt_source_tenant,
                               opt_source_bucket_name,
                               opt_source_bucket_id);
    if (opt_dest_zone_ids) {
      pipe->dest.remove_zones(*opt_dest_zone_ids);
    }
    pipe->dest.remove_bucket(opt_dest_tenant,
                             opt_dest_bucket_name,
                             opt_dest_bucket_id);

    if (!(opt_source_zone_ids ||
          opt_source_tenant ||
          opt_source_bucket ||
          opt_source_bucket_id ||
          opt_dest_zone_ids ||
          opt_dest_tenant ||
          opt_dest_bucket ||
          opt_dest_bucket_id)) {
      group.remove_pipe(*opt_pipe_id);
    }

    ret = sync_policy_ctx.write_policy();
    if (ret < 0) {
      return -ret;
    }

    show_result(sync_policy, zone_formatter.get(), cout);
  }

  if (opt_cmd == OPT::SYNC_POLICY_GET) {
    SyncPolicyContext sync_policy_ctx(zonegroup_id, zonegroup_name, opt_bucket);
    ret = sync_policy_ctx.init();
    if (ret < 0) {
      return -ret;
    }
    auto& sync_policy = sync_policy_ctx.get_policy();

    show_result(sync_policy, zone_formatter.get(), cout);
  }

  if (opt_cmd == OPT::BILOG_TRIM) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    ret = store->svc()->bilog_rados->log_trim(dpp(), bucket_info, shard_id, start_marker, end_marker);
    if (ret < 0) {
      cerr << "ERROR: trim_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::BILOG_STATUS) {
    if (bucket_name.empty()) {
      cerr << "ERROR: bucket not specified" << std::endl;
      return EINVAL;
    }
    RGWBucketInfo bucket_info;
    int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
    if (ret < 0) {
      cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    map<int, string> markers;
    ret = store->svc()->bilog_rados->get_log_status(dpp(), bucket_info, shard_id,
						    &markers, null_yield);
    if (ret < 0) {
      cerr << "ERROR: get_bi_log_status(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    formatter->open_object_section("entries");
    encode_json("markers", markers, formatter.get());
    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::BILOG_AUTOTRIM) {
    RGWCoroutinesManager crs(store->ctx(), store->getRados()->get_cr_registry());
    RGWHTTPManager http(store->ctx(), crs.get_completion_mgr());
    int ret = http.start();
    if (ret < 0) {
      cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }

    rgw::BucketTrimConfig config;
    configure_bucket_trim(store->ctx(), config);

    rgw::BucketTrimManager trim(store, config);
    ret = trim.init();
    if (ret < 0) {
      cerr << "trim manager init failed with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }
    ret = crs.run(dpp(), trim.create_admin_bucket_trim_cr(&http));
    if (ret < 0) {
      cerr << "automated bilog trim failed with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::DATALOG_LIST) {
    formatter->open_array_section("entries");
    bool truncated;
    int count = 0;
    if (max_entries < 0)
      max_entries = 1000;
    if (!start_date.empty()) {
      std::cerr << "start-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_date.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_marker.empty()) {
      std::cerr << "end-marker not allowed." << std::endl;
      return -EINVAL;
    }
    if (!start_marker.empty()) {
      if (marker.empty()) {
	marker = start_marker;
      } else {
	std::cerr << "start-marker and marker not both allowed." << std::endl;
	return -EINVAL;
      }
    }

    auto datalog_svc = store->svc()->datalog_rados;
    RGWDataChangesLog::LogMarker log_marker;

    do {
      std::vector<rgw_data_change_log_entry> entries;
      if (specified_shard_id) {
        ret = datalog_svc->list_entries(dpp(), shard_id, max_entries - count,
					entries, marker,
					&marker, &truncated);
      } else {
        ret = datalog_svc->list_entries(dpp(), max_entries - count, entries,
					log_marker, &truncated);
      }
      if (ret < 0) {
        cerr << "ERROR: datalog_svc->list_entries(): " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }

      count += entries.size();

      for (const auto& entry : entries) {
        if (!extra_info) {
          encode_json("entry", entry.entry, formatter.get());
        } else {
          encode_json("entry", entry, formatter.get());
        }
      }
      formatter.get()->flush(cout);
    } while (truncated && count < max_entries);

    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::DATALOG_STATUS) {
    int i = (specified_shard_id ? shard_id : 0);

    formatter->open_array_section("entries");
    for (; i < g_ceph_context->_conf->rgw_data_log_num_shards; i++) {
      list<cls_log_entry> entries;

      RGWDataChangesLogInfo info;
      store->svc()->datalog_rados->get_info(dpp(), i, &info);

      ::encode_json("info", info, formatter.get());

      if (specified_shard_id)
        break;
    }

    formatter->close_section();
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::DATALOG_AUTOTRIM) {
    RGWCoroutinesManager crs(store->ctx(), store->getRados()->get_cr_registry());
    RGWHTTPManager http(store->ctx(), crs.get_completion_mgr());
    int ret = http.start();
    if (ret < 0) {
      cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }

    auto num_shards = g_conf()->rgw_data_log_num_shards;
    std::vector<std::string> markers(num_shards);
    ret = crs.run(dpp(), create_admin_data_log_trim_cr(dpp(), store, &http, num_shards, markers));
    if (ret < 0) {
      cerr << "automated datalog trim failed with " << cpp_strerror(ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::DATALOG_TRIM) {
    if (!start_date.empty()) {
      std::cerr << "start-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_date.empty()) {
      std::cerr << "end-date not allowed." << std::endl;
      return -EINVAL;
    }
    if (!start_marker.empty()) {
      std::cerr << "start-marker not allowed." << std::endl;
      return -EINVAL;
    }
    if (!end_marker.empty()) {
      if (marker.empty()) {
	marker = end_marker;
      } else {
	std::cerr << "end-marker and marker not both allowed." << std::endl;
	return -EINVAL;
      }
    }

    if (!specified_shard_id) {
      cerr << "ERROR: requires a --shard-id" << std::endl;
      return EINVAL;
    }

    if (marker.empty()) {
      cerr << "ERROR: requires a --marker" << std::endl;
      return EINVAL;
    }

    auto datalog = store->svc()->datalog_rados;
    ret = datalog->trim_entries(dpp(), shard_id, marker);

    if (ret < 0 && ret != -ENODATA) {
      cerr << "ERROR: trim_entries(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::DATALOG_TYPE) {
    if (!opt_log_type) {
      std::cerr << "log-type not specified." << std::endl;
      return -EINVAL;
    }
    auto datalog = static_cast<rgw::sal::RGWRadosStore*>(store)->svc()->datalog_rados;
    ret = datalog->change_format(dpp(), *opt_log_type, null_yield);
    if (ret < 0) {
      cerr << "ERROR: change_format(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::DATALOG_PRUNE) {
    auto datalog = static_cast<rgw::sal::RGWRadosStore*>(store)->svc()->datalog_rados;
    std::optional<uint64_t> through;
    ret = datalog->trim_generations(dpp(), through);

    if (ret < 0) {
      cerr << "ERROR: trim_generations(): " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    if (through) {
      std::cout << "Pruned " << *through << " empty generations." << std::endl;
    } else {
      std::cout << "No empty generations." << std::endl;
    }
  }

  bool quota_op = (opt_cmd == OPT::QUOTA_SET || opt_cmd == OPT::QUOTA_ENABLE || opt_cmd == OPT::QUOTA_DISABLE);

  if (quota_op) {
    if (bucket_name.empty() && user_id.empty()) {
      cerr << "ERROR: bucket name or uid is required for quota operation" << std::endl;
      return EINVAL;
    }

    if (!bucket_name.empty()) {
      if (!quota_scope.empty() && quota_scope != "bucket") {
        cerr << "ERROR: invalid quota scope specification." << std::endl;
        return EINVAL;
      }
      set_bucket_quota(store, opt_cmd, tenant, bucket_name,
                       max_size, max_objects, have_max_size, have_max_objects);
    } else if (!user_id.empty()) {
      if (quota_scope == "bucket") {
        return set_user_bucket_quota(opt_cmd, user, user_op, max_size, max_objects, have_max_size, have_max_objects);
      } else if (quota_scope == "user") {
        return set_user_quota(opt_cmd, user, user_op, max_size, max_objects, have_max_size, have_max_objects);
      } else {
        cerr << "ERROR: invalid quota scope specification. Please specify either --quota-scope=bucket, or --quota-scope=user" << std::endl;
        return EINVAL;
      }
    }
  }

  if (opt_cmd == OPT::MFA_CREATE) {
    rados::cls::otp::otp_info_t config;

    if (user_id.empty()) {
      cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
      return EINVAL;
    }

    if (totp_serial.empty()) {
      cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
      return EINVAL;
    }

    if (totp_seed.empty()) {
      cerr << "ERROR: TOTP device seed was not provided (via --totp-seed)" << std::endl;
      return EINVAL;
    }


    rados::cls::otp::SeedType seed_type;
    if (totp_seed_type == "hex") {
      seed_type = rados::cls::otp::OTP_SEED_HEX;
    } else if (totp_seed_type == "base32") {
      seed_type = rados::cls::otp::OTP_SEED_BASE32;
    } else {
      cerr << "ERROR: invalid seed type: " << totp_seed_type << std::endl;
      return EINVAL;
    }

    config.id = totp_serial;
    config.seed = totp_seed;
    config.seed_type = seed_type;

    if (totp_seconds > 0) {
      config.step_size = totp_seconds;
    }

    if (totp_window > 0) {
      config.window = totp_window;
    }

    real_time mtime = real_clock::now();
    string oid = store->svc()->cls->mfa.get_mfa_oid(user_id);

    int ret = store->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user_id),
					     mtime, &objv_tracker,
					     null_yield, dpp(),
					     MDLOG_STATUS_WRITE,
					     [&] {
      return store->svc()->cls->mfa.create_mfa(dpp(), user_id, config, &objv_tracker, mtime, null_yield);
    });
    if (ret < 0) {
      cerr << "MFA creation failed, error: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    
    RGWUserInfo& user_info = user_op.get_user_info();
    user_info.mfa_ids.insert(totp_serial);
    user_op.set_mfa_ids(user_info.mfa_ids);
    string err;
    ret = user.modify(dpp(), user_op, null_yield, &err);
    if (ret < 0) {
      cerr << "ERROR: failed storing user info, error: " << err << std::endl;
      return -ret;
    }
  }

 if (opt_cmd == OPT::MFA_REMOVE) {
    if (user_id.empty()) {
      cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
      return EINVAL;
    }

    if (totp_serial.empty()) {
      cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
      return EINVAL;
    }

    real_time mtime = real_clock::now();

    int ret = store->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user_id),
					     mtime, &objv_tracker,
					     null_yield, dpp(),
					     MDLOG_STATUS_WRITE,
					     [&] {
      return store->svc()->cls->mfa.remove_mfa(dpp(), user_id, totp_serial, &objv_tracker, mtime, null_yield);
    });
    if (ret < 0) {
      cerr << "MFA removal failed, error: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    RGWUserInfo& user_info = user_op.get_user_info();
    user_info.mfa_ids.erase(totp_serial);
    user_op.set_mfa_ids(user_info.mfa_ids);
    string err;
    ret = user.modify(dpp(), user_op, null_yield, &err);
    if (ret < 0) {
      cerr << "ERROR: failed storing user info, error: " << err << std::endl;
      return -ret;
    }
  }

 if (opt_cmd == OPT::MFA_GET) {
    if (user_id.empty()) {
      cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
      return EINVAL;
    }

    if (totp_serial.empty()) {
      cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
      return EINVAL;
    }

    rados::cls::otp::otp_info_t result;
    int ret = store->svc()->cls->mfa.get_mfa(dpp(), user_id, totp_serial, &result, null_yield);
    if (ret < 0) {
      if (ret == -ENOENT || ret == -ENODATA) {
        cerr << "MFA serial id not found" << std::endl;
      } else {
        cerr << "MFA retrieval failed, error: " << cpp_strerror(-ret) << std::endl;
      }
      return -ret;
    }
    formatter->open_object_section("result");
    encode_json("entry", result, formatter.get());
    formatter->close_section();
    formatter->flush(cout);
  }

 if (opt_cmd == OPT::MFA_LIST) {
    if (user_id.empty()) {
      cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
      return EINVAL;
    }

    list<rados::cls::otp::otp_info_t> result;
    int ret = store->svc()->cls->mfa.list_mfa(dpp(), user_id, &result, null_yield);
    if (ret < 0) {
      cerr << "MFA listing failed, error: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    formatter->open_object_section("result");
    encode_json("entries", result, formatter.get());
    formatter->close_section();
    formatter->flush(cout);
  }

 if (opt_cmd == OPT::MFA_CHECK) {
    if (user_id.empty()) {
      cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
      return EINVAL;
    }

    if (totp_serial.empty()) {
      cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
      return EINVAL;
    }

    if (totp_pin.empty()) {
      cerr << "ERROR: TOTP device serial number was not provided (via --totp-pin)" << std::endl;
      return EINVAL;
    }

    list<rados::cls::otp::otp_info_t> result;
    int ret = store->svc()->cls->mfa.check_mfa(dpp(), user_id, totp_serial, totp_pin.front(), null_yield);
    if (ret < 0) {
      cerr << "MFA check failed, error: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

    cout << "ok" << std::endl;
  }

 if (opt_cmd == OPT::MFA_RESYNC) {
    if (user_id.empty()) {
      cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
      return EINVAL;
    }

    if (totp_serial.empty()) {
      cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
      return EINVAL;
    }

    if (totp_pin.size() != 2) {
      cerr << "ERROR: missing two --totp-pin params (--totp-pin=<first> --totp-pin=<second>)" << std::endl;
      return EINVAL;
    }

    rados::cls::otp::otp_info_t config;
    int ret = store->svc()->cls->mfa.get_mfa(dpp(), user_id, totp_serial, &config, null_yield);
    if (ret < 0) {
      if (ret == -ENOENT || ret == -ENODATA) {
        cerr << "MFA serial id not found" << std::endl;
      } else {
        cerr << "MFA retrieval failed, error: " << cpp_strerror(-ret) << std::endl;
      }
      return -ret;
    }

    ceph::real_time now;

    ret = store->svc()->cls->mfa.otp_get_current_time(dpp(), user_id, &now, null_yield);
    if (ret < 0) {
      cerr << "ERROR: failed to fetch current time from osd: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    time_t time_ofs;

    ret = scan_totp(store->ctx(), now, config, totp_pin, &time_ofs);
    if (ret < 0) {
      if (ret == -ENOENT) {
        cerr << "failed to resync, TOTP values not found in range" << std::endl;
      } else {
        cerr << "ERROR: failed to scan for TOTP values: " << cpp_strerror(-ret) << std::endl;
      }
      return -ret;
    }

    config.time_ofs = time_ofs;

    /* now update the backend */
    real_time mtime = real_clock::now();

    ret = store->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user_id),
				         mtime, &objv_tracker,
				         null_yield, dpp(),
				         MDLOG_STATUS_WRITE,
				         [&] {
      return store->svc()->cls->mfa.create_mfa(dpp(), user_id, config, &objv_tracker, mtime, null_yield);
    });
    if (ret < 0) {
      cerr << "MFA update failed, error: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }

 }

 if (opt_cmd == OPT::RESHARD_STALE_INSTANCES_LIST) {
   if (!store->svc()->zone->can_reshard() && !yes_i_really_mean_it) {
     cerr << "Resharding disabled in a multisite env, stale instances unlikely from resharding" << std::endl;
     cerr << "These instances may not be safe to delete." << std::endl;
     cerr << "Use --yes-i-really-mean-it to force displaying these instances." << std::endl;
     return EINVAL;
   }

   ret = RGWBucketAdminOp::list_stale_instances(store, bucket_op, f, dpp());
   if (ret < 0) {
     cerr << "ERROR: listing stale instances" << cpp_strerror(-ret) << std::endl;
   }
 }

 if (opt_cmd == OPT::RESHARD_STALE_INSTANCES_DELETE) {
   if (!store->svc()->zone->can_reshard()) {
     cerr << "Resharding disabled in a multisite env. Stale instances are not safe to be deleted." << std::endl;
     return EINVAL;
   }

   ret = RGWBucketAdminOp::clear_stale_instances(store, bucket_op,f, dpp());
   if (ret < 0) {
     cerr << "ERROR: deleting stale instances" << cpp_strerror(-ret) << std::endl;
   }
 }

  if (opt_cmd == OPT::PUBSUB_TOPICS_LIST) {

    RGWPubSub ps(store, tenant);

    rgw_bucket bucket;

    if (!bucket_name.empty()) {
      rgw_pubsub_bucket_topics result;
      RGWBucketInfo bucket_info;
      int ret = init_bucket(tenant, bucket_name, bucket_id, bucket_info, bucket);
      if (ret < 0) {
        cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }

      auto b = ps.get_bucket(bucket_info.bucket);
      ret = b->get_topics(&result);
      if (ret < 0) {
        cerr << "ERROR: could not get topics: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      encode_json("result", result, formatter.get());
    } else {
      rgw_pubsub_topics result;
      int ret = ps.get_topics(&result);
      if (ret < 0) {
        cerr << "ERROR: could not get topics: " << cpp_strerror(-ret) << std::endl;
        return -ret;
      }
      encode_json("result", result, formatter.get());
    }
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::PUBSUB_TOPIC_GET) {
    if (topic_name.empty()) {
      cerr << "ERROR: topic name was not provided (via --topic)" << std::endl;
      return EINVAL;
    }

    RGWPubSub ps(store, tenant);

    rgw_pubsub_topic_subs topic;
    ret = ps.get_topic(topic_name, &topic);
    if (ret < 0) {
      cerr << "ERROR: could not get topic: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    encode_json("topic", topic, formatter.get());
    formatter->flush(cout);
  }

  if (opt_cmd == OPT::PUBSUB_TOPIC_RM) {
    if (topic_name.empty()) {
      cerr << "ERROR: topic name was not provided (via --topic)" << std::endl;
      return EINVAL;
    }

    RGWPubSub ps(store, tenant);

    ret = ps.remove_topic(dpp(), topic_name, null_yield);
    if (ret < 0) {
      cerr << "ERROR: could not remove topic: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::PUBSUB_SUB_GET) {
    if (get_tier_type(store) != "pubsub") {
      cerr << "ERROR: only pubsub tier type supports this command" << std::endl;
      return EINVAL;
    }
    if (sub_name.empty()) {
      cerr << "ERROR: subscription name was not provided (via --subscription)" << std::endl;
      return EINVAL;
    }

    RGWPubSub ps(store, tenant);

    rgw_pubsub_sub_config sub_conf;

    auto sub = ps.get_sub(sub_name);
    ret = sub->get_conf(&sub_conf);
    if (ret < 0) {
      cerr << "ERROR: could not get subscription info: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    encode_json("sub", sub_conf, formatter.get());
    formatter->flush(cout);
  }

 if (opt_cmd == OPT::PUBSUB_SUB_RM) {
    if (get_tier_type(store) != "pubsub") {
      cerr << "ERROR: only pubsub tier type supports this command" << std::endl;
      return EINVAL;
    }
    if (sub_name.empty()) {
      cerr << "ERROR: subscription name was not provided (via --subscription)" << std::endl;
      return EINVAL;
    }

    RGWPubSub ps(store, tenant);

    auto sub = ps.get_sub(sub_name);
    ret = sub->unsubscribe(dpp(), topic_name, null_yield);
    if (ret < 0) {
      cerr << "ERROR: could not get subscription info: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

 if (opt_cmd == OPT::PUBSUB_SUB_PULL) {
    if (get_tier_type(store) != "pubsub") {
      cerr << "ERROR: only pubsub tier type supports this command" << std::endl;
      return EINVAL;
    }
    if (sub_name.empty()) {
      cerr << "ERROR: subscription name was not provided (via --subscription)" << std::endl;
      return EINVAL;
    }

    RGWPubSub ps(store, tenant);

    if (!max_entries_specified) {
      max_entries = RGWPubSub::Sub::DEFAULT_MAX_EVENTS;
    }
    auto sub = ps.get_sub_with_events(sub_name);
    ret = sub->list_events(dpp(), marker, max_entries);
    if (ret < 0) {
      cerr << "ERROR: could not list events: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
    encode_json("result", *sub, formatter.get());
    formatter->flush(cout);
 }

 if (opt_cmd == OPT::PUBSUB_EVENT_RM) {
    if (get_tier_type(store) != "pubsub") {
      cerr << "ERROR: only pubsub tier type supports this command" << std::endl;
      return EINVAL;
    }
    if (sub_name.empty()) {
      cerr << "ERROR: subscription name was not provided (via --subscription)" << std::endl;
      return EINVAL;
    }
    if (event_id.empty()) {
      cerr << "ERROR: event id was not provided (via --event-id)" << std::endl;
      return EINVAL;
    }

    RGWPubSub ps(store, tenant);

    auto sub = ps.get_sub_with_events(sub_name);
    ret = sub->remove_event(dpp(), event_id);
    if (ret < 0) {
      cerr << "ERROR: could not remove event: " << cpp_strerror(-ret) << std::endl;
      return -ret;
    }
  }

  if (opt_cmd == OPT::SCRIPT_PUT) {
    if (!str_script_ctx) {
      cerr << "ERROR: context was not provided (via --context)" << std::endl;
      return EINVAL;
    }
    if (infile.empty()) {
      cerr << "ERROR: infile was not provided (via --infile)" << std::endl;
      return EINVAL;
    }
    bufferlist bl;
    auto rc = read_input(infile, bl);
    if (rc < 0) {
      cerr << "ERROR: failed to read script: '" << infile << "'. error: " << rc << std::endl;
      return -rc;
    }
    const std::string script = bl.to_str();
    std::string err_msg;
    if (!rgw::lua::verify(script, err_msg)) {
      cerr << "ERROR: script: '" << infile << "' has error: " << std::endl << err_msg << std::endl;
      return EINVAL;
    }
    const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
    if (script_ctx == rgw::lua::context::none) {
      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: preRequest, postRequest" <<  std::endl;
      return EINVAL;
    }
    rc = rgw::lua::write_script(dpp(), store, tenant, null_yield, script_ctx, script);
    if (rc < 0) {
      cerr << "ERROR: failed to put script. error: " << rc << std::endl;
      return -rc;
    }
  }

  if (opt_cmd == OPT::SCRIPT_GET) {
    if (!str_script_ctx) {
      cerr << "ERROR: context was not provided (via --context)" << std::endl;
      return EINVAL;
    }
    const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
    if (script_ctx == rgw::lua::context::none) {
      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: preRequest, postRequest" <<  std::endl;
      return EINVAL;
    }
    std::string script;
    const auto rc = rgw::lua::read_script(store, tenant, null_yield, script_ctx, script);
    if (rc == -ENOENT) {
      std::cout << "no script exists for context: " << *str_script_ctx << 
        (tenant.empty() ? "" : (" in tenant: " + tenant)) << std::endl;
    } else if (rc < 0) {
      cerr << "ERROR: failed to read script. error: " << rc << std::endl;
      return -rc;
    } else {
      std::cout << script << std::endl;
    }
  }
  
  if (opt_cmd == OPT::SCRIPT_RM) {
    if (!str_script_ctx) {
      cerr << "ERROR: context was not provided (via --context)" << std::endl;
      return EINVAL;
    }
    const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
    if (script_ctx == rgw::lua::context::none) {
      cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: preRequest, postRequest" <<  std::endl;
      return EINVAL;
    }
    const auto rc = rgw::lua::delete_script(dpp(), store, tenant, null_yield, script_ctx);
    if (rc < 0) {
      cerr << "ERROR: failed to remove script. error: " << rc << std::endl;
      return -rc;
    }
  }

  if (opt_cmd == OPT::SCRIPT_PACKAGE_ADD) {
#ifdef WITH_RADOSGW_LUA_PACKAGES
    if (!script_package) {
      cerr << "ERROR: lua package name was not provided (via --package)" << std::endl;
      return EINVAL;
    }
    const auto rc = rgw::lua::add_package(dpp(), store, null_yield, *script_package, bool(allow_compilation));
    if (rc < 0) {
      cerr << "ERROR: failed to add lua package: " << script_package << " .error: " << rc << std::endl;
      return -rc;
    }
#else
    cerr << "ERROR: adding lua packages is not permitted" << std::endl;
    return EPERM;
#endif
  }

  if (opt_cmd == OPT::SCRIPT_PACKAGE_RM) {
#ifdef WITH_RADOSGW_LUA_PACKAGES
    if (!script_package) {
      cerr << "ERROR: lua package name was not provided (via --package)" << std::endl;
      return EINVAL;
    }
    const auto rc = rgw::lua::remove_package(dpp(), store, null_yield, *script_package);
    if (rc == -ENOENT) {
      cerr << "WARNING: package " << script_package << " did not exists or already removed" << std::endl;
      return 0;
    }
    if (rc < 0) {
      cerr << "ERROR: failed to remove lua package: " << script_package << " .error: " << rc << std::endl;
      return -rc;
    }
#else
    cerr << "ERROR: removing lua packages in not permitted" << std::endl;
    return EPERM;
#endif
  }

  if (opt_cmd == OPT::SCRIPT_PACKAGE_LIST) {
#ifdef WITH_RADOSGW_LUA_PACKAGES
    rgw::lua::packages_t packages;
    const auto rc = rgw::lua::list_packages(dpp(), store, null_yield, packages);
    if (rc == -ENOENT) {
      std::cout << "no lua packages in allowlist" << std::endl;
    } else if (rc < 0) {
      cerr << "ERROR: failed to read lua packages allowlist. error: " << rc << std::endl;
      return rc;
    } else {
      for (const auto& package : packages) {
          std::cout << package << std::endl;
      }
    }
#else
    cerr << "ERROR: listing lua packages in not permitted" << std::endl;
    return EPERM;
#endif
  }

  return 0;
}