Files @ ef192b082541
Branch filter:

Location: majic-scripts/games/factorio_manager.sh

branko
Noticket: [factorio_manager.sh] Add verbose output for info command:

- Lists mod URLs and their descriptions.
   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
#!/bin/bash
#
# factorio_manager.sh
#
# Copyright (C) 2020, Branko Majic <branko@majic.rs>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Treat unset variables as errors.
set -u

program="factorio_manager.sh"
version="0.4.0"

function synopsis() {
cat <<EOF
$program $version, helper tool for managing Factorio instances

Usage:
  $program [OPTIONS] launch INSTANCE
  $program [OPTIONS] info INSTANCE
  $program [OPTIONS] list

  $program [OPTIONS] create INSTANCE
  $program [OPTIONS] create-server INSTANCE
  $program [OPTIONS] rename CURRENT_NAME NEW_NAME
  $program [OPTIONS] copy SOURCE_INSTANCE DESTINATION_INSTANCE
  $program [OPTIONS] remove INSTANCE
  $program [OPTIONS] import INSTANCE SOURCE_DIRECTORY
  $program [OPTIONS] set-version INSTANCE
  $program [OPTIONS] reset-server-map INSTANCE

  $program [OPTIONS] versions
  $program [OPTIONS] install GAME_ARCHIVE

  $program [OPTIONS] list-backups INSTANCE
  $program [OPTIONS] backup INSTANCE [DESCRIPTION]
  $program [OPTIONS] restore INSTANCE BACKUP_NAME
  $program [OPTIONS] remove-backup INSTANCE BACKUP_NAME

  $program [OPTIONS] set-game-dir GAME_INSTALLATIONS_DIRECTORY
EOF
}

function short_usage() {
cat <<EOF
$(synopsis)

For more details see $program -h.
EOF
}

function usage() {
    cat <<EOF
$(synopsis)

$program is a helper tool for managing multiple Factorio instances.

Each instance is designated a dedicated directory, which contains all
of its configuration files, saves games, and mods, and is kept
separate from all other instances.

Each instance is bound to a specific game version, and the manager
fully supports working with multiple versions of Factorio. Base game
files are kept intact and can be shared by multiple instances.

Factorio Manager keeps instances in sub-directories under the
~/.factorio/ directory. Sub-directories correspond to instance
names.

The following instance names are reserved for special use by
the tool:

 - .game_installations (used for storing symlink towards directory
   containing Factorio installations)

Multiple commands are provided for managing Factorio instances. Each
command accepts its own set of positional arguments.


backup INSTANCE [DESCRIPTION]

    Creates backup of an instance. All backups will be stored as
    subdirectories under the .bak directory within the instance
    directory. An optional description can be passed-in to make it
    easier to distinguish between different backups. Hidden files
    (names starting with '.') will be omitted from the backup.

copy SOURCE_INSTANCE DESTINATION_INSTANCE

    Creates a copy of an existing instance. Requires name of an
    existing instance and name of the new instance to be passed-in as
    arguments. Command will refuse to overwrite destination instance
    if it already exists. Command will prompt user to specify desired
    version for the copy, and to choose whether the backups should be
    copied as well.

create INSTANCE

    Creates a new Factorio instance with the given name. Command will
    prompt the user to pick between locally available Factorio
    versions.

    NOTE: When launching the instance for the first time, Factorio
    will report that its configuration file is invalid, and offer to
    fix it. The reason is that the manager creates a minimal
    configuration file when creating an instance, and Factorio does
    not like this. It should be safe to allow Factorio to fix the
    configuration file (this will populate it with the necessary
    commented-out options).

create-server INSTANCE

    Creates a new Factorio server instance with the given
    name. Command will prompt the user to pick between locally
    available Factorio versions, and to provide settings for server.

import INSTANCE

    Creates a new instance out of existing files found within a
    Factorio installation directory. This command is useful when
    migrating from Factorio installations that store all data in the
    root of the game installation directory. Command will prompt the
    user to pick between locally available Factorio versions.

info INSTANCE

    Shows information about the specified instance. This includes:

        - instance name
        - game version
        - instance directory path
        - list of enabled/disabled mods
        - list of backups

    If verbose mode is enabled, mods are listed with URLs and
    description as well.

install GAME_ARCHIVE

    Installs Factorio from the provided archive into the game
    installations directory. Version is automatically detected from
    the archive. All extracted game files are set-up to be read-only
    to prevent accidentally running the game directly from its own
    directory.

launch INSTANCE

    Launches the instance with specified name. See the note for the
    "create" command.

list

    Lists available Factorio instances.

list-backups INSTANCE

    Lists available backups for the specified instance.

remove-backup INSTANCE BACKUP_NAME

    Removes the specified backup for the specified instance. User must
    confirm the action prior to any files being removed.

remove INSTANCE

    Removes the specified instance. User must confirm the action prior
    to any files being removed.

rename CURRENT_NAME NEW_NAME

    Renames an existing instnace. Requires current name of an
    instance, as well as a new name. Command will refuse to rename the
    instance if an instance with specified new name already exists.

restore INSTANCE BACKUP_NAME

    Restores the specified instance from the specified backup. User
    must confirm the action prior to any files being replaced.

set-game-dir GAME_INSTALLATIONS_DIRECTORY

    Sets the base directory where Factorio game installations can be
    found. Each sub-directory within this directory should be named
    after the version of Factorio it represents. For example:

        - ~/local/games/factorio/0.17.79/
        - ~/local/games/factorio/0.18.30/
        - ~/local/games/factorio/0.18.34/

    Directory must be either empty or it should contain at least one
    instance of Factorio installation already.

set-version INSTANCE

    Sets Factorio version for the specified instance. User is prompted
    to pick between locally available versions.

versions

    Shows locally available Factorio versions.


$program accepts the following options:

    -C
        Force colour output.
    -V
        Verbose mode. Some commands may provide more output when enabled.
    -q
        Quiet mode. Output a message only if newer packages are available.
    -d
        Enable debug mode.
    -v
        Show script licensing information.
    -h
        Show usage help.


Please report bugs and send feature requests to <branko@majic.rs>.
EOF
}

function version() {
    cat <<EOF
$program, version $version

+-----------------------------------------------------------------------+
| Copyright (C) 2020, Branko Majic <branko@majic.rs>                    |
|                                                                       |
| This program is free software: you can redistribute it and/or modify  |
| it under the terms of the GNU General Public License as published by  |
| the Free Software Foundation, either version 3 of the License, or     |
| (at your option) any later version.                                   |
|                                                                       |
| This program is distributed in the hope that it will be useful,       |
| but WITHOUT ANY WARRANTY; without even the implied warranty of        |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         |
| GNU General Public License for more details.                          |
|                                                                       |
| You should have received a copy of the GNU General Public License     |
| along with this program.  If not, see <http://www.gnu.org/licenses/>. |
+-----------------------------------------------------------------------+

EOF
}

function setup_colours() {

    # Set-up colours for message printing if we're not piping and terminal is
    # capable of outputting the colors.
    _color_terminal=$(tput colors 2>&1)
    if [[ -t 1 ]] && (( _color_terminal > 0 )) || (( force_colours == 1 )); then
        _text_black=$(tput setaf 0)
        _text_red=$(tput setaf 1)
        _text_green=$(tput setaf 2)
        _text_yellow=$(tput setaf 3)
        _text_blue=$(tput setaf 4)
        _text_purple=$(tput setaf 5)
        _text_cyan=$(tput setaf 6)
        _text_white=$(tput setaf 7)

        _text_bold=$(tput bold)
        _text_reset=$(tput sgr0)

        _bg_black=$(tput setab 0)
        _bg_red=$(tput setab 1)
        _bg_green=$(tput setab 2)
        _bg_yellow=$(tput setab 3)
        _bg_blue=$(tput setab 4)
        _bg_purple=$(tput setab 5)
        _bg_cyan=$(tput setab 6)
        _bg_white=$(tput setab 7)
    else
        _text_black=""
        _text_red=""
        _text_green=""
        _text_yellow=""
        _text_blue=""
        _text_purple=""
        _text_cyan=""
        _text_white=""

        _text_bold=""
        _text_reset=""

        # Part of the standard Majic Bash script template.
        # shellcheck disable=SC2034
        _bg_black=""
        # shellcheck disable=SC2034
        _bg_red=""
        # shellcheck disable=SC2034
        _bg_green=""
        # shellcheck disable=SC2034
        _bg_yellow=""
        # shellcheck disable=SC2034
        _bg_blue=""
        # shellcheck disable=SC2034
        _bg_purple=""
        # shellcheck disable=SC2034
        _bg_cyan=""
        # shellcheck disable=SC2034
        _bg_white=""
    fi

    # Make the colors available via an associative array as well.
    declare -g -A _text_colors=()

    _text_colors[black]="${_text_black}"
    _text_colors[blue]="${_text_blue}"
    _text_colors[cyan]="${_text_cyan}"
    _text_colors[green]="${_text_green}"
    _text_colors[purple]="${_text_purple}"
    _text_colors[red]="${_text_red}"
    _text_colors[white]="${_text_white}"
    _text_colors[yellow]="${_text_yellow}"

    _text_colors[boldblack]="${_text_bold}${_text_black}"
    _text_colors[boldblue]="${_text_bold}${_text_blue}"
    _text_colors[boldcyan]="${_text_bold}${_text_cyan}"
    _text_colors[boldgreen]="${_text_bold}${_text_green}"
    _text_colors[boldpurple]="${_text_bold}${_text_purple}"
    _text_colors[boldred]="${_text_bold}${_text_red}"
    _text_colors[boldwhite]="${_text_bold}${_text_white}"
    _text_colors[boldyellow]="${_text_bold}${_text_yellow}"
}

