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

ua_run.cc « dird « src « core - github.com/bareos/bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e97b28dd8be6804b60d2bbf37a20b468651bc7b0 (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
/* BAREOS® - Backup Archiving REcovery Open Sourced

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

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

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.
*/
// Kern Sibbald, December MMI
/**
 * @file
 * BAREOS Director -- Run Command
 */
#include "include/bareos.h"
#include "dird.h"
#include "dird/director_jcr_impl.h"
#include "dird/job.h"
#include "dird/migration.h"
#include "dird/storage.h"
#include "dird/ua_db.h"
#include "dird/ua_input.h"
#include "dird/ua_select.h"
#include "dird/ua_run.h"
#include "lib/breg.h"
#include "lib/berrno.h"
#include "lib/edit.h"
#include "lib/keyword_table_s.h"
#include "lib/util.h"
#include "dird/jcr_util.h"

namespace directordaemon {

/* Forward referenced subroutines */
static void SelectJobLevel(UaContext* ua, JobControlRecord* jcr);
static bool DisplayJobParameters(UaContext* ua,
                                 JobControlRecord* jcr,
                                 RunContext& rc);
static void SelectWhereRegexp(UaContext* ua, JobControlRecord* jcr);
static bool ScanCommandLineArguments(UaContext* ua, RunContext& rc);
static bool ResetRestoreContext(UaContext* ua,
                                JobControlRecord* jcr,
                                RunContext& rc);
static int ModifyJobParameters(UaContext* ua,
                               JobControlRecord* jcr,
                               RunContext& rc);

/* Imported variables */
extern struct s_kw ReplaceOptions[];

/**
 * Rerun a job by jobid. Lookup the job data and rerun the job with that data.
 *
 * Returns: false on error
 *          true if OK
 */
static inline bool reRunJob(UaContext* ua, JobId_t JobId, bool yes, utime_t now)
{
  JobDbRecord jr;
  char dt[MAX_TIME_LENGTH];
  PoolMem cmdline(PM_MESSAGE);

  jr.JobId = JobId;
  ua->SendMsg("rerunning jobid %d\n", jr.JobId);
  if (!ua->db->GetJobRecord(ua->jcr, &jr)) {
    Jmsg(ua->jcr, M_WARNING, 0,
         _("Error getting Job record for Job rerun: ERR=%s\n"),
         ua->db->strerror());
    return false;
  }

  // Only perform rerun on JobTypes where it makes sense.
  switch (jr.JobType) {
    case JT_BACKUP:
    case JT_COPY:
    case JT_MIGRATE:
      break;
    default:
      return true;
  }

  if (jr.JobLevel == L_NONE) {
    Mmsg(cmdline, "run job=\"%s\"", jr.Name);
  } else {
    Mmsg(cmdline, "run job=\"%s\" level=\"%s\"", jr.Name,
         JobLevelToString(jr.JobLevel));
  }
  PmStrcpy(ua->cmd, cmdline);

  if (jr.ClientId) {
    ClientDbRecord cr;

    cr.ClientId = jr.ClientId;
    if (!ua->db->GetClientRecord(ua->jcr, &cr)) {
      Jmsg(ua->jcr, M_WARNING, 0,
           _("Error getting Client record for Job rerun: ERR=%s\n"),
           ua->db->strerror());
      return false;
    }
    Mmsg(cmdline, " client=\"%s\"", cr.Name);
    PmStrcat(ua->cmd, cmdline);
  }

  if (jr.PoolId) {
    PoolDbRecord pr;

    pr.PoolId = jr.PoolId;
    if (!ua->db->GetPoolRecord(ua->jcr, &pr)) {
      Jmsg(ua->jcr, M_WARNING, 0,
           _("Error getting Pool record for Job rerun: ERR=%s\n"),
           ua->db->strerror());
      return false;
    }

    // Source pool.
    switch (jr.JobType) {
      case JT_COPY:
      case JT_MIGRATE: {
        JobResource* job = NULL;

        job = ua->GetJobResWithName(jr.Name, false);
        if (job) {
          Mmsg(cmdline, " pool=\"%s\"", job->pool->resource_name_);
          PmStrcat(ua->cmd, cmdline);
        }
        break;
      }
      case JT_BACKUP:
        switch (jr.JobLevel) {
          case L_VIRTUAL_FULL: {
            JobResource* job = NULL;

            job = ua->GetJobResWithName(jr.Name, false);
            if (job) {
              Mmsg(cmdline, " pool=\"%s\"", job->pool->resource_name_);
              PmStrcat(ua->cmd, cmdline);
            }
            break;
          }
          default:
            Mmsg(cmdline, " pool=\"%s\"", pr.Name);
            PmStrcat(ua->cmd, cmdline);
            break;
        }
    }

    // Next pool.
    switch (jr.JobType) {
      case JT_COPY:
      case JT_MIGRATE:
        Mmsg(cmdline, " nextpool=\"%s\"", pr.Name);
        PmStrcat(ua->cmd, cmdline);
        break;
      case JT_BACKUP:
        switch (jr.JobLevel) {
          case L_VIRTUAL_FULL:
            Mmsg(cmdline, " nextpool=\"%s\"", pr.Name);
            PmStrcat(ua->cmd, cmdline);

            break;
          default:
            break;
        }
        break;
    }
  }

  if (jr.FileSetId) {
    FileSetDbRecord fs;

    fs.FileSetId = jr.FileSetId;
    if (!ua->db->GetFilesetRecord(ua->jcr, &fs)) {
      Jmsg(ua->jcr, M_WARNING, 0,
           _("Error getting FileSet record for Job rerun: ERR=%s\n"),
           ua->db->strerror());
      return false;
    }
    Mmsg(cmdline, " fileset=\"%s\"", fs.FileSet);
    PmStrcat(ua->cmd, cmdline);
  }

  bstrutime(dt, sizeof(dt), now);
  Mmsg(cmdline, " when=\"%s\"", dt);
  PmStrcat(ua->cmd, cmdline);

  if (yes) { PmStrcat(ua->cmd, " yes"); }

  Dmsg1(100, "rerun cmdline=%s\n", ua->cmd);

  ParseUaArgs(ua);
  return RunCmd(ua, ua->cmd);
}

RerunArguments GetRerunCmdlineArguments(UaContext* ua)
{
  RerunArguments rerunarguments{};
  // Determine what cmdline arguments are given.

  int s = FindArgWithValue(ua, NT_("since_jobid"));
  if (s > 0) { rerunarguments.since_jobid = str_to_int64(ua->argv[s]); }

  int u = FindArgWithValue(ua, NT_("until_jobid"));
  if (u > 0) { rerunarguments.until_jobid = str_to_int64(ua->argv[u]); }

  int d = FindArgWithValue(ua, NT_("days"));
  if (d > 0) { rerunarguments.days = str_to_int64(ua->argv[d]); }

  int h = FindArgWithValue(ua, NT_("hours"));
  if (h > 0) { rerunarguments.hours = str_to_int64(ua->argv[h]); }

  if (FindArg(ua, NT_("yes")) > 0) { rerunarguments.yes = true; }

  int j = FindArgWithValue(ua, NT_("jobid"));
  if (j < 0 && !(rerunarguments.days || rerunarguments.hours)
      && !rerunarguments.since_jobid) {
    ua->SendMsg("Please specify jobid, since_jobid, hours or days\n");
    rerunarguments.parsingerror = true;
    return rerunarguments;
  }
  if (j >= 0) {
    char delimiter = ',';
    std::vector<std::string> parsed_jobids
        = split_string(ua->argv[j], delimiter);
    for (const auto& jobid : parsed_jobids) {
      if (Is_a_number(jobid.c_str())) {
        rerunarguments.JobIds.push_back(str_to_int64(jobid.c_str()));
      } else {
        ua->SendMsg("Specified jobid \"%s\" is not valid\n", jobid.c_str());
        rerunarguments.JobIds.clear();
        rerunarguments.parsingerror = true;
        return rerunarguments;
      }
    }
  }
  if (j >= 0 && rerunarguments.since_jobid) {
    ua->SendMsg(
        "Please specify either jobid or since_jobid (and optionally "
        "until_jobid)\n");
    rerunarguments.parsingerror = true;
    return rerunarguments;
  }

  if (j >= 0 && (rerunarguments.days || rerunarguments.hours)) {
    ua->SendMsg("Please specify either jobid or a timeframe\n");
    rerunarguments.parsingerror = true;
    return rerunarguments;
  }

  return rerunarguments;
}

static time_t ConvertDaysHoursToSecs(const RerunArguments& rerunargs,
                                     utime_t now)
{
  const int secs_in_day = 86400;
  const int secs_in_hour = 3600;
  time_t schedtime
      = now - (rerunargs.days * secs_in_day + rerunargs.hours * secs_in_hour);
  return schedtime;
}

static std::string PrepareRerunSqlQuery(UaContext*,
                                        const RerunArguments& rerunargs,
                                        utime_t now)
{
  char dt[MAX_TIME_LENGTH];
  time_t schedtime = ConvertDaysHoursToSecs(rerunargs, now);
  bstrutime(dt, sizeof(dt), schedtime);

  std::string select{"SELECT JobId FROM Job WHERE JobStatus = 'f'"};
  if (rerunargs.since_jobid) {
    if (rerunargs.until_jobid) {
      select += " AND JobId >= " + std::to_string(rerunargs.since_jobid)
                + " AND JobId <= " + std::to_string(rerunargs.until_jobid);
    } else {
      select += " AND JobId >= " + std::to_string(rerunargs.since_jobid);
    }

  } else {
    select += " AND SchedTime > '" + std::string(dt) + "'";
  }
  select += " ORDER BY JobId";

  return select;
}

/**
 * Rerun a job selection.
 *
 * Returns: 0 on error
 *          1 if OK
 */
bool reRunCmd(UaContext* ua, const char*)
{
  if (!OpenClientDb(ua)) { return true; }
  // Determine what cmdline arguments are given.

  RerunArguments rerunargs = GetRerunCmdlineArguments(ua);

  if (rerunargs.parsingerror) { return false; }

  utime_t now = (utime_t)time(NULL);
  if ((rerunargs.days || rerunargs.hours) || rerunargs.since_jobid) {
    std::string select = PrepareRerunSqlQuery(ua, rerunargs, now);

    dbid_list ids;
    PoolMem query(PM_MESSAGE);
    Mmsg(query, select.c_str());
    ua->db->GetQueryDbids(ua->jcr, query, ids);

    if (!ids.size()) {
      ua->SendMsg("No jobids with the specified options were found.\n");
    } else {
      ua->SendMsg("The following ids were selected for rerun:\n");
      for (int i = 0; i < ids.num_ids; i++) {
        if (i > 0) {
          ua->SendMsg(",%d", ids.DBId[i]);
        } else {
          ua->SendMsg("%d", ids.DBId[i]);
        }
      }
      ua->SendMsg("\n");

      if (!rerunargs.yes
          && (!GetYesno(ua, _("rerun these jobids? (yes/no): "))
              || !ua->pint32_val)) {
        return false;
      }
      // Loop over all selected JobIds.
      for (int i = 0; i < ids.num_ids; i++) {
        rerunargs.JobIds.push_back(ids.DBId[i]);
      }
      for (const auto& jobid : rerunargs.JobIds) {
        if (!reRunJob(ua, jobid, rerunargs.yes, now)) { return false; }
      }
    }
  } else {
    for (const auto& jobid : rerunargs.JobIds) {
      if (!reRunJob(ua, jobid, rerunargs.yes, now)) { return false; }
    }
  }

  return true;
}

/**
 * For Backup and Verify Jobs
 *     run [job=]<job-name> level=<level-name>
 *
 *  Jobs
 *     run <job-name>
 *
 * Returns: 0 on error
 *          JobId if OK
 *
 */
int DoRunCmd(UaContext* ua, const char*)
{
  JobControlRecord* jcr = NULL;
  RunContext rc;
  int status, length;
  bool valid_response;
  bool do_pool_overrides = true;

  if (!OpenClientDb(ua)) { return 0; }

  if (!ScanCommandLineArguments(ua, rc)) { return 0; }

  if (FindArg(ua, NT_("fdcalled")) > 0) {
    jcr->file_bsock = ua->UA_sock->clone();
    ua->quit = true;
  }

  /*
   * Create JobControlRecord to run job.  NOTE!!! after this point, FreeJcr()
   * before returning.
   */
  if (!jcr) {
    jcr = NewDirectorJcr(DirdFreeJcr);
    SetJcrDefaults(jcr, rc.job);
    jcr->dir_impl->unlink_bsr
        = ua->jcr->dir_impl->unlink_bsr; /* copy unlink flag from caller */
    ua->jcr->dir_impl->unlink_bsr = false;
  }

  // Transfer JobIds to new restore Job
  if (ua->jcr->JobIds) {
    jcr->JobIds = ua->jcr->JobIds;
    ua->jcr->JobIds = NULL;
  }

  // Transfer selected restore tree to new restore Job
  if (ua->jcr->dir_impl->restore_tree_root) {
    jcr->dir_impl->restore_tree_root = ua->jcr->dir_impl->restore_tree_root;
    ua->jcr->dir_impl->restore_tree_root = NULL;
  }

try_again:
  if (!ResetRestoreContext(ua, jcr, rc)) { goto bail_out; }

  // Run without prompting?
  if (ua->batch || FindArg(ua, NT_("yes")) > 0) { goto start_job; }

  /*
   * When doing interactive runs perform the pool level overrides
   * early this way the user doesn't get nasty surprisses when
   * a level override changes the pool the data will be saved to
   * later. We only want to do these overrides once so we use
   * a tracking boolean do_pool_overrides to see if we still
   * need to do this (e.g. we pass by here multiple times when
   * the user interactivly changes options.
   */
  if (do_pool_overrides) {
    switch (jcr->getJobType()) {
      case JT_BACKUP:
        if (!jcr->is_JobLevel(L_VIRTUAL_FULL)) { ApplyPoolOverrides(jcr); }
        break;
      default:
        break;
    }
    do_pool_overrides = false;
  }

  /*
   * Prompt User to see if all run job parameters are correct, and
   * allow him to modify them.
   */
  if (!DisplayJobParameters(ua, jcr, rc)) { goto bail_out; }

  // Prompt User until we have a valid response.
  do {
    if (!GetCmd(ua, _("OK to run? (yes/mod/no): "))) { goto bail_out; }

    /*
     * Empty line equals yes, anything other we compare
     * the cmdline for the length of the given input unless
     * its mod or .mod where we compare only the keyword
     * and a space as it can be followed by a full cmdline
     * with new cmdline arguments that need to be parsed.
     */
    valid_response = false;
    length = strlen(ua->cmd);
    if (ua->cmd[0] == 0 || bstrncasecmp(ua->cmd, ".mod ", MIN(length, 5))
        || bstrncasecmp(ua->cmd, "mod ", MIN(length, 4))
        || bstrncasecmp(ua->cmd, NT_("yes"), length)
        || bstrncasecmp(ua->cmd, _("yes"), length)
        || bstrncasecmp(ua->cmd, NT_("no"), length)
        || bstrncasecmp(ua->cmd, _("no"), length)) {
      valid_response = true;
    }

    if (!valid_response) {
      ua->WarningMsg(_("Illegal response %s\n"), ua->cmd);
    }
  } while (!valid_response);

  // See if the .mod or mod has arguments.
  if (bstrncasecmp(ua->cmd, ".mod ", 5)
      || (bstrncasecmp(ua->cmd, "mod ", 4) && strlen(ua->cmd) > 6)) {
    ParseUaArgs(ua);
    rc.mod = true;
    if (!ScanCommandLineArguments(ua, rc)) { return 0; }
    goto try_again;
  }

  // Allow the user to modify the settings
  status = ModifyJobParameters(ua, jcr, rc);
  switch (status) {
    case 0:
      goto try_again;
    case 1:
      break;
    case -1:
      goto bail_out;
  }

  /*
   * For interactive runs we set IgnoreLevelPoolOverrides as we already
   * performed the actual overrrides.
   */
  jcr->dir_impl->IgnoreLevelPoolOverrides = true;

  if (ua->cmd[0] == 0 || bstrncasecmp(ua->cmd, NT_("yes"), strlen(ua->cmd))
      || bstrncasecmp(ua->cmd, _("yes"), strlen(ua->cmd))) {
    JobId_t JobId;
    Dmsg1(800, "Calling RunJob job=%x\n", jcr->dir_impl->res.job);

  start_job:
    Dmsg3(100, "JobId=%u using pool %s priority=%d\n", (int)jcr->JobId,
          jcr->dir_impl->res.pool->resource_name_, jcr->JobPriority);
    Dmsg1(900, "Running a job; its spool_data = %d\n",
          jcr->dir_impl->spool_data);

    JobId = RunJob(jcr);

    Dmsg4(100, "JobId=%u NewJobId=%d using pool %s priority=%d\n",
          (int)jcr->JobId, JobId, jcr->dir_impl->res.pool->resource_name_,
          jcr->JobPriority);

    jcr->dir_impl->job_trigger = JobTrigger::kUser;

    // For interactive runs we send a message to the audit log
    if (jcr->dir_impl->IgnoreLevelPoolOverrides) {
      char buf[50];
      ua->LogAuditEventInfoMsg(_("Job queued. JobId=%s"),
                               edit_int64(jcr->JobId, buf));
    }

    FreeJcr(jcr); /* release jcr */

    if (JobId == 0) {
      ua->ErrorMsg(_("Job failed.\n"));
    } else {
      char ed1[50];
      ua->send->ObjectStart("run");
      ua->send->ObjectKeyValue("jobid", edit_int64(JobId, ed1),
                               _("Job queued. JobId=%s\n"));
      ua->send->ObjectEnd("run");
    }

    return JobId;
  }

bail_out:
  ua->SendMsg(_("Job not run.\n"));
  FreeJcr(jcr);

  return 0; /* do not run */
}

bool RunCmd(UaContext* ua, const char*) { return (DoRunCmd(ua, ua->cmd) != 0); }

int ModifyJobParameters(UaContext* ua, JobControlRecord* jcr, RunContext& rc)
{
  int opt;

  // At user request modify parameters of job to be run.
  if (ua->cmd[0] != 0 && bstrncasecmp(ua->cmd, _("mod"), strlen(ua->cmd))) {
    StartPrompt(ua, _("Parameters to modify:\n"));

    AddPrompt(ua, _("Level"));   /* 0 */
    AddPrompt(ua, _("Storage")); /* 1 */
    AddPrompt(ua, _("Job"));     /* 2 */
    AddPrompt(ua, _("FileSet")); /* 3 */
    if (jcr->is_JobType(JT_RESTORE)) {
      AddPrompt(ua, _("Restore Client")); /* 4 */
    } else {
      AddPrompt(ua, _("Client")); /* 4 */
    }
    AddPrompt(ua, _("Backup Format")); /* 5 */
    AddPrompt(ua, _("When"));          /* 6 */
    AddPrompt(ua, _("Priority"));      /* 7 */
    if (jcr->is_JobType(JT_BACKUP) || jcr->is_JobType(JT_COPY)
        || jcr->is_JobType(JT_MIGRATE) || jcr->is_JobType(JT_VERIFY)) {
      AddPrompt(ua, _("Pool")); /* 8 */
      if (jcr->is_JobType(JT_MIGRATE) || jcr->is_JobType(JT_COPY)
          || (jcr->is_JobType(JT_BACKUP)
              && jcr->is_JobLevel(L_VIRTUAL_FULL))) { /* NextPool */
        AddPrompt(ua, _("NextPool"));                 /* 9 */
        if (jcr->is_JobType(JT_BACKUP)) {
          AddPrompt(ua, _("Plugin Options")); /* 10 */
        }
      } else if (jcr->is_JobType(JT_VERIFY)) {
        AddPrompt(ua, _("Verify Job")); /* 9 */
      } else if (jcr->is_JobType(JT_BACKUP)) {
        AddPrompt(ua, _("Plugin Options")); /* 9 */
      }
    } else if (jcr->is_JobType(JT_RESTORE)) {
      AddPrompt(ua, _("Bootstrap"));       /* 8 */
      AddPrompt(ua, _("Where"));           /* 9 */
      AddPrompt(ua, _("File Relocation")); /* 10 */
      AddPrompt(ua, _("Replace"));         /* 11 */
      AddPrompt(ua, _("JobId"));           /* 12 */
      AddPrompt(ua, _("Plugin Options"));  /* 13 */
    }

    switch (DoPrompt(ua, "", _("Select parameter to modify"), NULL, 0)) {
      case 0:
        /* Level */
        SelectJobLevel(ua, jcr);
        switch (jcr->getJobType()) {
          case JT_BACKUP:
            if (!rc.pool_override && !jcr->is_JobLevel(L_VIRTUAL_FULL)) {
              ApplyPoolOverrides(jcr, true);
              rc.pool = jcr->dir_impl->res.pool;
              rc.level_override = true;
            }
            break;
          default:
            break;
        }
        goto try_again;
      case 1:
        /* Storage */
        rc.store->store = select_storage_resource(ua);
        if (rc.store->store) {
          PmStrcpy(rc.store->store_source, _("user selection"));
          SetRwstorage(jcr, rc.store);
          goto try_again;
        }
        break;
      case 2:
        /* Job */
        rc.job = select_job_resource(ua);
        if (rc.job) {
          jcr->dir_impl->res.job = rc.job;
          SetJcrDefaults(jcr, rc.job);
          goto try_again;
        }
        break;
      case 3:
        /* FileSet */
        rc.fileset = select_fileset_resource(ua);
        if (rc.fileset) {
          jcr->dir_impl->res.fileset = rc.fileset;
          goto try_again;
        }
        break;
      case 4:
        /* Client */
        rc.client = select_client_resource(ua);
        if (rc.client) {
          jcr->dir_impl->res.client = rc.client;
          goto try_again;
        }
        break;
      case 5:
        /* Backup Format */
        if (GetCmd(ua, _("Please enter Backup Format: "))) {
          if (jcr->dir_impl->backup_format) {
            free(jcr->dir_impl->backup_format);
            jcr->dir_impl->backup_format = NULL;
          }
          jcr->dir_impl->backup_format = strdup(ua->cmd);
          goto try_again;
        }
        break;
      case 6:
        /* When */
        if (GetCmd(ua, _("Please enter desired start time as YYYY-MM-DD "
                         "HH:MM:SS (return for now): "))) {
          if (ua->cmd[0] == 0) {
            jcr->sched_time = time(NULL);
          } else {
            jcr->sched_time = StrToUtime(ua->cmd);
            if (jcr->sched_time == 0) {
              ua->SendMsg(_("Invalid time, using current time.\n"));
              jcr->sched_time = time(NULL);
            }
          }
          goto try_again;
        }
        break;
      case 7:
        /* Priority */
        if (GetPint(ua, _("Enter new Priority: "))) {
          if (!ua->pint32_val) {
            ua->SendMsg(_("Priority must be a positive integer.\n"));
          } else {
            jcr->JobPriority = ua->pint32_val;
          }
          goto try_again;
        }
        break;
      case 8:
        /* Pool or Bootstrap depending on JobType */
        if (jcr->is_JobType(JT_BACKUP) || jcr->is_JobType(JT_COPY)
            || jcr->is_JobType(JT_MIGRATE)
            || jcr->is_JobType(JT_VERIFY)) { /* Pool */
          rc.pool = select_pool_resource(ua);
          if (rc.pool) {
            jcr->dir_impl->res.pool = rc.pool;
            rc.level_override = false;
            rc.pool_override = true;
            Dmsg1(100, "Set new pool=%s\n",
                  jcr->dir_impl->res.pool->resource_name_);
            goto try_again;
          }
        } else {
          /* Bootstrap */
          if (GetCmd(ua, _("Please enter the Bootstrap file name: "))) {
            if (jcr->RestoreBootstrap) {
              free(jcr->RestoreBootstrap);
              jcr->RestoreBootstrap = NULL;
            }
            if (ua->cmd[0] != 0) {
              FILE* fd;

              jcr->RestoreBootstrap = strdup(ua->cmd);
              fd = fopen(jcr->RestoreBootstrap, "rb");
              if (!fd) {
                BErrNo be;
                ua->SendMsg(_("Warning cannot open %s: ERR=%s\n"),
                            jcr->RestoreBootstrap, be.bstrerror());
                free(jcr->RestoreBootstrap);
                jcr->RestoreBootstrap = NULL;
              } else {
                fclose(fd);
              }
            }
            goto try_again;
          }
        }
        break;
      case 9:
        /* NextPool/Verify Job/Where/Plugin Options depending on JobType */
        if (jcr->is_JobType(JT_MIGRATE) || jcr->is_JobType(JT_COPY)
            || (jcr->is_JobType(JT_BACKUP)
                && jcr->is_JobLevel(L_VIRTUAL_FULL))) { /* NextPool */
          rc.next_pool = select_pool_resource(ua);
          if (rc.next_pool) {
            jcr->dir_impl->res.next_pool = rc.next_pool;
            Dmsg1(100, "Set new next_pool=%s\n",
                  jcr->dir_impl->res.next_pool->resource_name_);
            goto try_again;
          }
        } else if (jcr->is_JobType(JT_VERIFY)) { /* Verify Job */
          rc.verify_job = select_job_resource(ua);
          if (rc.verify_job) { jcr->dir_impl->res.verify_job = rc.verify_job; }
          goto try_again;
        } else if (jcr->is_JobType(JT_RESTORE)) { /* Where */
          if (GetCmd(ua, _("Please enter the full path prefix for restore (/ "
                           "for none): "))) {
            if (jcr->RegexWhere) { /* cannot use regexwhere and where */
              free(jcr->RegexWhere);
              jcr->RegexWhere = NULL;
            }
            if (jcr->where) {
              free(jcr->where);
              jcr->where = NULL;
            }
            if (IsPathSeparator(ua->cmd[0]) && ua->cmd[1] == '\0') {
              ua->cmd[0] = 0;
            }
            jcr->where = strdup(ua->cmd);
            goto try_again;
          }
        } else { /* Plugin Options */
          if (GetCmd(ua, _("Please enter Plugin Options string: "))) {
            if (jcr->dir_impl->plugin_options) {
              free(jcr->dir_impl->plugin_options);
              jcr->dir_impl->plugin_options = NULL;
            }
            jcr->dir_impl->plugin_options = strdup(ua->cmd);
            goto try_again;
          }
        }
        break;
      case 10:
        /* File relocation/Plugin Options depending on JobType */
        if (jcr->is_JobType(JT_RESTORE)) {
          SelectWhereRegexp(ua, jcr);
          goto try_again;
        } else if (jcr->is_JobType(JT_BACKUP)) {
          if (GetCmd(ua, _("Please enter Plugin Options string: "))) {
            if (jcr->dir_impl->plugin_options) {
              free(jcr->dir_impl->plugin_options);
              jcr->dir_impl->plugin_options = NULL;
            }
            jcr->dir_impl->plugin_options = strdup(ua->cmd);
            goto try_again;
          }
        }
        break;
      case 11:
        /* Replace */
        StartPrompt(ua, _("Replace:\n"));
        for (int i = 0; ReplaceOptions[i].name; i++) {
          AddPrompt(ua, ReplaceOptions[i].name);
        }
        opt = DoPrompt(ua, "", _("Select replace option"), NULL, 0);
        if (opt >= 0) {
          rc.replace = ReplaceOptions[opt].name;
          jcr->dir_impl->replace = ReplaceOptions[opt].token;
        }
        goto try_again;
      case 12:
        /* JobId */
        rc.jid = NULL; /* force reprompt */
        jcr->dir_impl->RestoreJobId = 0;
        if (jcr->RestoreBootstrap) {
          ua->SendMsg(
              _("You must set the bootstrap file to NULL to be able to specify "
                "a JobId.\n"));
        }
        goto try_again;
      case 13:
        /* Plugin Options */
        if (GetCmd(ua, _("Please enter Plugin Options string: "))) {
          if (jcr->dir_impl->plugin_options) {
            free(jcr->dir_impl->plugin_options);
            jcr->dir_impl->plugin_options = NULL;
          }
          jcr->dir_impl->plugin_options = strdup(ua->cmd);
          goto try_again;
        }
        break;
      case -1: /* error or cancel */
        return -1;
      default:
        goto try_again;
    }
    return -1;
  }
  return 1;

  return -1;

try_again:
  return 0;
}

/**
 * Reset the restore context.
 * This subroutine can be called multiple times, so it must keep any prior
 * settings.
 */
static bool ResetRestoreContext(UaContext* ua,
                                JobControlRecord* jcr,
                                RunContext& rc)
{
  jcr->dir_impl->res.verify_job = rc.verify_job;
  jcr->dir_impl->res.previous_job = rc.previous_job;
  jcr->dir_impl->res.pool = rc.pool;
  jcr->dir_impl->res.next_pool = rc.next_pool;

  /*
   * See if an explicit pool override was performed.
   * If so set the pool_source to command line and
   * set the IgnoreLevelPoolOverrides so any level Pool
   * overrides are ignored.
   */
  if (rc.pool_name) {
    PmStrcpy(jcr->dir_impl->res.pool_source, _("command line"));
    jcr->dir_impl->IgnoreLevelPoolOverrides = true;
  } else if (!rc.level_override
             && jcr->dir_impl->res.pool != jcr->dir_impl->res.job->pool) {
    PmStrcpy(jcr->dir_impl->res.pool_source, _("user input"));
  }
  SetRwstorage(jcr, rc.store);

  if (rc.next_pool_name) {
    PmStrcpy(jcr->dir_impl->res.npool_source, _("command line"));
    jcr->dir_impl->res.run_next_pool_override = true;
  } else if (jcr->dir_impl->res.next_pool
             != jcr->dir_impl->res.pool->NextPool) {
    PmStrcpy(jcr->dir_impl->res.npool_source, _("user input"));
    jcr->dir_impl->res.run_next_pool_override = true;
  }

  jcr->dir_impl->res.client = rc.client;
  if (jcr->dir_impl->res.client) {
    PmStrcpy(jcr->client_name, rc.client->resource_name_);
  }
  jcr->dir_impl->res.fileset = rc.fileset;
  jcr->dir_impl->ExpectedFiles = rc.files;

  if (rc.catalog) {
    jcr->dir_impl->res.catalog = rc.catalog;
    PmStrcpy(jcr->dir_impl->res.catalog_source, _("user input"));
  }

  PmStrcpy(jcr->comment, rc.comment);

  if (rc.where) {
    if (jcr->where) { free(jcr->where); }
    jcr->where = strdup(rc.where);
    rc.where = NULL;
  }

  if (rc.regexwhere) {
    if (jcr->RegexWhere) { free(jcr->RegexWhere); }
    jcr->RegexWhere = strdup(rc.regexwhere);
    rc.regexwhere = NULL;
  }

  if (rc.when) {
    jcr->sched_time = StrToUtime(rc.when);
    if (jcr->sched_time == 0) {
      ua->SendMsg(_("Invalid time, using current time.\n"));
      jcr->sched_time = time(NULL);
    }
    rc.when = NULL;
  }

  if (rc.bootstrap) {
    if (jcr->RestoreBootstrap) { free(jcr->RestoreBootstrap); }
    jcr->RestoreBootstrap = strdup(rc.bootstrap);
    rc.bootstrap = NULL;
  }

  if (rc.plugin_options) {
    if (jcr->dir_impl->plugin_options) { free(jcr->dir_impl->plugin_options); }
    jcr->dir_impl->plugin_options = strdup(rc.plugin_options);
    rc.plugin_options = NULL;
  }

  if (rc.replace) {
    jcr->dir_impl->replace = 0;
    for (int i = 0; ReplaceOptions[i].name; i++) {
      if (Bstrcasecmp(rc.replace, ReplaceOptions[i].name)) {
        jcr->dir_impl->replace = ReplaceOptions[i].token;
      }
    }
    if (!jcr->dir_impl->replace) {
      ua->SendMsg(_("Invalid replace option: %s\n"), rc.replace);
      return false;
    }
  } else if (rc.job->replace) {
    jcr->dir_impl->replace = rc.job->replace;
  } else {
    jcr->dir_impl->replace = REPLACE_ALWAYS;
  }
  rc.replace = NULL;

  if (rc.Priority) {
    jcr->JobPriority = rc.Priority;
    rc.Priority = 0;
  }

  if (rc.since) {
    if (StrToUtime(rc.since) != 0) {
      if (!jcr->starttime_string) {
        jcr->starttime_string = GetPoolMemory(PM_MESSAGE);
      }
      PmStrcpy(jcr->starttime_string, rc.since);
      rc.since = NULL;
    } else {
      ua->SendMsg(_("Since option expects string in format \"yyyy-mm-dd "
                    "hh:mm:ss\", but is: %s\n"),
                  rc.since);
      return false;
    }
  }

  if (rc.cloned) {
    jcr->dir_impl->cloned = rc.cloned;
    rc.cloned = false;
  }

  // If pool changed, update migration write storage
  if (jcr->is_JobType(JT_MIGRATE) || jcr->is_JobType(JT_COPY)
      || (jcr->is_JobType(JT_BACKUP) && jcr->is_JobLevel(L_VIRTUAL_FULL))) {
    if (!SetMigrationWstorage(jcr, rc.pool, rc.next_pool,
                              _("Storage from Run NextPool override"))) {
      return false;
    }
  }
  rc.replace = ReplaceOptions[0].name;
  for (int i = 0; ReplaceOptions[i].name; i++) {
    if (ReplaceOptions[i].token == jcr->dir_impl->replace) {
      rc.replace = ReplaceOptions[i].name;
    }
  }

  if (rc.level_name) {
    if (!GetLevelFromName(jcr, rc.level_name)) {
      ua->SendMsg(_("Level \"%s\" not valid.\n"), rc.level_name);
      return false;
    }
    rc.level_name = NULL;
  }

  if (rc.jid) {
    if (jcr->is_JobType(JT_BACKUP) && jcr->is_JobLevel(L_VIRTUAL_FULL)) {
      if (!jcr->dir_impl->vf_jobids) {
        jcr->dir_impl->vf_jobids = GetPoolMemory(PM_MESSAGE);
      }
      PmStrcpy(jcr->dir_impl->vf_jobids, rc.jid);
    } else {
      // Note, this is also MigrateJobId and a VerifyJobId
      jcr->dir_impl->RestoreJobId = str_to_int64(rc.jid);
    }
    rc.jid = NULL;
  }

  if (rc.backup_format) {
    if (jcr->dir_impl->backup_format) { free(jcr->dir_impl->backup_format); }
    jcr->dir_impl->backup_format = strdup(rc.backup_format);
    rc.backup_format = NULL;
  }

  /*
   * Some options are not available through the menu
   * TODO: Add an advanced menu?
   */
  if (rc.spool_data_set) { jcr->dir_impl->spool_data = rc.spool_data; }

  if (rc.accurate_set) { jcr->accurate = rc.accurate; }

  /*
   * Used by migration jobs that can have the same name,
   * but can run at the same time
   */
  if (rc.ignoreduplicatecheck_set) {
    jcr->dir_impl->IgnoreDuplicateJobChecking = rc.ignoreduplicatecheck;
  }

  return true;
}

static void SelectWhereRegexp(UaContext* ua, JobControlRecord* jcr)
{
  alist<BareosRegex*>* regs;
  char *strip_prefix, *add_prefix, *add_suffix, *rwhere;
  strip_prefix = add_suffix = rwhere = add_prefix = NULL;

try_again_reg:
  ua->SendMsg(_("strip_prefix=%s add_prefix=%s add_suffix=%s\n"),
              NPRT(strip_prefix), NPRT(add_prefix), NPRT(add_suffix));

  StartPrompt(ua, _("This will replace your current Where value\n"));
  AddPrompt(ua, _("Strip prefix"));               /* 0 */
  AddPrompt(ua, _("Add prefix"));                 /* 1 */
  AddPrompt(ua, _("Add file suffix"));            /* 2 */
  AddPrompt(ua, _("Enter a regexp"));             /* 3 */
  AddPrompt(ua, _("Test filename manipulation")); /* 4 */
  AddPrompt(ua, _("Use this ?"));                 /* 5 */

  switch (DoPrompt(ua, "", _("Select parameter to modify"), NULL, 0)) {
    case 0:
      /* Strip prefix */
      if (GetCmd(ua, _("Please enter the path prefix to strip: "))) {
        if (strip_prefix) free(strip_prefix);
        strip_prefix = strdup(ua->cmd);
      }
      goto try_again_reg;
    case 1:
      /* Add prefix */
      if (GetCmd(ua, _("Please enter the path prefix to add (/ for none): "))) {
        if (IsPathSeparator(ua->cmd[0]) && ua->cmd[1] == '\0') {
          ua->cmd[0] = 0;
        }

        if (add_prefix) free(add_prefix);
        add_prefix = strdup(ua->cmd);
      }
      goto try_again_reg;
    case 2:
      /* Add suffix */
      if (GetCmd(ua, _("Please enter the file suffix to add: "))) {
        if (add_suffix) free(add_suffix);
        add_suffix = strdup(ua->cmd);
      }
      goto try_again_reg;
    case 3:
      /* Add rwhere */
      if (GetCmd(ua, _("Please enter a valid regexp (!from!to!): "))) {
        if (rwhere) free(rwhere);
        rwhere = strdup(ua->cmd);
      }
      goto try_again_reg;
    case 4:
      /* Test regexp */
      char* result;
      char* regexp;

      if (rwhere && rwhere[0] != '\0') {
        regs = get_bregexps(rwhere);
        ua->SendMsg(_("regexwhere=%s\n"), NPRT(rwhere));
      } else {
        int len
            = BregexpGetBuildWhereSize(strip_prefix, add_prefix, add_suffix);
        regexp = (char*)malloc(len * sizeof(char));
        bregexp_build_where(regexp, len, strip_prefix, add_prefix, add_suffix);
        regs = get_bregexps(regexp);
        ua->SendMsg(
            _("strip_prefix=%s add_prefix=%s add_suffix=%s result=%s\n"),
            NPRT(strip_prefix), NPRT(add_prefix), NPRT(add_suffix),
            NPRT(regexp));

        free(regexp);
      }

      if (!regs) {
        ua->SendMsg(_("Cannot use your regexp\n"));
        goto try_again_reg;
      }
      ua->SendMsg(_("Enter a period (.) to stop this test\n"));
      while (GetCmd(ua, _("Please enter filename to test: "))) {
        ApplyBregexps(ua->cmd, regs, &result);
        ua->SendMsg(_("%s -> %s\n"), ua->cmd, result);
      }
      FreeBregexps(regs);
      delete regs;
      goto try_again_reg;
    case 5:
      /* OK */
      break;
    case -1: /* error or cancel */
      goto bail_out_reg;
    default:
      goto try_again_reg;
  }

  /* replace the existing where */
  if (jcr->where) {
    free(jcr->where);
    jcr->where = NULL;
  }

  /* replace the existing regexwhere */
  if (jcr->RegexWhere) {
    free(jcr->RegexWhere);
    jcr->RegexWhere = NULL;
  }

  if (rwhere) {
    jcr->RegexWhere = strdup(rwhere);
  } else if (strip_prefix || add_prefix || add_suffix) {
    int len = BregexpGetBuildWhereSize(strip_prefix, add_prefix, add_suffix);
    jcr->RegexWhere = (char*)malloc(len * sizeof(char));
    bregexp_build_where(jcr->RegexWhere, len, strip_prefix, add_prefix,
                        add_suffix);
  }

  regs = get_bregexps(jcr->RegexWhere);
  if (regs) {
    FreeBregexps(regs);
    delete regs;
  } else {
    if (jcr->RegexWhere) {
      free(jcr->RegexWhere);
      jcr->RegexWhere = NULL;
    }
    ua->SendMsg(_("Cannot use your regexp.\n"));
  }

bail_out_reg:
  if (strip_prefix) { free(strip_prefix); }
  if (add_prefix) { free(add_prefix); }
  if (add_suffix) { free(add_suffix); }
  if (rwhere) { free(rwhere); }
}

static void SelectJobLevel(UaContext* ua, JobControlRecord* jcr)
{
  if (jcr->is_JobType(JT_BACKUP)) {
    StartPrompt(ua, _("Levels:\n"));
    //    AddPrompt(ua, _("Base"));
    AddPrompt(ua, _("Full"));
    AddPrompt(ua, _("Incremental"));
    AddPrompt(ua, _("Differential"));
    AddPrompt(ua, _("Since"));
    AddPrompt(ua, _("VirtualFull"));
    switch (DoPrompt(ua, "", _("Select level"), NULL, 0)) {
        //    case 0:
        //       jcr->JobLevel = L_BASE;
        //       break;
      case 0:
        jcr->setJobLevel(L_FULL);
        break;
      case 1:
        jcr->setJobLevel(L_INCREMENTAL);
        break;
      case 2:
        jcr->setJobLevel(L_DIFFERENTIAL);
        break;
      case 3:
        jcr->setJobLevel(L_SINCE);
        break;
      case 4:
        jcr->setJobLevel(L_VIRTUAL_FULL);
        break;
      default:
        break;
    }
  } else if (jcr->is_JobType(JT_VERIFY)) {
    StartPrompt(ua, _("Levels:\n"));
    AddPrompt(ua, _("Initialize Catalog"));
    AddPrompt(ua, _("Verify Catalog"));
    AddPrompt(ua, _("Verify Volume to Catalog"));
    AddPrompt(ua, _("Verify Disk to Catalog"));
    AddPrompt(ua, _("Verify Volume Data (not yet implemented)"));
    switch (DoPrompt(ua, "", _("Select level"), NULL, 0)) {
      case 0:
        jcr->setJobLevel(L_VERIFY_INIT);
        break;
      case 1:
        jcr->setJobLevel(L_VERIFY_CATALOG);
        break;
      case 2:
        jcr->setJobLevel(L_VERIFY_VOLUME_TO_CATALOG);
        break;
      case 3:
        jcr->setJobLevel(L_VERIFY_DISK_TO_CATALOG);
        break;
      case 4:
        jcr->setJobLevel(L_VERIFY_DATA);
        break;
      default:
        break;
    }
  } else {
    ua->WarningMsg(
        _("Level not appropriate for this Job. Cannot be changed.\n"));
  }
  return;
}

static bool DisplayJobParameters(UaContext* ua,
                                 JobControlRecord* jcr,
                                 RunContext& rc)
{
  char ec1[30];
  JobResource* job = rc.job;
  char dt[MAX_TIME_LENGTH];
  const char* verify_list = rc.verify_list;

  Dmsg1(800, "JobType=%c\n", jcr->getJobType());
  switch (jcr->getJobType()) {
    case JT_ADMIN:
      if (ua->api) {
        ua->signal(BNET_RUN_CMD);
        ua->SendMsg(
            "Type: Admin\n"
            "Title: Run Admin Job\n"
            "JobName:  %s\n"
            "FileSet:  %s\n"
            "Client:   %s\n"
            "Storage:  %s\n"
            "When:     %s\n"
            "Priority: %d\n",
            job->resource_name_, jcr->dir_impl->res.fileset->resource_name_,
            NPRT(jcr->dir_impl->res.client->resource_name_),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
      } else {
        ua->SendMsg(
            _("Run Admin Job\n"
              "JobName:  %s\n"
              "FileSet:  %s\n"
              "Client:   %s\n"
              "Storage:  %s\n"
              "When:     %s\n"
              "Priority: %d\n"),
            job->resource_name_, jcr->dir_impl->res.fileset->resource_name_,
            NPRT(jcr->dir_impl->res.client->resource_name_),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
      }
      jcr->setJobLevel(L_FULL);
      break;
    case JT_ARCHIVE:
      if (ua->api) {
        ua->signal(BNET_RUN_CMD);
        ua->SendMsg(
            "Type: Archive\n"
            "Title: Run Archive Job\n"
            "JobName:  %s\n"
            "FileSet:  %s\n"
            "Client:   %s\n"
            "Storage:  %s\n"
            "When:     %s\n"
            "Priority: %d\n",
            job->resource_name_, jcr->dir_impl->res.fileset->resource_name_,
            NPRT(jcr->dir_impl->res.client->resource_name_),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
      } else {
        ua->SendMsg(
            _("Run Archive Job\n"
              "JobName:  %s\n"
              "FileSet:  %s\n"
              "Client:   %s\n"
              "Storage:  %s\n"
              "When:     %s\n"
              "Priority: %d\n"),
            job->resource_name_, jcr->dir_impl->res.fileset->resource_name_,
            NPRT(jcr->dir_impl->res.client->resource_name_),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
      }
      jcr->setJobLevel(L_FULL);
      break;
    case JT_CONSOLIDATE:
      if (ua->api) {
        ua->signal(BNET_RUN_CMD);
        ua->SendMsg(
            "Type: Consolidate\n"
            "Title: Run Consolidate Job\n"
            "JobName:  %s\n"
            "FileSet:  %s\n"
            "Client:   %s\n"
            "Storage:  %s\n"
            "When:     %s\n"
            "Priority: %d\n",
            job->resource_name_, jcr->dir_impl->res.fileset->resource_name_,
            NPRT(jcr->dir_impl->res.client->resource_name_),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
      } else {
        ua->SendMsg(
            _("Run Consolidate Job\n"
              "JobName:  %s\n"
              "FileSet:  %s\n"
              "Client:   %s\n"
              "Storage:  %s\n"
              "When:     %s\n"
              "Priority: %d\n"),
            job->resource_name_, jcr->dir_impl->res.fileset->resource_name_,
            NPRT(jcr->dir_impl->res.client->resource_name_),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
      }
      jcr->setJobLevel(L_FULL);
      break;
    case JT_BACKUP:
    case JT_VERIFY:
      if (jcr->is_JobType(JT_BACKUP)) {
        bool is_virtual = jcr->is_JobLevel(L_VIRTUAL_FULL);

        if (ua->api) {
          ua->signal(BNET_RUN_CMD);
          ua->SendMsg(
              "Type: Backup\n"
              "Title: Run Backup Job\n"
              "JobName:  %s\n"
              "Level:    %s\n"
              "Client:   %s\n"
              "Format:   %s\n"
              "FileSet:  %s\n"
              "Pool:     %s\n"
              "%s%s%s"
              "Storage:  %s\n"
              "When:     %s\n"
              "Priority: %d\n"
              "%s%s%s",
              job->resource_name_, JobLevelToString(jcr->getJobLevel()),
              jcr->dir_impl->res.client->resource_name_,
              jcr->dir_impl->backup_format,
              jcr->dir_impl->res.fileset->resource_name_,
              NPRT(jcr->dir_impl->res.pool->resource_name_),
              is_virtual ? "NextPool: " : "",
              is_virtual ? (jcr->dir_impl->res.next_pool
                                ? jcr->dir_impl->res.next_pool->resource_name_
                                : _("*None*"))
                         : "",
              is_virtual ? "\n" : "",
              jcr->dir_impl->res.write_storage
                  ? jcr->dir_impl->res.write_storage->resource_name_
                  : _("*None*"),
              bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority,
              jcr->dir_impl->plugin_options ? "Plugin Options: " : "",
              jcr->dir_impl->plugin_options ? jcr->dir_impl->plugin_options
                                            : "",
              jcr->dir_impl->plugin_options ? "\n" : "");
        } else {
          ua->SendMsg(
              _("Run Backup job\n"
                "JobName:  %s\n"
                "Level:    %s\n"
                "Client:   %s\n"
                "Format:   %s\n"
                "FileSet:  %s\n"
                "Pool:     %s (From %s)\n"
                "%s%s%s%s%s"
                "Storage:  %s (From %s)\n"
                "When:     %s\n"
                "Priority: %d\n"
                "%s%s%s"),
              job->resource_name_, JobLevelToString(jcr->getJobLevel()),
              jcr->dir_impl->res.client->resource_name_,
              jcr->dir_impl->backup_format,
              jcr->dir_impl->res.fileset->resource_name_,
              NPRT(jcr->dir_impl->res.pool->resource_name_),
              jcr->dir_impl->res.pool_source, is_virtual ? "NextPool: " : "",
              is_virtual ? (jcr->dir_impl->res.next_pool
                                ? jcr->dir_impl->res.next_pool->resource_name_
                                : _("*None*"))
                         : "",
              is_virtual ? " (From " : "",
              is_virtual ? jcr->dir_impl->res.npool_source : "",
              is_virtual ? ")\n" : "",
              jcr->dir_impl->res.write_storage
                  ? jcr->dir_impl->res.write_storage->resource_name_
                  : _("*None*"),
              jcr->dir_impl->res.wstore_source,
              bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority,
              jcr->dir_impl->plugin_options ? "Plugin Options: " : "",
              jcr->dir_impl->plugin_options ? jcr->dir_impl->plugin_options
                                            : "",
              jcr->dir_impl->plugin_options ? "\n" : "");
        }
      } else { /* JT_VERIFY */
        JobDbRecord jr;
        const char* Name;
        if (jcr->dir_impl->res.verify_job) {
          Name = jcr->dir_impl->res.verify_job->resource_name_;
        } else if (jcr->dir_impl->RestoreJobId) { /* Display job name if jobid
                                                   * requested
                                                   */
          jr.JobId = jcr->dir_impl->RestoreJobId;
          if (!ua->db->GetJobRecord(jcr, &jr)) {
            ua->ErrorMsg(
                _("Could not get job record for selected JobId. ERR=%s"),
                ua->db->strerror());
            return false;
          }
          Name = jr.Job;
        } else {
          Name = "";
        }
        if (!verify_list) { verify_list = job->WriteVerifyList; }
        if (!verify_list) { verify_list = ""; }
        if (ua->api) {
          ua->signal(BNET_RUN_CMD);
          ua->SendMsg(
              "Type: Verify\n"
              "Title: Run Verify Job\n"
              "JobName:     %s\n"
              "Level:       %s\n"
              "Client:      %s\n"
              "FileSet:     %s\n"
              "Pool:        %s (From %s)\n"
              "Storage:     %s (From %s)\n"
              "Verify Job:  %s\n"
              "Verify List: %s\n"
              "When:        %s\n"
              "Priority:    %d\n",
              job->resource_name_, JobLevelToString(jcr->getJobLevel()),
              jcr->dir_impl->res.client->resource_name_,
              jcr->dir_impl->res.fileset->resource_name_,
              NPRT(jcr->dir_impl->res.pool->resource_name_),
              jcr->dir_impl->res.pool_source,
              jcr->dir_impl->res.read_storage->resource_name_,
              jcr->dir_impl->res.rstore_source, Name, verify_list,
              bstrutime(dt, sizeof(dt), jcr->sched_time), jcr->JobPriority);
        } else {
          ua->SendMsg(_("Run Verify Job\n"
                        "JobName:     %s\n"
                        "Level:       %s\n"
                        "Client:      %s\n"
                        "FileSet:     %s\n"
                        "Pool:        %s (From %s)\n"
                        "Storage:     %s (From %s)\n"
                        "Verify Job:  %s\n"
                        "Verify List: %s\n"
                        "When:        %s\n"
                        "Priority:    %d\n"),
                      job->resource_name_, JobLevelToString(jcr->getJobLevel()),
                      jcr->dir_impl->res.client->resource_name_,
                      jcr->dir_impl->res.fileset->resource_name_,
                      NPRT(jcr->dir_impl->res.pool->resource_name_),
                      jcr->dir_impl->res.pool_source,
                      jcr->dir_impl->res.read_storage->resource_name_,
                      jcr->dir_impl->res.rstore_source, Name, verify_list,
                      bstrutime(dt, sizeof(dt), jcr->sched_time),
                      jcr->JobPriority);
        }
      }
      break;
    case JT_RESTORE:
      if (jcr->dir_impl->RestoreJobId == 0 && !jcr->RestoreBootstrap) {
        if (rc.jid) {
          jcr->dir_impl->RestoreJobId = str_to_int64(rc.jid);
        } else {
          if (!GetPint(ua, _("Please enter a JobId for restore: "))) {
            return false;
          }
          std::string jobIdInput = std::to_string(ua->int64_val);
          if (!ua->db->FindJobById(jcr, jobIdInput)) {
            ua->SendMsg("JobId %s not found in catalog. \n",
                        jobIdInput.c_str());
            return false;
          }

          jcr->dir_impl->RestoreJobId = ua->int64_val;
        }
      }
      jcr->setJobLevel(L_FULL); /* default level */
      Dmsg1(800, "JobId to restore=%d\n", jcr->dir_impl->RestoreJobId);
      if (jcr->dir_impl->RestoreJobId == 0) {
        /* RegexWhere is take before RestoreWhere */
        if (jcr->RegexWhere || (job->RegexWhere && !jcr->where)) {
          if (ua->api) {
            ua->signal(BNET_RUN_CMD);
            ua->SendMsg(
                "Type: Restore\n"
                "Title: Run Restore Job\n"
                "JobName:         %s\n"
                "Bootstrap:       %s\n"
                "RegexWhere:      %s\n"
                "Replace:         %s\n"
                "FileSet:         %s\n"
                "Backup Client:   %s\n"
                "Restore Client:  %s\n"
                "Format:          %s\n"
                "Storage:         %s\n"
                "When:            %s\n"
                "Catalog:         %s\n"
                "Priority:        %d\n"
                "Plugin Options:  %s\n",
                job->resource_name_, NPRT(jcr->RestoreBootstrap),
                jcr->RegexWhere ? jcr->RegexWhere : job->RegexWhere, rc.replace,
                jcr->dir_impl->res.fileset->resource_name_, rc.client_name,
                jcr->dir_impl->res.client->resource_name_,
                jcr->dir_impl->backup_format,
                jcr->dir_impl->res.read_storage->resource_name_,
                bstrutime(dt, sizeof(dt), jcr->sched_time),
                jcr->dir_impl->res.catalog->resource_name_, jcr->JobPriority,
                NPRT(jcr->dir_impl->plugin_options));
          } else {
            ua->SendMsg(_("Run Restore job\n"
                          "JobName:         %s\n"
                          "Bootstrap:       %s\n"
                          "RegexWhere:      %s\n"
                          "Replace:         %s\n"
                          "FileSet:         %s\n"
                          "Backup Client:   %s\n"
                          "Restore Client:  %s\n"
                          "Format:          %s\n"
                          "Storage:         %s\n"
                          "When:            %s\n"
                          "Catalog:         %s\n"
                          "Priority:        %d\n"
                          "Plugin Options:  %s\n"),
                        job->resource_name_, NPRT(jcr->RestoreBootstrap),
                        jcr->RegexWhere ? jcr->RegexWhere : job->RegexWhere,
                        rc.replace, jcr->dir_impl->res.fileset->resource_name_,
                        rc.client_name,
                        jcr->dir_impl->res.client->resource_name_,
                        jcr->dir_impl->backup_format,
                        jcr->dir_impl->res.read_storage->resource_name_,
                        bstrutime(dt, sizeof(dt), jcr->sched_time),
                        jcr->dir_impl->res.catalog->resource_name_,
                        jcr->JobPriority, NPRT(jcr->dir_impl->plugin_options));
          }
        } else {
          if (ua->api) {
            ua->signal(BNET_RUN_CMD);
            ua->SendMsg(
                "Type: Restore\n"
                "Title: Run Restore job\n"
                "JobName:         %s\n"
                "Bootstrap:       %s\n"
                "Where:           %s\n"
                "Replace:         %s\n"
                "FileSet:         %s\n"
                "Backup Client:   %s\n"
                "Restore Client:  %s\n"
                "Format:          %s\n"
                "Storage:         %s\n"
                "When:            %s\n"
                "Catalog:         %s\n"
                "Priority:        %d\n"
                "Plugin Options:  %s\n",
                job->resource_name_, NPRT(jcr->RestoreBootstrap),
                jcr->where ? jcr->where : NPRT(job->RestoreWhere), rc.replace,
                jcr->dir_impl->res.fileset->resource_name_, rc.client_name,
                jcr->dir_impl->res.client->resource_name_,
                jcr->dir_impl->backup_format,
                jcr->dir_impl->res.read_storage->resource_name_,
                bstrutime(dt, sizeof(dt), jcr->sched_time),
                jcr->dir_impl->res.catalog->resource_name_, jcr->JobPriority,
                NPRT(jcr->dir_impl->plugin_options));
          } else {
            ua->SendMsg(_("Run Restore job\n"
                          "JobName:         %s\n"
                          "Bootstrap:       %s\n"
                          "Where:           %s\n"
                          "Replace:         %s\n"
                          "FileSet:         %s\n"
                          "Backup Client:   %s\n"
                          "Restore Client:  %s\n"
                          "Format:          %s\n"
                          "Storage:         %s\n"
                          "When:            %s\n"
                          "Catalog:         %s\n"
                          "Priority:        %d\n"
                          "Plugin Options:  %s\n"),
                        job->resource_name_, NPRT(jcr->RestoreBootstrap),
                        jcr->where ? jcr->where : NPRT(job->RestoreWhere),
                        rc.replace, jcr->dir_impl->res.fileset->resource_name_,
                        rc.client_name,
                        jcr->dir_impl->res.client->resource_name_,
                        jcr->dir_impl->backup_format,
                        jcr->dir_impl->res.read_storage->resource_name_,
                        bstrutime(dt, sizeof(dt), jcr->sched_time),
                        jcr->dir_impl->res.catalog->resource_name_,
                        jcr->JobPriority, NPRT(jcr->dir_impl->plugin_options));
          }
        }

      } else {
        if (ua->api) ua->signal(BNET_RUN_CMD);
        ua->SendMsg(_("Run Restore job\n"
                      "JobName:    %s\n"
                      "Bootstrap:  %s\n"),
                    job->resource_name_, NPRT(jcr->RestoreBootstrap));

        /* RegexWhere is take before RestoreWhere */
        if (jcr->RegexWhere || (job->RegexWhere && !jcr->where)) {
          ua->SendMsg(_("RegexWhere: %s\n"),
                      jcr->RegexWhere ? jcr->RegexWhere : job->RegexWhere);
        } else {
          ua->SendMsg(_("Where:      %s\n"),
                      jcr->where ? jcr->where : NPRT(job->RestoreWhere));
        }

        ua->SendMsg(_("Replace:         %s\n"
                      "Client:          %s\n"
                      "Format:          %s\n"
                      "Storage:         %s\n"
                      "JobId:           %s\n"
                      "When:            %s\n"
                      "Catalog:         %s\n"
                      "Priority:        %d\n"
                      "Plugin Options:  %s\n"),
                    rc.replace, jcr->dir_impl->res.client->resource_name_,
                    jcr->dir_impl->backup_format,
                    jcr->dir_impl->res.read_storage->resource_name_,
                    (jcr->dir_impl->RestoreJobId == 0)
                        ? _("*None*")
                        : edit_uint64(jcr->dir_impl->RestoreJobId, ec1),
                    bstrutime(dt, sizeof(dt), jcr->sched_time),
                    jcr->dir_impl->res.catalog->resource_name_,
                    jcr->JobPriority, NPRT(jcr->dir_impl->plugin_options));
      }
      break;
    case JT_COPY:
    case JT_MIGRATE:
      const char* prt_type;

      jcr->setJobLevel(L_FULL); /* default level */
      if (ua->api) {
        ua->signal(BNET_RUN_CMD);
        if (jcr->is_JobType(JT_COPY)) {
          prt_type = _("Type: Copy\nTitle: Run Copy Job\n");
        } else {
          prt_type = _("Type: Migration\nTitle: Run Migration Job\n");
        }
        ua->SendMsg(
            "%s"
            "JobName:       %s\n"
            "Bootstrap:     %s\n"
            "Read Storage:  %s\n"
            "Pool:          %s\n"
            "Write Storage: %s\n"
            "NextPool:      %s\n"
            "JobId:         %s\n"
            "When:          %s\n"
            "Catalog:       %s\n"
            "Priority:      %d\n",
            prt_type, job->resource_name_, NPRT(jcr->RestoreBootstrap),
            jcr->dir_impl->res.read_storage
                ? jcr->dir_impl->res.read_storage->resource_name_
                : _("*None*"),
            NPRT(jcr->dir_impl->res.pool->resource_name_),
            jcr->dir_impl->res.next_pool
                ? jcr->dir_impl->res.next_pool->resource_name_
                : _("*None*"),
            jcr->dir_impl->res.write_storage
                ? jcr->dir_impl->res.write_storage->resource_name_
                : _("*None*"),
            (jcr->dir_impl->MigrateJobId == 0)
                ? _("*None*")
                : edit_uint64(jcr->dir_impl->MigrateJobId, ec1),
            bstrutime(dt, sizeof(dt), jcr->sched_time),
            jcr->dir_impl->res.catalog->resource_name_, jcr->JobPriority);
      } else {
        if (jcr->is_JobType(JT_COPY)) {
          prt_type = _("Run Copy job\n");
        } else {
          prt_type = _("Run Migration job\n");
        }
        ua->SendMsg(_("%s"
                      "JobName:       %s\n"
                      "Bootstrap:     %s\n"
                      "Read Storage:  %s (From %s)\n"
                      "Pool:          %s (From %s)\n"
                      "Write Storage: %s (From %s)\n"
                      "NextPool:      %s (From %s)\n"
                      "JobId:         %s\n"
                      "When:          %s\n"
                      "Catalog:       %s\n"
                      "Priority:      %d\n"),
                    prt_type, job->resource_name_, NPRT(jcr->RestoreBootstrap),
                    jcr->dir_impl->res.read_storage
                        ? jcr->dir_impl->res.read_storage->resource_name_
                        : _("*None*"),
                    jcr->dir_impl->res.rstore_source,
                    NPRT(jcr->dir_impl->res.pool->resource_name_),
                    jcr->dir_impl->res.pool_source,
                    jcr->dir_impl->res.write_storage
                        ? jcr->dir_impl->res.write_storage->resource_name_
                        : _("*None*"),
                    jcr->dir_impl->res.wstore_source,
                    jcr->dir_impl->res.next_pool
                        ? jcr->dir_impl->res.next_pool->resource_name_
                        : _("*None*"),
                    NPRT(jcr->dir_impl->res.npool_source),
                    jcr->dir_impl->MigrateJobId == 0
                        ? _("*None*")
                        : edit_uint64(jcr->dir_impl->MigrateJobId, ec1),
                    bstrutime(dt, sizeof(dt), jcr->sched_time),
                    jcr->dir_impl->res.catalog->resource_name_,
                    jcr->JobPriority);
      }
      break;
    default:
      ua->ErrorMsg(_("Unknown Job Type=%d\n"), jcr->getJobType());
      return false;
  }
  return true;
}

static bool ScanCommandLineArguments(UaContext* ua, RunContext& rc)
{
  bool kw_ok;
  int i, j;
  static const char* kw[]
      = {                 /* command line arguments */
         "job",           /* 0 */
         "jobid",         /* 1 */
         "client",        /* 2 */
         "fd",            /* 3 */
         "fileset",       /* 4 */
         "level",         /* 5 */
         "storage",       /* 6 */
         "sd",            /* 7 */
         "regexwhere",    /* 8 - where string as a bregexp */
         "where",         /* 9 */
         "bootstrap",     /* 10 */
         "replace",       /* 11 */
         "when",          /* 12 */
         "priority",      /* 13 */
         "yes",           /* 14 -- if you change this change YES_POS too */
         "verifyjob",     /* 15 */
         "files",         /* 16 - number of files to restore */
         "catalog",       /* 17 - override catalog */
         "since",         /* 18 - since */
         "cloned",        /* 19 - cloned */
         "verifylist",    /* 20 - verify output list */
         "migrationjob",  /* 21 - migration job name */
         "pool",          /* 22 */
         "nextpool",      /* 23 */
         "backupclient",  /* 24 */
         "restoreclient", /* 25 */
         "pluginoptions", /* 26 */
         "spooldata",     /* 27 */
         "comment",       /* 28 */
         "ignoreduplicatecheck", /* 29 */
         "accurate",             /* 30 */
         "backupformat",         /* 31 */
         NULL};

#define YES_POS 14

  rc.catalog_name = NULL;
  rc.job_name = NULL;
  rc.pool_name = NULL;
  rc.next_pool_name = NULL;
  rc.StoreName = NULL;
  rc.client_name = NULL;
  rc.restore_client_name = NULL;
  rc.fileset_name = NULL;
  rc.verify_job_name = NULL;
  rc.previous_job_name = NULL;
  rc.accurate_set = false;
  rc.spool_data_set = false;
  rc.ignoreduplicatecheck = false;
  rc.comment = NULL;
  rc.backup_format = NULL;

  for (i = 1; i < ua->argc; i++) {
    Dmsg2(800, "Doing arg %d = %s\n", i, ua->argk[i]);
    kw_ok = false;

    // Keep looking until we find a good keyword
    for (j = 0; !kw_ok && kw[j]; j++) {
      if (Bstrcasecmp(ua->argk[i], kw[j])) {
        // Note, yes and run have no value, so do not fail
        if (!ua->argv[i] && j != YES_POS /*yes*/) {
          ua->SendMsg(_("Value missing for keyword %s\n"), ua->argk[i]);
          return false;
        }
        Dmsg1(800, "Got keyword=%s\n", NPRT(kw[j]));
        switch (j) {
          case 0: /* job */
            if (rc.job_name) {
              ua->SendMsg(_("Job name specified twice.\n"));
              return false;
            }
            rc.job_name = ua->argv[i];
            kw_ok = true;
            break;
          case 1: /* JobId */ {
            if (rc.jid && !rc.mod) {
              ua->SendMsg(_("JobId specified twice.\n"));
              return false;
            }
            rc.jid = ua->argv[i];
            std::vector jobIdList = split_string(rc.jid, ',');
            for (const auto& jobId : jobIdList) {
              if (!ua->db->FindJobById(ua->jcr, jobId)) {
                ua->SendMsg("JobId %s not found in catalog. \n", jobId.c_str());
                return false;
              }
            }

            kw_ok = true;
            break;
          }
          case 2: /* client */
          case 3: /* fd */
            if (rc.client_name) {
              ua->SendMsg(_("Client specified twice.\n"));
              return false;
            }
            rc.client_name = ua->argv[i];
            kw_ok = true;
            break;
          case 4: /* fileset */
            if (rc.fileset_name) {
              ua->SendMsg(_("FileSet specified twice.\n"));
              return false;
            }
            rc.fileset_name = ua->argv[i];
            kw_ok = true;
            break;
          case 5: /* level */
            if (rc.level_name) {
              ua->SendMsg(_("Level specified twice.\n"));
              return false;
            }
            rc.level_name = ua->argv[i];
            kw_ok = true;
            break;
          case 6: /* storage */
          case 7: /* sd */
            if (rc.StoreName) {
              ua->SendMsg(_("Storage specified twice.\n"));
              return false;
            }
            rc.StoreName = ua->argv[i];
            kw_ok = true;
            break;
          case 8: /* regexwhere */
            if ((rc.regexwhere || rc.where) && !rc.mod) {
              ua->SendMsg(_("RegexWhere or Where specified twice.\n"));
              return false;
            }
            rc.regexwhere = ua->argv[i];
            if (!ua->AclAccessOk(Where_ACL, rc.regexwhere, true)) {
              ua->SendMsg(
                  _("No authorization for \"regexwhere\" specification.\n"));
              return false;
            }
            kw_ok = true;
            break;
          case 9: /* where */
            if ((rc.where || rc.regexwhere) && !rc.mod) {
              ua->SendMsg(_("Where or RegexWhere specified twice.\n"));
              return false;
            }
            rc.where = ua->argv[i];
            if (!ua->AclAccessOk(Where_ACL, rc.where, true)) {
              ua->SendMsg(_("No authoriztion for \"where\" specification.\n"));
              return false;
            }
            kw_ok = true;
            break;
          case 10: /* bootstrap */
            if (rc.bootstrap && !rc.mod) {
              ua->SendMsg(_("Bootstrap specified twice.\n"));
              return false;
            }
            rc.bootstrap = ua->argv[i];
            kw_ok = true;
            break;
          case 11: /* replace */
            if (rc.replace && !rc.mod) {
              ua->SendMsg(_("Replace specified twice.\n"));
              return false;
            }
            rc.replace = ua->argv[i];
            kw_ok = true;
            break;
          case 12: /* When */
            if (rc.when && !rc.mod) {
              ua->SendMsg(_("When specified twice.\n"));
              return false;
            }
            rc.when = ua->argv[i];
            kw_ok = true;
            break;
          case 13: /* Priority */
            if (rc.Priority && !rc.mod) {
              ua->SendMsg(_("Priority specified twice.\n"));
              return false;
            }
            rc.Priority = atoi(ua->argv[i]);
            if (rc.Priority <= 0) {
              ua->SendMsg(
                  _("Priority must be positive nonzero setting it to 10.\n"));
              rc.Priority = 10;
            }
            kw_ok = true;
            break;
          case 14: /* yes */
            kw_ok = true;
            break;
          case 15: /* Verify Job */
            if (rc.verify_job_name) {
              ua->SendMsg(_("Verify Job specified twice.\n"));
              return false;
            }
            rc.verify_job_name = ua->argv[i];
            kw_ok = true;
            break;
          case 16: /* files */
            rc.files = atoi(ua->argv[i]);
            kw_ok = true;
            break;
          case 17: /* catalog */
            rc.catalog_name = ua->argv[i];
            kw_ok = true;
            break;
          case 18: /* since */
            rc.since = ua->argv[i];
            kw_ok = true;
            break;
          case 19: /* cloned */
            rc.cloned = true;
            kw_ok = true;
            break;
          case 20: /* write verify list output */
            rc.verify_list = ua->argv[i];
            kw_ok = true;
            break;
          case 21: /* Migration Job */
            if (rc.previous_job_name) {
              ua->SendMsg(_("Migration Job specified twice.\n"));
              return false;
            }
            rc.previous_job_name = ua->argv[i];
            kw_ok = true;
            break;
          case 22: /* pool */
            if (rc.pool_name) {
              ua->SendMsg(_("Pool specified twice.\n"));
              return false;
            }
            rc.pool_name = ua->argv[i];
            kw_ok = true;
            break;
          case 23: /* nextpool */
            if (rc.next_pool_name) {
              ua->SendMsg(_("NextPool specified twice.\n"));
              return false;
            }
            rc.next_pool_name = ua->argv[i];
            kw_ok = true;
            break;
          case 24: /* backupclient */
            if (rc.client_name) {
              ua->SendMsg(_("Client specified twice.\n"));
              return 0;
            }
            rc.client_name = ua->argv[i];
            kw_ok = true;
            break;
          case 25: /* restoreclient */
            if (rc.restore_client_name && !rc.mod) {
              ua->SendMsg(_("Restore Client specified twice.\n"));
              return false;
            }
            rc.restore_client_name = ua->argv[i];
            kw_ok = true;
            break;
          case 26: /* pluginoptions */
            if (rc.plugin_options) {
              ua->SendMsg(_("Plugin Options specified twice.\n"));
              return false;
            }
            rc.plugin_options = ua->argv[i];
            if (!ua->AclAccessOk(PluginOptions_ACL, rc.plugin_options, true)) {
              ua->SendMsg(
                  _("No authorization for \"PluginOptions\" specification.\n"));
              return false;
            }
            kw_ok = true;
            break;
          case 27: /* spooldata */
            if (rc.spool_data_set) {
              ua->SendMsg(_("Spool flag specified twice.\n"));
              return false;
            }
            if (IsYesno(ua->argv[i], &rc.spool_data)) {
              rc.spool_data_set = true;
              kw_ok = true;
            } else {
              ua->SendMsg(_("Invalid spooldata flag.\n"));
            }
            break;
          case 28: /* comment */
            rc.comment = ua->argv[i];
            kw_ok = true;
            break;
          case 29: /* ignoreduplicatecheck */
            if (rc.ignoreduplicatecheck_set) {
              ua->SendMsg(_("IgnoreDuplicateCheck flag specified twice.\n"));
              return false;
            }
            if (IsYesno(ua->argv[i], &rc.ignoreduplicatecheck)) {
              rc.ignoreduplicatecheck_set = true;
              kw_ok = true;
            } else {
              ua->SendMsg(_("Invalid ignoreduplicatecheck flag.\n"));
            }
            break;
          case 30: /* accurate */
            if (rc.accurate_set) {
              ua->SendMsg(_("Accurate flag specified twice.\n"));
              return false;
            }
            if (IsYesno(ua->argv[i], &rc.accurate)) {
              rc.accurate_set = true;
              kw_ok = true;
            } else {
              ua->SendMsg(_("Invalid accurate flag.\n"));
            }
            break;
          case 31: /* backupformat */
            if (rc.backup_format && !rc.mod) {
              ua->SendMsg(_("Backup Format specified twice.\n"));
              return false;
            }
            rc.backup_format = ua->argv[i];
            kw_ok = true;
            break;
          default:
            break;
        }
      } /* end strcase compare */
    }   /* end keyword loop */

    // End of keyword for loop -- if not found, we got a bogus keyword
    if (!kw_ok) {
      Dmsg1(800, "%s not found\n", ua->argk[i]);
      /*
       * Special case for Job Name, it can be the first
       * keyword that has no value.
       */
      if (!rc.job_name && !ua->argv[i]) {
        rc.job_name = ua->argk[i]; /* use keyword as job name */
        Dmsg1(800, "Set jobname=%s\n", rc.job_name);
      } else {
        ua->SendMsg(_("Invalid keyword: %s\n"), ua->argk[i]);
        return false;
      }
    }
  } /* end argc loop */

  Dmsg0(800, "Done scan.\n");
  if (rc.comment) {
    if (!IsCommentLegal(ua, rc.comment)) { return false; }
  }
  if (rc.catalog_name) {
    rc.catalog = ua->GetCatalogResWithName(rc.catalog_name);
    if (rc.catalog == NULL) {
      ua->ErrorMsg(_("Catalog \"%s\" not found\n"), rc.catalog_name);
      return false;
    }
  }
  Dmsg1(800, "Using catalog=%s\n", NPRT(rc.catalog_name));

  if (rc.job_name) {
    /* Find Job */
    rc.job = ua->GetJobResWithName(rc.job_name);
    if (!rc.job) {
      if (*rc.job_name != 0) {
        ua->SendMsg(_("Job \"%s\" not found\n"), rc.job_name);
      }
      rc.job = select_job_resource(ua);
    } else {
      Dmsg1(800, "Found job=%s\n", rc.job_name);
    }
  } else if (!rc.job) {
    ua->SendMsg(_("A job name must be specified.\n"));
    rc.job = select_job_resource(ua);
  }
  if (!rc.job) { return false; }

  if (rc.pool_name) {
    rc.pool = ua->GetPoolResWithName(rc.pool_name);
    if (!rc.pool) {
      if (*rc.pool_name != 0) {
        ua->WarningMsg(_("Pool \"%s\" not found.\n"), rc.pool_name);
      }
      rc.pool = select_pool_resource(ua);
    }
  } else if (!rc.pool) {
    rc.pool = rc.job->pool; /* use default */
  }
  if (!rc.pool) { return false; }
  Dmsg1(100, "Using pool %s\n", rc.pool->resource_name_);

  if (rc.next_pool_name) {
    rc.next_pool = ua->GetPoolResWithName(rc.next_pool_name);
    if (!rc.next_pool) {
      if (*rc.next_pool_name != 0) {
        ua->WarningMsg(_("Pool \"%s\" not found.\n"), rc.next_pool_name);
      }
      rc.next_pool = select_pool_resource(ua);
    }
  } else if (!rc.next_pool) {
    rc.next_pool = rc.pool->NextPool; /* use default */
  }
  if (rc.next_pool) {
    Dmsg1(100, "Using next pool %s\n", rc.next_pool->resource_name_);
  }

  if (rc.StoreName) {
    rc.store->store = ua->GetStoreResWithName(rc.StoreName);
    PmStrcpy(rc.store->store_source, _("command line"));
    if (!rc.store->store) {
      if (*rc.StoreName != 0) {
        ua->WarningMsg(_("Storage \"%s\" not found.\n"), rc.StoreName);
      }
      rc.store->store = select_storage_resource(ua);
      PmStrcpy(rc.store->store_source, _("user selection"));
    }
  } else if (!rc.store->store) {
    GetJobStorage(rc.store, rc.job, NULL); /* use default */
  }

  /*
   * For certain Jobs an explicit setting of the read storage is not
   * required as its determined when the Job is executed automatically.
   */
  switch (rc.job->JobType) {
    case JT_COPY:
    case JT_MIGRATE:
      break;
    default:
      if (!rc.store->store) {
        ua->ErrorMsg(_("No storage specified.\n"));
        return false;
      } else if (!ua->AclAccessOk(Storage_ACL, rc.store->store->resource_name_,
                                  true)) {
        ua->ErrorMsg(_("No authorization. Storage \"%s\".\n"),
                     rc.store->store->resource_name_);
        return false;
      }
      Dmsg1(800, "Using storage=%s\n", rc.store->store->resource_name_);
      break;
  }

  if (rc.client_name) {
    rc.client = ua->GetClientResWithName(rc.client_name);
    if (!rc.client) {
      if (*rc.client_name != 0) {
        ua->WarningMsg(_("Client \"%s\" not found.\n"), rc.client_name);
      }
      rc.client = select_client_resource(ua);
    }
  } else if (!rc.client) {
    rc.client = rc.job->client; /* use default */
  }

  if (rc.client) {
    if (!ua->AclAccessOk(Client_ACL, rc.client->resource_name_, true)) {
      ua->ErrorMsg(_("No authorization. Client \"%s\".\n"),
                   rc.client->resource_name_);
      return false;
    } else {
      Dmsg1(800, "Using client=%s\n", rc.client->resource_name_);
    }
  }

  if (rc.restore_client_name) {
    rc.client = ua->GetClientResWithName(rc.restore_client_name);
    if (!rc.client) {
      if (*rc.restore_client_name != 0) {
        ua->WarningMsg(_("Restore Client \"%s\" not found.\n"),
                       rc.restore_client_name);
      }
      rc.client = select_client_resource(ua);
    }
  } else if (!rc.client) {
    rc.client = rc.job->client; /* use default */
  }

  if (rc.client) {
    if (!ua->AclAccessOk(Client_ACL, rc.client->resource_name_, true)) {
      ua->ErrorMsg(_("No authorization. Client \"%s\".\n"),
                   rc.client->resource_name_);
      return false;
    } else {
      Dmsg1(800, "Using restore client=%s\n", rc.client->resource_name_);
    }
  }

  if (rc.fileset_name) {
    rc.fileset = ua->GetFileSetResWithName(rc.fileset_name);
    if (!rc.fileset) {
      ua->SendMsg(_("FileSet \"%s\" not found.\n"), rc.fileset_name);
      rc.fileset = select_fileset_resource(ua);
      if (!rc.fileset) { return false; }
    }
  } else if (!rc.fileset) {
    rc.fileset = rc.job->fileset; /* use default */
  }

  if (rc.verify_job_name) {
    rc.verify_job = ua->GetJobResWithName(rc.verify_job_name);
    if (!rc.verify_job) {
      ua->SendMsg(_("Verify Job \"%s\" not found.\n"), rc.verify_job_name);
      rc.verify_job = select_job_resource(ua);
    }
  } else if (!rc.verify_job) {
    rc.verify_job = rc.job->verify_job;
  }

  if (rc.previous_job_name) {
    rc.previous_job = ua->GetJobResWithName(rc.previous_job_name);
    if (!rc.previous_job) {
      ua->SendMsg(_("Migration Job \"%s\" not found.\n"), rc.previous_job_name);
      rc.previous_job = select_job_resource(ua);
    }
  } else {
    rc.previous_job = rc.job->verify_job;
  }
  return true;
}
} /* namespace directordaemon */