# Set-up functions for printing coloured messages.
function debug() {
    if [[ $debug != 0 ]]; then
        echo "${_text_bold}${_text_blue}[DEBUG]${_text_reset}" "$@"
    fi
}

function info() {
    echo "${_text_bold}${_text_white}[INFO] ${_text_reset}" "$@"
}

function success() {
    echo "${_text_bold}${_text_green}[OK]   ${_text_reset}" "$@"
}

function warning() {
    echo "${_text_bold}${_text_yellow}[WARN] ${_text_reset}" "$@"
}

function error() {
    echo "${_text_bold}${_text_red}[ERROR]${_text_reset}" "$@" >&2
}

#
# Prints text in requested color to standard output. Behaves as thin
# wrapper around the echo built-in.
#
# Two invocation variants with different arguments are
# supported. First argument is the one that will determine what the
# desired invocation is.
#
# Arguments (variant 1):
#
#   $1 (echo_options)
#     Additional options to pass-in to echo. Must be a single argument
#     with leading dash followed by echo's own options. E.g. "-ne".
#
#   $2 (color)
#     Text color to use. Supported values: black, blue, cyan, green,
#     purple, red, white, yellow.
#
#   $3 (text)
#     Text to output.
#
#
# Arguments (variant 2):
#
#   $1 (color)
#     Text color to use. Supported values: black, blue, cyan, green,
#     purple, red, white, yellow, boldblack, boldblue, boldcyan,
#     boldgreen, boldpurple, boldred, boldwhite, boldyellow.
#
#   $2 (text)
#     Text to output.
#
function colorecho() {
    local options="" color text
    local reset="$_text_reset"

    if [[ ${1-} =~ -.* ]]; then
        options="$1"
        shift
    fi

    color="$1"
    text="$2"

    if [[ -n $options ]]; then
        echo "$options" "${_text_colors[$color]}$text${reset}"
    else
        echo "${_text_colors[$color]}$text${reset}"
    fi
}

#
# Prints text in requested color to standard output using printf
# format string and arguments.. Behaves as thin wrapper around the
# printf built-in.
#
# Arguments:
#
#   $1 (color)
#     Text color to use. Supported values: black, blue, cyan, green,
#     purple, red, white, yellow.
#
#   $2 (format_string)
#     printf-compatible format string.
#
#   $3 .. $n
#      Replacement values for the the format string.
#
function colorprintf() {
    local reset="$_text_reset"

    local color="$1"
    local format="$2"
    shift 2

    # Variables within this printf are used for dynamic color and
    # formatting, and can't be used as arguments.
    # shellcheck disable=SC2059
    printf "${_text_colors[$color]}${format}${reset}" "$@"
}

#
# Presents user with a warning, asks user for confirmation to
# continue, and terminates the script is confirmation is not provided
# with designated exit code.
#
# This function can be used to request confirmation for dangerous
# actions/operations (such as removal of large number of files etc).
#
# The user must type-in YES (with capital casing) to proceed.
#
# Arguments:
#
#   $1 (prompt_text)
#     Text to prompt the user with.
#
#   $2 (abort_text)
#     Text to show to user in case the operation was aborted by user.
#
#   $3 (exit_code)
#     Exit code when terminating the proram.
#
function critical_confirmation() {
    local prompt_text="$1"
    local abort_text="$2"
    local exit_code="$3"

    echo -n "${_text_bold}${_text_yellow}[WARN] ${_text_reset}" "${prompt_text} Type YES to confirm (default is no): "
    read -r confirm

    if [[ $confirm != "YES" ]]; then
        error "$abort_text"
        exit "$ERROR_GENERAL"
    fi
}

#
# Validates that the specified value conforms to designated setting.
#
# This is a small helper function used within read_server_settings
# function to validate the settings.
#
# Arguments:
#
#   $1 (name)
#     Name of the setting. Used to show erros to the user.
#
#   $2 (value)
#     Value to validate.
#
#   $3 (type)
#
#     Value type. Currently supports the following types:
#
#       - bool (boolean)
#       - int (integer/number)
#       - str (string, essentially anything can pass this validation)
#       - list (space-separated list of strings, essentially anything
#         can pass this validation)
#       - VAL_1|...|VAL_N (choice between different values)
#
#     When using the VAL_1|...|VAL_N variant, validation is slightly
#     relaxed for string values to allow both quoted and unquoted
#     variants. For example, if type was set to true|false|"admins",
#     then both 'admin' and '"admins"' will validate successfully
#     against the type.
#
# Returns:
#
#   0 if validation has passed, 1 if validation failed, and 2 if
#   passed-in type is not supported.
#
function validate_server_setting_value() {
    local name="$1"
    local value="$2"
    local type="$3"

    declare -a possible_values

    local i

    # Assume failure.
    local result=1

    if [[ $type == "bool" ]]; then
        if [[ $value == true || $value == false ]]; then
            result=0
        else
            colorecho "red" "$name must be a boolean [true|false]."
        fi

    elif [[ $type == "int" ]]; then
        if [[ $value =~ ^[[:digit:]]+$ ]]; then
            result=0
        else
            colorecho "red" "$name must be a number."
        fi

    elif [[ $type == "str" ]]; then
        result=0

    elif [[ $type == "list" ]]; then
        # This is free-form space-delimited list.
        result=0

    elif [[ $type =~ ^.+\|.+$ ]]; then
        readarray -d "|" -t possible_values < <(echo -n "$type")

        for i in "${possible_values[@]}"; do
            # Allow strings without quotes to be specified by the user.
            [[ $value == "$i" || \"$value\" == "$i" ]] && result=0
        done

        [[ $result == 0 ]] || colorecho red "$name must be one of listed values [$type]."
    else
        error "Unsupported type associated with '$name': $type"
        result=2
    fi

    return "$result"
}

#
# Prompts user to provide settings for a server instance.
#
# Function will go over a number of questions, providing a set of
# default values, and allowing the user to edit them in-place. Once
# all questions have been answered, user is presented with summary and
# ability to revisit the settings again.
#
# The function will transform the answers to be fully usable in the
# server configuration file, making sure the parameters are properly
# escaped for use in a JSON file.
#
# Defaults are mostly identical to the ones listed under Factorio's
# default "server-settings.json" with some exceptions to options that
# may be considered invasion of privacy:
#
#   - User verification is disabled. Otherwise the central
#     authentication server will always be aware of who is playing the
#     game at the moment.
#   - Game is specifically configured to be non-public.
#
# In addition to settings from the "server-settings.json"
# configuiration file, settings also cover the server port (specified
# in the "config.ini").
#
# Arguments:
#
#   $1 (server_name)
#     Default name to use for the server.
#
# Sets:
#
#   settings_value
#     Associative array storing settings and their values. Keys are
#     equivalent to setting names in the server configuration file.
#
function read_server_settings() {

    # Read arguments.
    local server_name="$1"

    # Local helper variables.
    local key="" value="" prompt="" confirmed="" item="" possible_values i

    declare -A settings_prompt=()
    declare -A settings_description=()
    declare -A settings_type=()

    declare -a settings_order=()

    # Global variables set by the function.
    declare -g -A settings_value=()

    # Set-up listings of server settings. Each setting is described
    # with name, prompt, description, default value, and
    # type. Supported types are: bool, int, str, list (input treated
    # as space-delimited list).
    #
    # Maintain additional array with keys in order to maintain
    # order when displaying questions to users.
    key="name"
    settings_prompt["$key"]="Name"
    settings_description["$key"]="Name of the game as it will appear in the game listing"
    settings_value["$key"]="$server_name"
    settings_type["$key"]="str"
    settings_order+=("$key")

    key="description"
    settings_prompt["$key"]="Description"
    settings_description["$key"]="Description of the game that will appear in the listing"
    settings_value["$key"]=""
    settings_type["$key"]="str"
    settings_order+=("$key")

    key="tags"
    settings_prompt["$key"]="Tags"
    settings_description["$key"]="Tags for the game that will appear in the listing (space-separated)"
    settings_value["$key"]=""
    settings_type["$key"]="list"
    settings_order+=("$key")

    # Not part of "server-settings.json", but important to show and
    # prompt the user for.
    key="port"
    settings_prompt["$key"]="Port"
    settings_description["$key"]="Port on which the server should listen"
    settings_value["$key"]="34197"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="max_players"
    settings_prompt["$key"]="Maximum players"
    settings_description["$key"]="Maximum number of players allowed, admins can join even a full server. 0 means unlimited."
    settings_value["$key"]="0"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="public"
    settings_prompt["$key"]="Publicly available"
    settings_description["$key"]="Game will be published on the official Factorio matching server."
    settings_value["$key"]="false"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="lan"
    settings_prompt["$key"]="Broadcast on LAN"
    settings_description["$key"]="Game will be broadcast on LAN."
    settings_value["$key"]="false"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="username"
    settings_prompt["$key"]="Factorio login username"
    settings_description["$key"]="Your factorio.com login credentials. Required for games with visibility public."
    settings_value["$key"]=""
    settings_type["$key"]="str"
    settings_order+=("$key")

    key="password"
    settings_prompt["$key"]="Factorio login password"
    settings_description["$key"]="Your factorio.com login credentials. Required for games with visibility public."
    settings_value["$key"]=""
    settings_type["$key"]="str"
    settings_order+=("$key")

    key="token"
    settings_prompt["$key"]="Factorio authentication token"
    settings_description["$key"]="Authentication token. May be used instead of 'password' for factorio.com login credentials."
    settings_value["$key"]=""
    settings_type["$key"]="str"
    settings_order+=("$key")

    key="game_password"
    settings_prompt["$key"]="Server password"
    settings_description["$key"]="Server password used to authenticate users towards the server itself. Default value has been randomly generated using /dev/urandom."
    settings_value["$key"]=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 33)
    settings_type["$key"]="str"
    settings_order+=("$key")

    key="require_user_verification"
    settings_prompt["$key"]="Require user verification"
    settings_description["$key"]="When set to true, the server will only allow clients that have a valid Factorio.com account."
    settings_value["$key"]="false"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="max_upload_in_kilobytes_per_second"
    settings_prompt["$key"]="Maxiumum upload in kilobytes per second"
    settings_description["$key"]="Limits the maximum upload speed from server towards the clients (for map transfers etc). 0 means unlimited."
    settings_value["$key"]="0"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="max_upload_slots"
    settings_prompt["$key"]="Maximum upload slots"
    settings_description["$key"]="Limits the number of simulataneous uploads from server towards clients. 0 means unlimited."
    settings_value["$key"]="5"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="minimum_latency_in_ticks"
    settings_prompt["$key"]="Minimum latency in ticks"
    settings_description["$key"]="Minimum tolerable latency in ticks for connecting clients. One tick is 16ms in default speed. 0 means no minimum."
    settings_value["$key"]="0"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="ignore_player_limit_for_returning_players"
    settings_prompt["$key"]="Ignore player limit for returning players"
    settings_description["$key"]="Players that played on this map already can join even when the max player limit was reached."
    settings_value["$key"]="false"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="allow_commands"
    settings_prompt["$key"]="Allow commands"
    settings_description["$key"]="Allow execution of commands via Lua console."
    settings_value["$key"]="admins-only"
    settings_type["$key"]="true|false|\"admins-only\""
    settings_order+=("$key")

    key="autosave_interval"
    settings_prompt["$key"]="Autosave interval"
    settings_description["$key"]="Autosave interval in minutes."
    settings_value["$key"]="10"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="autosave_slots"
    settings_prompt["$key"]="Autosave slots"
    settings_description["$key"]="Number of autosave slots to use. Autosave slots are cycled through when the server autosaves."
    settings_value["$key"]="5"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="afk_autokick_interval"
    settings_prompt["$key"]="AFK auto-kick interval"
    settings_description["$key"]="How many minutes until someone is kicked when doing nothing, 0 for never."
    settings_value["$key"]="0"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="auto_pause"
    settings_prompt["$key"]="Auto-pause"
    settings_description["$key"]="Whether should the server be paused when no players are present."
    settings_value["$key"]="true"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="only_admins_can_pause_the_game"
    settings_prompt["$key"]="Only admins can pause the game"
    settings_description["$key"]="Specify if only admins should be able to pause the game."
    settings_value["$key"]="true"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="autosave_only_on_server"
    settings_prompt["$key"]="Autosave only on server"
    settings_description["$key"]="Whether autosaves should be saved only on server or also on all connected clients."
    settings_value["$key"]="true"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="non_blocking_saving"
    settings_prompt["$key"]="[EXPERT] Non-blocking saving"
    settings_description["$key"]="Highly experimental feature, enable only at your own risk of losing your saves. On UNIX systems, server will fork itself to create an autosave. Autosaving on connected Windows clients will be disabled regardless of autosave_only_on_server option."
    settings_value["$key"]="false"
    settings_type["$key"]="bool"
    settings_order+=("$key")

    key="minimum_segment_size"
    settings_prompt["$key"]="[EXPERT] Minimum segment size"
    settings_description["$key"]="Long network messages are split into segments that are sent over multiple ticks. Their size depends on the number of peers currently connected. Increasing the segment size will increase upload bandwidth requirement for the server and download bandwidth requirement for clients. This setting only affects server outbound messages. Changing these settings can have a negative impact on connection stability for some clients."
    settings_value["$key"]="25"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="minimum_segment_size_peer_count"
    settings_prompt["$key"]="[EXPERT] Minimum segment size peer count"
    settings_description["$key"]="See description for minimum_segment_size"
    settings_value["$key"]="20"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="maximum_segment_size"
    settings_prompt["$key"]="[EXPERT] Maximum segment size"
    settings_description["$key"]="See description for minimum_segment_size"
    settings_value["$key"]="100"
    settings_type["$key"]="int"
    settings_order+=("$key")

    key="maximum_segment_size_peer_count"
    settings_prompt["$key"]="[EXPERT] Maxmium segment size peer count"
    settings_description["$key"]="See description for minimum_segment_size"
    settings_value["$key"]="10"
    settings_type["$key"]="int"
    settings_order+=("$key")

    # Loop until user has confirmed the settings.
    while [[ ${confirmed,,} != 'y' ]]; do
        confirmed=""

        # Display the settings.
        echo "Current settings:"
        echo
        for key in "${settings_order[@]}"; do
            colorecho -n "yellow" "${settings_prompt[$key]}: "
            echo "${settings_value[$key]}"
        done

        # Prompt user to confirm settings.
        while [[ ${confirmed,,} != 'y' && ${confirmed,,} != 'n' ]]; do
            echo
            colorecho -n "green" "Are you satisfied with current settings (y/n)? "
            read -rn1 confirmed
            echo
        done

        # Allow user to provide changed values if not satisfied with
        # settings.
        if [[ ${confirmed,,} == 'n' ]]; then
            echo

            local total_questions="${#settings_order[@]}"
            local current_question=1

            for key in "${settings_order[@]}"; do

                # Prompt based on associated value type for the setting.
                if [[ ${settings_type[$key]} == "bool" ]]; then
                    prompt="${settings_prompt[$key]} [true|false]:"
                elif [[ ${settings_type[$key]} == "int" ]]; then
                    prompt="${settings_prompt[$key]} [number]:"
                elif [[ ${settings_type[$key]} == "str" ]]; then
                    prompt="${settings_prompt[$key]} [text]:"
                elif [[ ${settings_type[$key]} == "list" ]]; then
                    prompt="${settings_prompt[$key]} [space-delimited list]:"
                else
                    prompt="${settings_prompt[$key]} [${settings_type[$key]}]:"
                fi

                # Add some coloring to the prompt.
                prompt=$(colorprintf "green" "%02d/%02d ${prompt} " "$current_question" "$total_questions")

                # Show setting description.
                colorecho "white" "${settings_description[$key]}" | fold -s

                # Keep prompting user until a valid value is provided.
                validation_result=""
                until [[ $validation_result == 0 ]]; do

                    read -r -p "$prompt" -e -i "${settings_value[$key]}" value

                    validate_server_setting_value "${settings_prompt[$key]}" "$value" "${settings_type[$key]}"
                    validation_result="$?"
                    [[ $validation_result == 2 ]] && error "Internal error, type not set correctly for setting: $key." && exit "$ERROR_GENERAL"
                done

                settings_value[$key]="$value"

                echo
                (( current_question++ ))
            done
        fi
    done

    # Prepare values so they can be used within the JSON file.
    for key in "${settings_order[@]}"; do
        debug "Raw value for $key: ${settings_value[$key]}"

        if ! validate_server_setting_value "$key (${settings_prompt[$key]})" "${settings_value[$key]}" "${settings_type[$key]}"; then
            error "Failed to validate the settings value. This is most likely an internal bug in $program."
            exit "$ERROR_GENERAL"
        fi

        if [[ ${settings_type[$key]} == "str" ]]; then
            settings_value[$key]="\"${settings_value[$key]}\""

        # Used for selecting between multiple values.
        elif [[ ${settings_type[$key]} =~ ^.+\|.+$ ]]; then
            readarray -d "|" -t possible_values < <(echo -n "${settings_type[$key]}")

            for i in "${possible_values[@]}"; do
                # Convenience for allowing strings without quotes specified by the user.
                [[ \"${settings_value[$key]}\" == "$i" ]] && settings_value[$key]="\"${settings_value[$key]}\""
            done

        # List of strings.
        elif [[ ${settings_type[$key]} == "list" ]]; then
            value=""

            for item in ${settings_value[$key]}; do
                value="$value, \"$item\""
            done

            settings_value[$key]="[${value##, }]"
        fi
        debug "Processed value for $key: ${settings_value[$key]}"
    done
}

#
# Validates paths according to internal tool rules or terminates the
# program.
#
# This function helps to reduce boilerplate and centralise some common
# checks around handling of various paths.
#
# Arguments:
#
#   $1 (path_test)
#     Test to apply against the path. Supported tests are:
#
#       game_installations_directory
#         Checks if path contains Factorio installations in
#         sub-directories.
#
#       instance_directory_new
#         Checks if path is unused and can be used for new instance.
#
#       instance_directory
#         Checks if path contains a valid instance.
#
#       backup_directory_new
#         Checks if path is usable as destination for a new backup.
#
#       backup_directory
#         Checks if path contains a valid backup.
#
#       instance_import_source
#         Checks if path is usable as source for importing an instance.
#
#       game_archive
#         Checks if file at designated path is a valid game archive.
#
#       server_instance_directory
#         Checks if path contains a valid server instance.
#
#   $2 (path)
#     Path that should be validated.
#
#   $3 (exit_code)
#     Exit code to use when terminating the program.
#
# Exits:
#
#   If the path type is unsupported, or if the specified path does not
#   conform to requirements for the specified path type.
#
function validate_path_or_terminate() {
    local path_test="$1"
    local path="$2"
    local exit_code="$3"

    if [[ $path_test == "game_installations_directory" ]]; then
        # Make sure user has set directory with game installations -
        # test both symlink and target destination.
        if [[ ! -L $game_installations_directory || ! -d $game_installations_directory ]]; then
            error "Game installations directory has not been properly set. Please run the set-game-dir command first."
            exit "$exit_code"
        fi

    elif [[ $path_test == "instance_directory_new" ]]; then
        if [[ -e $path/config.ini ]]; then
            error "Instance already exists."
            exit "$exit_code"
        fi

        if [[ -e $path ]]; then
            error "Instance directory already exists, but does not contain a valid Factorio instance: $path."
            exit "$exit_code"
        fi

    elif [[ $path_test == "instance_directory" ]]; then
        if [[ ! -d $path ]]; then
            error "Missing instance directory: $path"
            error "Perhaps you have misstyped the instance name or forgot to create one first?"
            exit "$exit_code"
        fi

        if [[ ! -f $path/instance.conf ]]; then
            error "Missing instance configuration file: $path/instance.conf"
            exit "$exit_code"
        fi

        if [[ ! -f $path/config.ini ]]; then
            error "Missing game configuration file: $path/config.ini"
            exit "$exit_code"
        fi

    elif [[ $path_test == "backup_directory_new" ]]; then
        if [[ -e $path/config.ini ]]; then
            error "Backup already exists under directory: $path"
            exit "$exit_code"
        elif [[ -e $path ]]; then
            error "Backup directory already exists, but does not contain a valid backup: $path"
            exit "$exit_code"
        fi

    elif [[ $path_test == "backup_directory" ]]; then

        if [[ ! -d $path ]]; then
            error "Specified backup not available under: $path"
            exit "$ERROR_ARGUMENTS"
        fi

        if [[ ! -f $path/instance.conf ]]; then
            error "Backup missing instance configuration file: $path/instance.conf"
            exit "$exit_code"
        fi

        if [[ ! -f $path/config.ini ]]; then
            error "Backup missing game configuration file: $path/config.ini"
            exit "$exit_code"
        fi

    elif [[ $path_test == "instance_import_source" ]]; then
        if [[ ! -f $path/bin/x64/factorio ]]; then
            error "Could not locate Factorio binary in directory under: $path/bin/x64/factorio"
            error "Factorio Manager natively supports instance imports only when all game data (savegames etc) are stored within Factorio installation directory."
            exit "$ERROR_ARGUMENTS"
        fi

    elif [[ $path_test == "game_archive" ]]; then
        if [[ ! -f $path ]]; then
            error "Supplied path does not point to a valid game archive."
            exit "$ERROR_ARGUMENTS"
        fi

        if ! tar --occurrence=1 --list --file "$game_archive" "factorio/bin/x64/factorio" > /dev/null; then
            error "Supplied path does not point to a valid game archive."
            exit "$ERROR_ARGUMENTS"
        fi

    elif [[ $path_test == "server_instance_directory" ]]; then
        if [[ ! -d $path ]]; then
            error "Missing instance directory: $path"
            error "Perhaps you have misstyped the instance name or forgot to create one first?"
            exit "$exit_code"
        fi

        if [[ ! -f $path/instance.conf ]]; then
            error "Missing instance configuration file: $path/instance.conf"
            exit "$exit_code"
        fi

        if [[ ! -f $path/config.ini ]]; then
            error "Missing game configuration file: $path/config.ini"
            exit "$exit_code"
        fi

        if [[ ! -f $path/server-settings.json ]]; then
            error "Missing server settings file: $path/server-settings.json"
            exit "$exit_code"
        fi
    else
        error "Unable to validate path '$path', unsupported test requested: '$path_test'."
        exit "$ERROR_GENERAL"
    fi
}

#
# Prompts user to pick version of Factorio.
#
# Arguments:
#
#   $1 (game_installations_directory)
#     Path to directory containing Factorio installations.
#
#   $2 (default_version, optional)
#     Default version to fill-in for the user. If not set, last
#     version in the directory (sorted alphabetically) will be used.
#
#   $3 (default_marker, optional)
#     Marker text to use for the default version. Default is "default".
#
# Returns:
#
#   0 if version was successfully selected, 1 otherwise.
#
# Sets:
#
#   game_version_selected
#
function select_factorio_version() {
    local game_installations_directory="$1"
    local default_version="${2-}"
    local default_marker="${3-default}"

    local game_versions_available=()
    local candidate
    local i default_option selected_option

    declare -g game_version_selected=""

    # Grab a list of available versions.
    for candidate in "$game_installations_directory"/*; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            game_versions_available+=( "$(basename "$candidate")" )
        fi
    done

    if [[ ${#game_versions_available[@]} == 0 ]]; then
        error "Could not find any Factorio installations under directory '$game_installations_directory'."
        error "Please unpack Factorio installations into the directory, or use set-game-dir command to specify directory with Factorio installations."
        return 1
    fi

    echo "The following versions of Factorio are locally available:"
    echo

    for i in "${!game_versions_available[@]}"; do
        (( i++ ))
        echo -n "  [$i] $(basename "${game_versions_available[$i-1]}")"

        # Highlight default version.
        if [[ -z $default_version && $i == "${#game_versions_available[@]}" ]] || \
               [[ -n $default_version && ${game_versions_available[i-1]} == "$default_version" ]]; then
            colorecho boldgreen " [$default_marker]"
            default_option="$i"
        else
            echo
        fi
    done

    echo

    while [[ -z $game_version_selected ]]; do
        read -r -e -p "Please specify what version you would like to use (enter for $default_marker): " selected_option
        [[ -z $selected_option ]] && selected_option="$default_option"

        if [[ $selected_option =~ ^[[:digit:]]+$ ]] && (( selected_option >= 1 && selected_option <= ${#game_versions_available[@]} )); then
            game_version_selected="${game_versions_available[$selected_option-1]}"
        else
            error "Invalid option selected, please try again."
            echo
        fi
    done

    return 0
}

#
# Removes all registered lock files. Lock files are registered via the
# global array variable "lock_files". This function is meant to be
# used in conjunction with trap built-in to clean-up the files on exit.
#
# Arguments (globals):
#
#   lock_files
#     Array listing all the lock files that should be removed.
#
function remove_lock_files() {
    local lock

    for lock in "${lock_files[@]}"; do
        rm -f "$lock"
    done
}
declare -a lock_files=()
trap remove_lock_files EXIT

#
# Acquires an exclusive lock via flock call using the specified file
# and file descriptor. If it is not possible to acquire a lock,
# terminates the script, and registers the lock file for removal.
#
# The function should be used in conjunction with subshell as follows:
#
# (
#     lock "$HOME/.mylock" 200
#
#     do_my_stuff_here
#
# ) 200>"$HOME/.mylock"
#
#
# Arguments:
#
# $1 (lock_file)
#   Path to lock file.
#
# $2 (fd)
#   File descriptor number to use for the lock.
#
function lock() {
    local lock_file="$1"
    local fd="$2"

    lock_files+=("$lock_file")

    # Obtain lock - Factorio uses the same mechanism, so we should
    # be able to detect the game is running in this way.
    if ! flock --exclusive --nonblock "$fd"; then
        error "Could not acquire lock via lock file '$lock_file'. Is Factorio still running?"
        exit "$ERROR_GENERAL"
    fi
}

# Define error codes.
SUCCESS=0
ERROR_ARGUMENTS=1
ERROR_CONFIGURATION=2
ERROR_GENERAL=3

# Disable debug and quiet modes by default.
debug=0
quiet=0
verbose=0
force_colours=0

# Set-up some default paths.
manager_directory="$HOME/.factorio"
game_installations_directory="$manager_directory/.game_installations"

# If no arguments were given, just show usage help.
if [[ -z ${1-} ]]; then
    setup_colours
    short_usage
    exit "$SUCCESS"
fi

# Parse the arguments
while getopts "VCqdvh" opt; do
    case "$opt" in
        V) verbose=1;;
        C) force_colours=1;;
	q) # shellcheck disable=SC2034 # part of standard Bash script template.
           quiet=1;;
	d) debug=1;;
        v) version
           exit "$SUCCESS";;
        h) usage
           exit "$SUCCESS";;
        *) usage
           exit "$ERROR_ARGUMENTS";;
    esac
done
i=$OPTIND
shift $((i-1))

setup_colours

# Make sure the manager home directory exists.
if [[ ! -e $manager_directory ]]; then
    info "Creating Factorio Manager home directory under: $manager_directory"
    mkdir -p "$manager_directory"
fi

command="$1"
shift


#==============#
# set-game-dir #
#==============#
if [[ $command == set-game-dir ]]; then

    # Read and verify additional positional arguments.
    game_installations_directory_target="${1-}"
    shift

    if [[ -z $game_installations_directory_target ]]; then
        error "Missing argument: GAME_INSTALLATIONS_DIRECTORY"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ ! -d $game_installations_directory_target ]]; then
        error "No such directory: $game_installations_directory"
        exit "$ERROR_GENERAL"
    fi

    # For directory to be usable, it must be either empty or contain
    # at least one Factorio installation.
    shopt -s nullglob
    candidates=("$game_installations_directory_target"/*)
    shopt -u nullglob

    factorio_versions_found=0
    for candidate in "${candidates[@]}"; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            (( factorio_versions_found++ ))
        fi
    done

    if [[ ${#candidates[@]} != 0 ]] && (( factorio_versions_found == 0 )); then
        error "Specified directory must be either empty or must contain at least one Factorio installation already."
        exit "$ERROR_GENERAL"
    fi

    # Update the link
    if [[ -L $game_installations_directory ]]; then
        rm "$game_installations_directory"
    fi

    if ! ln -s "$game_installations_directory_target" "$game_installations_directory"; then
        error "Could not create symlink from '$game_installations_directory_target' to '$game_installations_directory'."

        exit "$ERROR_GENERAL"
    fi


#==========#
# versions #
#==========#
elif [[ $command == versions ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    echo "Locally available Factorio versions:"
    echo

    # Find all sub-directories that are Factorio installations.
    for candidate in "$game_installations_directory"/*; do
        if [[ -d $candidate && -e $candidate/bin/x64/factorio ]]; then
            echo "  - $(basename "$candidate")"
        fi
    done
    echo


#======#
# list #
#======#
elif [[ $command == list ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    echo "Available instances:"
    echo

    # Find all sub-directories that are valid instances.
    for candidate in "$manager_directory"/*; do
        if [[ -f $candidate/instance.conf ]]; then
            # shellcheck source=/dev/null
            source "$candidate/instance.conf"
            # shellcheck disable=SC2154 # game_version is read from the configuration file
            echo "  - $(basename "$candidate") ($game_version)"
        fi
    done
    echo


#========#
# create #
#========#
elif [[ $command == create ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Calculate derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"

    # Verify arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Make sure new instance directory can be used.
    validate_path_or_terminate "instance_directory_new" "$instance_directory" "$ERROR_ARGUMENTS"

    select_factorio_version "$game_installations_directory" || exit "$ERROR_GENERAL"

    # Set-up the instance.
    mkdir "$instance_directory"
    mkdir "$instance_directory/mods"
    echo "{}" > "$instance_directory/mods/mod-list.json"

    cat <<EOF > "$instance_config"
game_version="$game_version_selected"
EOF

    # @TODO: If we could somehow obtain stock config.ini file without
    # having to first run Factorio, that would be great. As it is, the
    # user will presented with warning about corrupt config.ini when
    # running the instance for the first time.
    cat <<EOF > "$game_config"
[path]
read-data=__PATH__executable__/../../data
write-data=${instance_directory}

[general]
locale=

[other]
check-updates=false
enable-crash-log-uploading=false

[interface]

[controls]

[sound]

[map-view]

[debug]

[multiplayer-lobby]

[graphics]
EOF

    echo
    warning "Factorio Manager has created a minimal empty configuration file for Factorio under $game_config."
    warning "Since the generated configuration file is almost empty, Factorio will complain that the file seems corrupt."
    warning "Factorio will offer to fix the corrupted configuration file by filling-in the missing information during the first startup."
    warning "It should be safe to accept this. This warning will be shown by Factorio only the first time."


#========#
# launch #
#========#
elif [[ $command == launch ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Set-up derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"
    server_config="$instance_directory/server-settings.json"

    # Verify arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Update instance write directory prior to launching - this is a
    # failsafe in case it got changed by hand or perhaps the value
    # comes from backups of a copied instance.
    current_write_data=$(grep "^write-data=" "$game_config")
    expected_write_data="write-data=${instance_directory}"

    if [[ $current_write_data != "$expected_write_data" ]]; then
        warning "Incorrect path specified for write-data in game configuration file: $game_config"
        warning "Current configuration is: $current_write_data"
        warning "Configuration will be replaced with: $expected_write_data"
        sed -i -e "s#^write-data=.*#$expected_write_data#" "$game_config"
    fi

    # Read launcher configuration for the instance.
    # shellcheck source=/dev/null
    source "$instance_config"

    if [[ -z $game_version ]]; then
        error "Missing game version information in $game_config."
        exit "$ERROR_CONFIGURATION"
    fi

    # Set-up paths for launching the game, and ensure they still exist
    # (versions can be removed by user).
    game_directory="${game_installations_directory}/${game_version}"
    factorio_bin="$game_directory/bin/x64/factorio"

    if [[ ! -e $factorio_bin ]]; then
        error "Could not locate Factorio binary under: $factorio_bin"
        error "Factorio $game_version installation may have been removed from game installations directory:"
        error "   $(readlink -f "$game_installations_directory")"
        exit "$ERROR_CONFIGURATION"
    fi

    # Launch instance
    if [[ -e $server_config ]]; then
        "$factorio_bin" --config "$game_config" --start-server "$instance_directory/saves/default.zip"
    else
        "$factorio_bin" --config "$game_config"
    fi


#========#
# backup #
#========#
elif [[ $command == backup ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    description="${2-}"
    shift 2

    # Use timestamp-based names for backups.
    timestamp=$(date +%Y-%m-%d_%H:%M:%S)

    # Set-up derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"
    lock_file="$instance_directory/.lock"

    backup_destination="$instance_directory/.bak/$timestamp"
    backup_description="$backup_destination/.description"

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Validate destination path for backup directory can be used.
    validate_path_or_terminate "backup_directory_new" "$backup_destination" "$ERROR_GENERAL"

    (
        # shellcheck disable=SC2094 # Lock file is not being read from.
        lock "$lock_file" 200

        # Backup the instance. Clean-up the backup destination in case of failure.
        mkdir -p "$backup_destination"
        if ! cp -a "$instance_directory"/* "$backup_destination"; then
            error "Could not create backup under: $backup_destination"
            rm -rf "$backup_destination"
            exit "$ERROR_GENERAL"
        fi

        # Store (optional) description.
        if [[ -n $description ]]; then
            echo "$description" > "$backup_description"
        fi

        success "Backup saved to: $backup_destination"

    ) 200>"$lock_file"


#==============#
# list-backups #
#==============#
elif [[ $command == list-backups ]]; then

    # Read positional arguments.
    instance="${1-}"
    shift

    # Set-up derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"
    instance_backup_directory="$instance_directory/.bak"

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Read current game version.
    # shellcheck source=/dev/null
    source "$instance_config"
    current_game_version="$game_version"
    unset game_version

    # Set-up list of backup directories.
    shopt -s nullglob
    # Glob expression for matching YYYY-MM-DD-hh:mm:ss format.
    backup_directories=("$instance_backup_directory"/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9]:[0-9][0-9]:[0-9][0-9])
    shopt -s nullglob

    # Show available backups to the user.
    if (( ${#backup_directories[@]} == 0 )); then
        echo "No backups are available for instance $(colorecho -n green "$instance")."
    else
        echo "Available backups for instance $(colorecho -n green "$instance") (current version $(colorecho -n green "$current_game_version"))."
        echo

        for backup_directory in "${backup_directories[@]}"; do

            backup_date=$(basename "$backup_directory")

            # Read instance configuration for backup.
            # shellcheck source=/dev/null
            source "$backup_directory/instance.conf"

            if [[ -f "$backup_directory/.description" ]]; then
                backup_description=$(<"$backup_directory/.description")
                echo "  - $backup_date - version $(colorecho -n green "$game_version") ($backup_description)"
            else
                echo "  - $backup_date - version $(colorecho -n green "$game_version")"
            fi

        done

        echo

    fi


#=========#
# restore #
#=========#
elif [[ $command == restore ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    backup_name="${2-}"
    shift 2

    # Set-up derived values.
    instance_directory="$manager_directory/$instance"
    restore_source="$instance_directory/.bak/$backup_name"
    backup_instance_config="$restore_source/instance.conf"
    lock_file="$instance_directory/.lock"

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ -z $backup_name ]]; then
        error "Missing argument: BACKUP_NAME"
        exit "$ERROR_ARGUMENTS"
    fi

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Validate that backup directory contains valid backup.
    validate_path_or_terminate "backup_directory" "$restore_source" "$ERROR_ARGUMENTS"

    (
        # shellcheck disable=SC2094 # Lock file is not being read from.
        lock "$lock_file" 200

        # Set-up a list of files and directories that will get removed.
        shopt -s nullglob
        entries_to_remove=("$instance_directory"/*)
        shopt -u nullglob

        # Present user with extensive warning on consequences.
        echo
        warning "You are about to replace current instance's files, including (but not limited to):"
        warning
        warning "  - configuration files"
        warning "  - blueprints"
        warning "  - savegames"
        warning "  - achievements"
        warning "  - mods"
        warning
        warning "All instance files will be replaced by files from specified backup."

        # Display backup information.
        echo
        if [[ -f "$restore_source/.description" ]]; then
            backup_description=$(<"$restore_source/.description")
            backup_info="$backup_name ($backup_description)"
        else
            backup_info="$backup_name"
        fi
        echo "Restore instance $(colorecho -n green "$instance") from backup: $(colorecho -n green "$backup_info")"
        echo

        # Show user what files will be removed.
        if [[ ${#entries_to_remove[@]} == 0 ]]; then
            echo "Instance directory is currently empty. No files will be removed."
            echo
        else
            echo "Files and directories that will be removed:"
            echo
            for entry in "${entries_to_remove[@]}"; do
                echo "  - $entry"
            done
            echo
        fi

        # Request from user to confirm the operation.
        critical_confirmation "Are you sure you want to proceed?" \
                              "Aborted restore process, no changes have been made to instance files." \
                              "$ERROR_GENERAL"

        if [[ ${#entries_to_remove[@]} != 0 ]]; then
            if ! rm -rf "${entries_to_remove[@]}"; then
                error "Failed to remove existing instance files."
                exit "$ERROR_GENERAL"
            fi
        fi

        if ! cp -a "$restore_source"/* "$instance_directory"; then
            error "Failed to restore backup from: $restore_source"
            exit "$ERROR_GENERAL"
        fi

        success "Instance restored from backup."

    ) 200>"$lock_file"


#===============#
# remove-backup #
#===============#
elif [[ $command == remove-backup ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    backup_name="${2-}"
    shift 2

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ -z $backup_name ]]; then
        error "Missing argument: BACKUP_NAME"
        exit "$ERROR_ARGUMENTS"
    fi

    # Set-up derived values.
    instance_directory="$manager_directory/$instance"
    removal_target="$instance_directory/.bak/$backup_name"
    backup_instance_config="$removal_target/instance.conf"
    lock_file="$instance_directory/.lock"

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Validate that backup directory contains valid backup.
    validate_path_or_terminate "backup_directory" "$removal_target" "$ERROR_ARGUMENTS"

    # Read backup instance configuration.
    # shellcheck source=/dev/null
    source "$backup_instance_config"

    # Present user with warning.
    echo
    if [[ -f "$removal_target/.description" ]]; then
        backup_description=$(<"$removal_target/.description")
        backup_info="$(colorecho green "$backup_name"), version $(colorecho green "$game_version") ($backup_description)"
    else
        backup_info="$(colorecho green "$backup_name"), version $(colorecho green "$game_version")"
    fi

    warning "You are about to remove an instance backup. All files belonging to specified backup will be removed."
    echo
    echo "Instance: $(colorecho -n green "$instance")"
    echo
    echo "Backup: $(colorecho -n green "$backup_info")"
    echo
    echo "Files and directories that will be removed:"
    echo
    echo " - $removal_target"
    echo

    # Request from user to confirm the operation.
    critical_confirmation "Are you sure you want to proceed?" \
                          "Aborted backup removal, no changes have been made to backup files." \
                          "$ERROR_GENERAL"

    if ! rm -rf "$removal_target"; then
        error "Failed to remove existing instance files."
        exit "$ERROR_GENERAL"
    fi

    success "Backup removed."


#=============#
# set-version #
#=============#
elif [[ $command == set-version ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Set-up derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Load instance configuration.
    # shellcheck source=/dev/null
    source "$instance_config"

    # Display list of available Factorio versions.
    echo "Current version used for instance $(colorecho -n green "$instance") is $(colorecho -n green "$game_version")."
    echo
    select_factorio_version "$game_installations_directory" "$game_version" "current" || exit "$ERROR_GENERAL"
    echo

    # Change instance game version.
    if [[ $game_version_selected == "$game_version" ]]; then
        info "Current version has been kept."
    else
        sed -i -e "s/^game_version=.*/game_version=$game_version_selected/" "$instance_config"
        success "Version changed to: $(colorecho -n green "$game_version_selected")"
    fi


#======#
# info #
#======#
elif [[ $command == info ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Set-up derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Load instance configuration.
    # shellcheck source=/dev/null
    source "$instance_config"

    # Basic information.
    echo "Instance name: $(colorecho -n green "$instance")"

    if [[ -e "$game_installations_directory/$game_version" ]]; then
        echo "Game version: $(colorecho -n green "$game_version")"
    else
        echo "Game version: $(colorecho -n red "$game_version [not available locally]")"
    fi

    echo "Instance path: $(colorecho -n green "$instance_directory")"
    echo

    # Mod information.
    shopt -s nullglob
    mod_files=("$instance_directory/mods"/*.zip)
    mod_list="$instance_directory/mods/mod-list.json"
    shopt -u nullglob

    if [[ ${#mod_files[@]} == 0 ]]; then
        echo "Available mods: none"

    # Listing using just regular tools.
    elif ! hash jq 2>/dev/null; then
        echo "Available mods:"
        echo

        # Determine if mod is enabled by default or not when added to
        # mods directory (and is not yet listed in the mod list file).
        if grep -i -q "^[[:blank:]]*enable-new-mods=false" "$game_config"; then
            enable_new_mods="false"
        else
            enable_new_mods="true"
        fi

        # Process every mod found.
        for mod_file in "${mod_files[@]}"; do

            if [[ -f $mod_file ]]; then
                # Extract basic information about mod from the filename.
                mod_basename=$(basename "$mod_file" .zip)
                mod_name="${mod_basename%_*}"
                mod_version="${mod_basename##*_}"

                # Determine if mod is enabled or not.

                if grep -A1 "\"name\": \"$mod_name\"" "$mod_list" | tail -n1 | grep -q '"enabled": false'; then
                    color="$_text_yellow"
                elif grep -A1 "\"name\": \"$mod_name\"" "$mod_list" | tail -n1 | grep -q '"enabled": true'; then
                    color=""
                elif [[ $enable_new_mods == "false" ]]; then
                    color="$_text_yellow"
                else
                    color=""
                fi

                # Show colored-information for the mod.
                printf "$color  - %-48s %8s $_text_reset\n" "$mod_name" "$mod_version"
                if (( verbose == 1 )); then
                    mod_info=$(unzip -Z1 "$mod_file" | grep "info\.json" | head -n1)
                    mod_description=$(unzip -p "$mod_file" "$mod_info" | grep '"description":' | sed -e 's/\r//g;s/[^"]*"description": //;s/^"//;s/"$//')
                    mod_description=$(echo -e "$mod_description" | fold -s -w 50 | sed -e 's/^/    /')
                    mod_url="https://mods.factorio.com/mod/${mod_info}"
                    echo
                    echo "    ($mod_url)"
                    echo
                    echo "$mod_description"
                    echo
                fi
            fi

        done

    # Listing using the jq utility.
    elif hash jq 2>/dev/null; then
        echo "Available mods (enabled/${_text_yellow}disabled${_text_reset}):"
        echo

        # Determine if mod is enabled by default or not when added to
        # mods directory (and is not yet listed in the mod list file).
        if grep -i -q "^[[:blank:]]*enable-new-mods=false" "$game_config"; then
            enable_new_mods="false"
        else
            enable_new_mods="true"
        fi

        # Query string used in jq tool to determine if mod is enabled
        # or not. Take note that this string should remain
        # single-quoted, and that $ expansions are actually done
        # internally in jq itself. Query accepts two vars - mod_name
        # and enable_new_mods.
        # shellcheck disable=SC2016 # The $enable_new_mods is meant to be interpreted by jq, not bash.
        jq_is_enabled_query='.mods | map(select(.name==$mod_name))[0] // {"name": "default", "enabled": $enable_new_mods} | .enabled'

        # Process every mod found.
        for mod_file in "${mod_files[@]}"; do

            if [[ -f $mod_file ]]; then

                # Extract basic information about mod from the filename.
                mod_basename=$(basename "$mod_file" .zip)
                mod_name="${mod_basename%_*}"
                mod_version="${mod_basename##*_}"

                # Determine if mod is enabled or not.
                if jq -e \
                      --arg "mod_name" "$mod_name" \
                      --argjson "enable_new_mods" "$enable_new_mods" \
                      "$jq_is_enabled_query" "$mod_list" > /dev/null; then
                    color=""
                else
                    color="$_text_yellow"
                fi

                # Show colored-information for the mod.
                printf "$color  - %-48s %8s $_text_reset\n" "$mod_name" "$mod_version"
                if (( verbose == 1 )); then
                    mod_info=$(unzip -Z1 "$mod_file" | grep "info\.json" | head -n1)
                    mod_description=$(unzip -p "$mod_file" "$mod_info" | jq -r -e '.description' | fold -s -w 50 | sed -e 's/^/    /')
                    mod_url="https://mods.factorio.com/mod/${mod_info}"
                    echo
                    echo "    ($mod_url)"
                    echo
                    echo "$mod_description"
                    echo
                fi
            fi
        done
    fi
    echo

    # Call self for displaying list of backups. Better than duplicating code.
    "$program" list-backups "$instance" | sed -e "s/^Available backups for instance.*/Available backups:/"


#========#
# remove #
#========#
elif [[ $command == remove ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Set-up derived values.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    lock_file="$instance_directory/.lock"

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    (
        # shellcheck disable=SC2094 # Lock file is not being read from.
        lock "$lock_file" 200

        # Set-up a list of files and directories that will get removed.
        shopt -s nullglob dotglob
        entries_to_remove=("$instance_directory"/*)
        shopt -u nullglob dotglob

        # Present user with extensive warning on consequences.
        echo
        warning "You are about to remove all instance's files, including (but not limited to):"
        warning
        warning "  - configuration files"
        warning "  - blueprints"
        warning "  - savegames"
        warning "  - achievements"
        warning "  - mods"
        warning "  - backups"
        warning
        warning "All instance files will be removed."
        echo

        # Show user what files will be removed.
        if [[ ${#entries_to_remove[@]} == 0 ]]; then
            echo "Instance directory is currently empty. No files will be removed."
            echo
        else
            echo "Files and directories that will be removed:"
            echo
            echo "  - $instance_directory"
            for entry in "${entries_to_remove[@]}"; do
                echo "  - $entry"
            done
            echo
        fi

        # Display instance information.
        # shellcheck source=/dev/null
        source "$instance_config"
        echo "Instance name:    $(colorecho -n green "$instance")"
        echo "Instance version: $(colorecho -n green "$game_version")"
        echo

        # Request from user to confirm the operation.
        critical_confirmation "Are you sure you want to proceed?" \
                              "Aborted instance removal, no changes have been made to instance files." \
                              "$ERROR_GENERAL"

        if [[ ${#entries_to_remove[@]} != 0 ]]; then
            if ! rm -rf "${entries_to_remove[@]}"; then
                error "Failed to remove instance files."
                exit "$ERROR_GENERAL"
            fi
        fi

        if ! rmdir "$instance_directory"; then
            error "Failed to remove instance files."
            exit "$ERROR_GENERAL"
        fi

        success "Instance removed."

    ) 200>"$lock_file"


#======#
# copy #
#======#
elif [[ $command == copy ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    source_instance="${1-}"
    destination_instance="${2-}"
    shift 2

    # Verify positional arguments.
    if [[ -z $source_instance ]]; then
        error "Missing argument: SOURCE_INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ -z $destination_instance ]]; then
        error "Missing argument: DESTINATION_INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Calculate derived variables.
    source_instance_directory="$manager_directory/$source_instance"
    source_instance_config="$source_instance_directory/instance.conf"
    source_lock_file="$source_instance_directory/.lock"

    destination_instance_directory="$manager_directory/$destination_instance"
    destination_instance_config="$destination_instance_directory/instance.conf"

    # Validate that source instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$source_instance_directory" "$ERROR_ARGUMENTS"

    # Make sure destination instance directory can be used.
    validate_path_or_terminate "instance_directory_new" "$destination_instance_directory" "$ERROR_ARGUMENTS"

    (
        # shellcheck disable=SC2094 # Lock file is not being read from.
        lock "$source_lock_file" 200

        # Load source instance configuration.
        # shellcheck source=/dev/null
        source "$source_instance_config"

        # Display list of available Factorio versions.
        echo
        echo "If you wish to, you can now change version of Factorio used for destination instance, or keep the same version as for source instance."
        echo

        select_factorio_version "$game_installations_directory" "$game_version" "current" || exit "$ERROR_GENERAL"
        echo

        # Check if user wants to copy backup files as well.
        copy_backups=""

        until [[ $copy_backups == "y" || $copy_backups == "n" ]]; do
            echo
            read -rn1 -p "Would you like to copy backup files as well? (y/n)" copy_backups
            echo
            copy_backups="${copy_backups,,}"

            if [[ $copy_backups != "y" && $copy_backups != "n" ]]; then
                echo
                error "Please answer only with 'y' or 'n'."
            fi
        done

        # Set-up a list of files and directories to copy.
        entries_to_copy=("$source_instance_directory"/*)

        if [[ $copy_backups == "y" && -e "$source_instance_directory/.bak" ]]; then
             entries_to_copy+=("$source_instance_directory/.bak")
        fi

        # Create copy of source instance.
        mkdir "$destination_instance_directory"
        cp -a "${entries_to_copy[@]}" "$destination_instance_directory/"

        # Update write-data directory of destination instance,
        # including the backups.
        write_data="write-data=${destination_instance_directory}"
        find "$destination_instance_directory/" -type f -name config.ini -exec \
             sed -i -e "s#^write-data=.*#$write_data#" '{}' \;

        sed -i -e "s/^game_version=.*/game_version=$game_version_selected/" "$destination_instance_config"

        success "Created new instance $(colorecho -n green "$destination_instance") using version $(colorecho -n green "$game_version_selected") as copy of instance $(colorecho -n green "$source_instance")."

    ) 200>"$source_lock_file"


#========#
# import #
#========#
elif [[ $command == import ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    source_directory="${2-}"
    shift 2

    # Verify positional arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ -z $source_directory ]]; then
        error "Missing argument: SOURCE_DIRECTORY"
        exit "$ERROR_ARGUMENTS"
    fi

    # Calculate derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"

    source_lock_file="$source_directory/.lock"

    # Make sure new instance directory can be used.
    validate_path_or_terminate "instance_directory_new" "$instance_directory" "$ERROR_ARGUMENTS"

    # Make sure that the import source is valid (should be Factorio
    # installation directory).
    validate_path_or_terminate "instance_import_source" "$source_directory" "$ERROR_ARGUMENTS"

    # List of entries to import from the source directory. Keep
    # separate array of keys for sorting purposes.
    declare -A import_entries=()
    declare -a import_entries_keys
    key="achievements-modded.dat"
    import_entries[$key]="contains achivement information for modded plays"
    import_entries_keys+=("$key")

    key="achievements.dat"
    import_entries[$key]="contains achievement information for vanilla plays"
    import_entries_keys+=("$key")

    key="archive"
    import_entries[$key]="contains desync reports"
    import_entries_keys+=("$key")

    key="blueprint-storage.dat"
    import_entries[$key]="contains global (non-savegame specific) blueprints"
    import_entries_keys+=("$key")

    key="config/config.ini"
    import_entries[$key]="contains game configuration, including things like shortcuts etc."
    import_entries_keys+=("$key")

    key="crop-cache.dat"
    import_entries[$key]="purpose is not known"
    import_entries_keys+=("$key")

    key="factorio-current.log"
    import_entries[$key]="contains logs from the currently running game"
    import_entries_keys+=("$key")

    key="factorio-previous.log"
    import_entries[$key]="contains logs from the previously running game"
    import_entries_keys+=("$key")

    key="mods"
    import_entries[$key]="contains mods and mod settings"
    import_entries_keys+=("$key")

    key="player-data.json"
    import_entries[$key]="contains global information about the player, such as username, login token, chat history, etc."
    import_entries_keys+=("$key")

    key="saves"
    import_entries[$key]="contains savegames"
    import_entries_keys+=("$key")

    # Display list of available Factorio versions and let user pick one.
    echo "Factorio version must  be selected manually for imported instances."
    echo
    select_factorio_version "$game_installations_directory" || exit "$ERROR_GENERAL"

    (
        # shellcheck disable=SC2094 # Lock file is not being read from.
        lock "$source_lock_file" 200

        # Create instance directory.
        mkdir "$instance_directory"

        # Copy files and directories.
        echo
        declare -a missing_import_entries=()
        for source_entry in "${import_entries_keys[@]}"; do
            source_entry_path="$source_directory/$source_entry"
            if [[ -e $source_entry_path ]]; then
                info "Importing $(colorecho -n blue "$source_entry")..."

                if ! cp -a "$source_entry_path" "$instance_directory/"; then
                    error "Could not import $source_entry from $source_entry_path (see above for errors)."
                    exit "$ERROR_GENERAL"
                fi
            else
                missing_import_entries+=("$source_entry")
            fi

            # Copy the configuration file.
        done

        echo

        cat <<EOF > "$instance_config"
game_version="$game_version_selected"
EOF

        # Fix write-data in config.ini
        write_data="write-data=${instance_directory}"
        sed -i -e "s#^write-data=.*#$write_data#" "$game_config"

        if [[ ${#missing_import_entries[@]} != 0 ]]; then
            warning "A number of files or directories were missing from the specified source."
            warning "For some of the entries this is perfectly normal, but you should verify that no critical files have been missed by mistake before switching to using this instance."
            echo
            for missing_import_entry in "${missing_import_entries[@]}"; do
                echo "$(colorecho blue "$missing_import_entry"), ${import_entries[$missing_import_entry]}"
                echo
            done
            warning "Press any key to continue."
            read -rn1
        fi

        success "Finished import of instance $(colorecho -n green "$instance")."

    ) 200>"$source_lock_file"


#===============#
# create-server #
#===============#
elif [[ $command == create-server ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Calculate derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"
    server_config="$instance_directory/server-settings.json"
    saves_directory="$instance_directory/saves"
    main_save="$saves_directory/default.zip"

    # Verify arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Make sure new instance directory can be used.
    validate_path_or_terminate "instance_directory_new" "$instance_directory" "$ERROR_ARGUMENTS"

    select_factorio_version "$game_installations_directory" || exit "$ERROR_GENERAL"

    # Grab server settings from user.
    echo "You will now be prompted to provide settings for the server, with some pre-filled settings."
    echo "Do not change settings marked with [EXPERT] unless you know what you are doing."
    echo
    read_server_settings "$instance"

    # Set-up the instance.
    mkdir "$instance_directory"
    mkdir "$instance_directory/mods"
    echo "{}" > "$instance_directory/mods/mod-list.json"

    cat <<EOF > "$instance_config"
game_version="$game_version_selected"
EOF
    cat <<EOF > "$game_config"
[path]
read-data=__PATH__executable__/../../data
write-data=${instance_directory}

[general]
locale=

[other]
check-updates=false
enable-crash-log-uploading=false
port=${settings_value[port]}


[interface]

[controls]

[sound]

[map-view]

[debug]

[multiplayer-lobby]

[graphics]
EOF

    echo
    cat <<EOF >> "$server_config"
{
  "name": ${settings_value[name]},
  "description": ${settings_value[description]},
  "tags": ${settings_value[tags]},
  "max_players": ${settings_value[max_players]},
  "visibility":
  {
    "public": ${settings_value[public]},
    "lan": ${settings_value[lan]}
  },

  "_comment_credentials": "Your factorio.com login credentials. Required for games with visibility public",
  "username": ${settings_value[username]},
  "password": ${settings_value[password]},

  "_comment_token": "Authentication token. May be used instead of 'password' above.",
  "token": ${settings_value[token]},

  "game_password": ${settings_value[game_password]},

  "_comment_require_user_verification": "When set to true, the server will only allow clients that have a valid Factorio.com account",
  "require_user_verification": ${settings_value[require_user_verification]},

  "_comment_max_upload_in_kilobytes_per_second" : "optional, default value is 0. 0 means unlimited.",
  "max_upload_in_kilobytes_per_second": ${settings_value[max_upload_in_kilobytes_per_second]},

  "_comment_max_upload_slots" : "optional, default value is 5. 0 means unlimited.",
  "max_upload_slots": ${settings_value[max_upload_slots]},

  "_comment_minimum_latency_in_ticks": "optional one tick is 16ms in default speed, default value is 0. 0 means no minimum.",
  "minimum_latency_in_ticks": ${settings_value[minimum_latency_in_ticks]},

  "_comment_ignore_player_limit_for_returning_players": "Players that played on this map already can join even when the max player limit was reached.",
  "ignore_player_limit_for_returning_players": ${settings_value[ignore_player_limit_for_returning_players]},

  "_comment_allow_commands": "possible values are, true, false and admins-only",
  "allow_commands": ${settings_value[allow_commands]},

  "_comment_autosave_interval": "Autosave interval in minutes",
  "autosave_interval": ${settings_value[autosave_interval]},

  "_comment_autosave_slots": "server autosave slots, it is cycled through when the server autosaves.",
  "autosave_slots": ${settings_value[autosave_slots]},

  "_comment_afk_autokick_interval": "How many minutes until someone is kicked when doing nothing, 0 for never.",
  "afk_autokick_interval": ${settings_value[afk_autokick_interval]},

  "_comment_auto_pause": "Whether should the server be paused when no players are present.",
  "auto_pause": ${settings_value[auto_pause]},

  "only_admins_can_pause_the_game": ${settings_value[only_admins_can_pause_the_game]},

  "_comment_autosave_only_on_server": "Whether autosaves should be saved only on server or also on all connected clients. Default is true.",
  "autosave_only_on_server": ${settings_value[autosave_only_on_server]},

  "_comment_non_blocking_saving": "Highly experimental feature, enable only at your own risk of losing your saves. On UNIX systems, server will fork itself to create an autosave. Autosaving on connected Windows clients will be disabled regardless of autosave_only_on_server option.",
  "non_blocking_saving": ${settings_value[non_blocking_saving]},

  "_comment_segment_sizes": "Long network messages are split into segments that are sent over multiple ticks. Their size depends on the number of peers currently connected. Increasing the segment size will increase upload bandwidth requirement for the server and download bandwidth requirement for clients. This setting only affects server outbound messages. Changing these settings can have a negative impact on connection stability for some clients.",
  "minimum_segment_size": ${settings_value[minimum_segment_size]},
  "minimum_segment_size_peer_count": ${settings_value[minimum_segment_size_peer_count]},
  "maximum_segment_size": ${settings_value[maximum_segment_size]},
  "maximum_segment_size_peer_count": ${settings_value[maximum_segment_size_peer_count]}
}
EOF

    # Generate main save/map.
    info "Generating default savegame/map."
    game_directory="${game_installations_directory}/${game_version_selected}"
    factorio_bin="$game_directory/bin/x64/factorio"

    if ! "$factorio_bin" --config "$game_config" --create "$main_save"; then
        error "Failed to generate default savegame/map under: $main_save"
        exit "$ERROR_GENERAL"
    fi

    success "Created new server instance $(colorecho -n green "$instance")"


#=========#
# install #
#=========#
elif [[ $command == install ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    game_archive="${1-}"
    shift

    # Calculate derived variables.
    staging_directory="$game_installations_directory/.staging"
    game_staging_directory="$staging_directory/factorio"
    staging_factorio_bin="$game_staging_directory/bin/x64/factorio"

    # Verify arguments.
    if [[ -z $game_archive ]]; then
        error "Missing argument: GAME_ARCHIVE"
        exit "$ERROR_ARGUMENTS"
    fi

    validate_path_or_terminate "game_archive" "$game_archive" "$ERROR_ARGUMENTS"

    # Prepare staging directory.
    rm -rf "$staging_directory"
    mkdir "$staging_directory"

    # Extract the game version and verify it.
    tar --occurrence=1 --extract --file "$game_archive" --directory "$staging_directory" "factorio/bin/x64/factorio"

    game_version=$("$staging_factorio_bin" --version | grep '^Version' | sed -e 's/^Version: //;s/ .*//')

    if ! [[ $game_version =~ ^[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+$ ]]; then
        error "Could not parse version from output of command: $staging_factorio_bin --version"
        exit "$ERROR_GENERAL"
    fi

    # Check if version has already been installed.
    game_destination_directory="$game_installations_directory/$game_version"
    if [[ -e "$game_destination_directory" ]]; then
        error "Factorio $game_version already available under: $game_destination_directory"
        exit "$ERROR_GENERAL"
    fi

    # Unpack the full installation.
    info "Extracting the game installation, this might take a while."
    if ! tar --extract --file "$game_archive" --directory "$staging_directory"; then
        error "Could not extract game archive ($game_archive) to its staging directory ($staging_directory)."
        exit "$ERROR_GENERAL"
    fi

    # Move the game installation, and make it read-only.
    if ! mv "$game_staging_directory" "$game_destination_directory"; then
        error "Could not move the game from its staging directory ($game_staging_directory) to its destination directory ($game_destination_directory)."
        exit "$ERROR_GENERAL"
    fi
    if ! chmod -R u-w,g-w,o-w "$game_destination_directory"; then
        error "Could not write-protect the game directory ($game_destination_directory). Manual intervention might be required."
        exit "$ERROR_GENERAL"
    fi

    success "Successfully installed game version: $(colorecho -n green "$game_version")"


#==================#
# reset-server-map #
#==================#
elif [[ $command == reset-server-map ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    instance="${1-}"
    shift

    # Calculate derived variables.
    instance_directory="$manager_directory/$instance"
    instance_config="$instance_directory/instance.conf"
    game_config="$instance_directory/config.ini"
    server_config="$instance_directory/server-settings.json"
    main_save="$instance_directory/saves/default.zip"

    # Verify arguments.
    if [[ -z $instance ]]; then
        error "Missing argument: INSTANCE"
        exit "$ERROR_ARGUMENTS"
    fi

    # Validate that instance directory contains valid instance.
    validate_path_or_terminate "server_instance_directory" "$instance_directory" "$ERROR_ARGUMENTS"

    # Update instance write directory prior to launching - this is a
    # failsafe in case it got changed by hand or perhaps the value
    # comes from backups of a copied instance.
    current_write_data=$(grep "^write-data=" "$game_config")
    expected_write_data="write-data=${instance_directory}"

    if [[ $current_write_data != "$expected_write_data" ]]; then
        warning "Incorrect path specified for write-data in game configuration file: $game_config"
        warning "Current configuration is: $current_write_data"
        warning "Configuration will be replaced with: $expected_write_data"
        sed -i -e "s#^write-data=.*#$expected_write_data#" "$game_config"
    fi

    # Read launcher configuration for the instance.
    # shellcheck source=/dev/null
    source "$instance_config"

    if [[ -z $game_version ]]; then
        error "Missing game version information in $game_config."
        exit "$ERROR_CONFIGURATION"
    fi

    # Set-up paths for launching the game, and ensure they still exist
    # (versions can be removed by user).
    game_directory="${game_installations_directory}/${game_version}"
    factorio_bin="$game_directory/bin/x64/factorio"

    if [[ ! -e $factorio_bin ]]; then
        error "Could not locate Factorio binary under: $factorio_bin"
        error "Factorio $game_version installation may have been removed from game installations directory:"
        error "   $(readlink -f "$game_installations_directory")"
        exit "$ERROR_CONFIGURATION"
    fi

    # Request from user to confirm the destructive action.
    critical_confirmation "Resetting the server map will wipe the default save game as well." \
                          "Aborted server map reset, no changes have been made to instance files." \
                          "$ERROR_GENERAL"

    if ! rm -f "$main_save"; then
        error "Could not remove the default save game."
        exit "$ERROR_GENERAL"
    fi

    if ! "$factorio_bin" --config "$game_config" --create "$main_save"; then
        error "Failed to generate default savegame/map under: $main_save"
        exit "$ERROR_GENERAL"
    fi


#========#
# rename #
#========#
elif [[ $command == rename ]]; then

    # Make sure game installations directory has been set.
    validate_path_or_terminate "game_installations_directory" "$game_installations_directory" "$ERROR_CONFIGURATION"

    # Read positional arguments.
    current_name="${1-}"
    new_name="${2-}"
    shift 2

    # Verify positional arguments.
    if [[ -z $current_name ]]; then
        error "Missing argument: CURRENT_NAME"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ -z $new_name ]]; then
        error "Missing argument: NEW_NAME"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ $current_name == "$new_name" ]]; then
        error "New name must differ from current name."

        exit "$ERROR_ARGUMENTS"
    fi

    # Calculate derived variables.
    current_instance_directory="$manager_directory/$current_name"
    current_instance_config="$current_instance_directory/instance.conf"
    current_instance_lock_file="$current_instance_directory/.lock"
    new_instance_directory="$manager_directory/$new_name"

    # Validate that source instance directory contains valid instance.
    validate_path_or_terminate "instance_directory" "$current_instance_directory" "$ERROR_ARGUMENTS"

    # Make sure destination instance directory can be used.
    validate_path_or_terminate "instance_directory_new" "$new_instance_directory" "$ERROR_ARGUMENTS"

    (
        # shellcheck disable=SC2094 # Lock file is not being read from.
        lock "$current_instance_lock_file" 200

        # Load source instance configuration.
        # shellcheck source=/dev/null
        source "$current_instance_config"

        # Rename the instance.
        mv "$current_instance_directory" "$new_instance_directory"

        # Update write-data directory of destination instance,
        # including the backups.
        write_data="write-data=${new_instance_directory}"
        find "$new_instance_directory/" -type f -name config.ini -exec \
             sed -i -e "s#^write-data=.*#$write_data#" '{}' \;

        success "Renamed instance $(colorecho -n green "$current_name") to $(colorecho -n green "$new_name")."

    ) 200>"$current_instance_lock_file"
else
    error "Invalid command: $command"

    exit "$ERROR_ARGUMENTS"
fi