Files @ 8cd955bce0d2
Branch filter:

Location: majic-scripts/games/factorio_manager.sh

branko
Noticket: Refactor validation of server settings in Factorio Manager:

- Introduce dedicated validation function.
- Drop some unused variables.
- Validate settings while they are being prepared for the JSON file.
   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
#!/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.1"

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] copy SOURCE_INSTANCE DESTINATION_INSTANCE
  $program [OPTIONS] remove INSTANCE
  $program [OPTIONS] import INSTANCE SOURCE_DIRECTORY

  $program [OPTIONS] versions
  $program [OPTIONS] set-version INSTANCE

  $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.

A single Factorio version installation (base files) can be used by
multiple instances, but each instance is bound to a specific version
of Factorio.

Factorio Manager keeps instances in sub-directories under the
~/.factorio/ directory. Sub-directories are named after the
instances. 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, and
they all expect different positional parameters:


set-game-dir GAME_INSTALLATIONS_DIRECTORY

    Sets the passed-in directory path as the base directory where
    different versions of Factorio will be looked-up. Each
    sub-directory within this directory should be named after the
    version of Factorio it represents, and should be the base
    directory under which the Factorio installation files can be
    found.


versions

    Shows locally available Factorio versions.


list

    Lists available Factorio instances, and shows some basic
    information about them.


create INSTANCE

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


launch INSTANCE

    Launches an instance with the given name.

    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).


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.


list-backups INSTANCE

    Lists available backups of an instance, including description (if any is set).


$program accepts the following options:

    -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
}

# 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 )); 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=""

    _bg_black=""
    _bg_red=""
    _bg_green=""
    _bg_yellow=""
    _bg_blue=""
    _bg_purple=""
    _bg_cyan=""
    _bg_white=""
fi

# Make the colors available via an associative array as well.
declare -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

    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 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
        [[ $value == true || $value == false ]] && result=0 || colorecho "red" "$name must be a boolean [true|false]."

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

    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="" validation_passed 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 -n1 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 -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
                let 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
}

# 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

# 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
    short_usage
    exit "$SUCCESS"
fi

# Parse the arguments
while getopts "qdvh" opt; do
    case "$opt" in
	q) quiet=1;;
	d) debug=1;;
        v) version
           exit "$SUCCESS";;
        h) usage
           exit "$SUCCESS";;
        *) usage
           exit "$ERROR_ARGUMENTS";;
    esac
done
i=$OPTIND
shift $(($i-1))

# 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="${1-}"
    shift

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

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

    # Set-up additional derived variables.
    symlink="$manager_directory/.game_installations"

    # Verify that at least one Factorio instance can be found.
    factorio_versions_found=0
    for candidate in "$game_installations_directory"/*; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            let factorio_versions_found++
        fi
    done

    if (( $factorio_versions_found == 0 )); then
        error "Could not locate any Factorio installations under: $game_installations_directory"

        exit "$ERROR_GENERAL"
    fi

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

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

        exit "$ERROR_GENERAL"
    fi

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

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

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    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
    echo "Available instances:"
    echo

    # Find all sub-directories that are valid instances.
    for candidate in "$manager_directory"/*; do
        if [[ -f $candidate/instance.conf ]]; then
            source "$candidate/instance.conf"
            echo "  - $(basename "$candidate") ($game_version)"
        fi
    done
    echo

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

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    # 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

    if [[ -e $instance_directory ]]; then
        error "Instance already exists."
        exit "$ERROR_ARGUMENTS"
    fi

    # Display list of available Factorio versions and let user pick one.
    echo "The following versions of Factorio are locally available:"
    echo

    for candidate in "$game_installations_directory"/*; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            echo "  - $(basename "$candidate")"
        fi
    done

    echo

    echo -n "Please specify what version you would like to use: "
    read game_version_selected

    # Validate user input.
    if [[ ! -f "$game_installations_directory/$game_version_selected/bin/x64/factorio" ]]; then
        error "Requested version not locally available: $game_version_selected"
        exit "$ERROR_ARGUMENTS"
    fi

    # 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."
    echo
    echo "Please read the warning above, and press any key to continue."
    read

elif [[ $command == launch ]]; 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"
    server_config="$instance_directory/server-settings.json"

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

    if [[ ! -f $instance_config ]]; then
        error "Missing instance configuration file: $instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $game_config ]]; then
        error "Missing game configuration file: $game_config"
        exit "$ERROR_GENERAL"
    fi

    # Update instance write directory prior to launching - this is a
    # failsafe in case it got changed by hand through some other means
    # (or maybe it was copied over from another 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.
    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

elif [[ $command == backup ]]; then
    # 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_directory="$instance_directory/.bak"
    backup_destination="$backup_directory/$timestamp"
    backup_description="$backup_destination/.description"

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

    # Verify that we are trying to backup an actual instance.
    if [[ ! -f $instance_config ]]; then
        error "Missing instance configuration file: $instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $game_config ]]; then
        error "Missing game configuration file: $game_config"
        exit "$ERROR_GENERAL"
    fi

    # Make sure we do not overwrite the backup destination by mistake
    # - although highly unlikely unless user spams the backup command.
    if [[ -e $backup_destination ]]; then
        error "Backup already exists: $backup_destination"
    fi

    (

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

        function remove_lock() {
            rm "$lock_file"
        }

        trap remove_lock EXIT

        # 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"
    backup_directory="$instance_directory/.bak"

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

    # Verify instance.
    if [[ ! -d $instance_directory ]]; then
        error "No such instance: $instance"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ ! -f $instance_config ]]; then
        error "Missing instance configuration file: $instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $game_config ]]; then
        error "Missing game configuration file: $game_config"
        exit "$ERROR_GENERAL"
    fi

    # Extended regular expression for matching YYYY-MM-DD-hh:mm:ss format.
    backup_destination_name_pattern="[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}_[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}"

    # Read current game version.
    source "$instance_config"
    current_game_version="$game_version"
    unset game_version

    # Detect and show available backups to the user.
    if [[ ! -d $backup_directory ]] || ! ls "$backup_directory" | grep -q -E "^$backup_destination_name_pattern\$"; 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_destination in "$backup_directory"/*; do

            if [[ $backup_destination =~ $backup_destination_name_pattern ]]; then
                backup_date=$(basename "$backup_destination")

                # Read instance configuration for backup.
                source "$backup_destination/instance.conf"

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


            fi
        done

        echo

    fi

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

    # 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"
    backup_game_config="$restore_source/config.ini"
    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

    # Verify we are working with legitimate instance and backup.
    if [[ ! -d $instance_directory ]]; then
        error "No such instance: $instance"
        exit "$ERROR_ARGUMENTS"
    fi

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

    if [[ ! -f $backup_instance_config ]]; then
        error "Invalid backup, missing instance configuration file: $backup_instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $backup_game_config ]]; then
        error "Invalid backup, missing game configuration file: $backup_game_config"
        exit "$ERROR_GENERAL"
    fi

    (
        # Obtain lock - Factorio uses the same mechanism, so we should
        # be able to detect the game is running in this way.
        flock --exclusive --nonblock 200
        if [[ $? != 0 ]]; then
            error "Could not lock instance directory via lock file $lock_file. Is Factorio instance still running?"
            exit "$ERROR_GENERAL"
        fi

        function remove_lock() {
            rm "$lock_file"
        }
        trap remove_lock EXIT

        # 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

    # 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"
    backup_game_config="$removal_target/config.ini"
    lock_file="$instance_directory/.lock"

    # Verify we are working with legitimate instance and backup.
    if [[ ! -d $instance_directory ]]; then
        error "No such instance: $instance"
        exit "$ERROR_ARGUMENTS"
    fi

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

    if [[ ! -f $backup_instance_config ]]; then
        error "Invalid backup, missing instance configuration file: $backup_instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $backup_game_config ]]; then
        error "Invalid backup, missing game configuration file: $backup_game_config"
        exit "$ERROR_GENERAL"
    fi

    # Present user with warning.
    echo
    if [[ -f "$removal_target/.description" ]]; then
        backup_description=$(<"$removal_target/.description")
        backup_info="$backup_name ($backup_description)"
    else
        backup_info="$backup_name"
    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
    # Read positional arguments.
    instance="${1-}"
    shift

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

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

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

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

    # Verify we are working with legitimate instance.
    if [[ ! -f $instance_config ]]; then
        error "Missing instance configuration file: $instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $game_config ]]; then
        error "Missing game configuration file: $game_config"
        exit "$ERROR_GENERAL"
    fi

    # Load instance configuration.
    source "$instance_config"

    # Display list of available Factorio versions.
    echo
    echo "The following versions of Factorio are locally available:"
    echo

    for candidate in "$game_installations_directory"/*; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            candidate_version=$(basename "$candidate")
            if [[ $candidate_version == $game_version ]]; then
                echo "  - $candidate_version $(colorecho -n green "[current]")"
            else
                echo "  - $candidate_version"
            fi

        fi
    done
    echo

    # Display current version.
    echo "Current version used for instance $(colorecho -n green "$instance") is $(colorecho -n green "$game_version")."
    echo
    read -p "Please specify what version you would like to use (enter to keep current): " game_version_selected

    if [[ -z $game_version_selected ]]; then
        game_version_selected="$game_version"
    fi

    # Validate user input.
    if [[ ! -f "$game_installations_directory/$game_version_selected/bin/x64/factorio" ]]; then
        error "Requested version not locally available: $game_version_selected"
        exit "$ERROR_ARGUMENTS"
    fi

    # 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 user has set directory with game installations - test
    # both symlink and target destination.
    if [[ ! -L $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    # 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"

    # Verify we are working with legitimate instance.
    if [[ ! -f $instance_config ]]; then
        error "Missing instance configuration file: $instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $game_config ]]; then
        error "Missing game configuration file: $game_config"
        exit "$ERROR_GENERAL"
    fi

    # Load instance configuration.
    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"

    # Plain listing.
    elif ! hash jqs 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"
            fi

        done

    # Fancy listing with detection for enabled mods using jq.
    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.
        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"
            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

    # 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"

    # Verify we are working with legitimate instance and backup.
    if [[ ! -d $instance_directory ]]; then
        error "No such instance: $instance"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ ! -f $instance_config ]]; then
        error "Missing instance configuration file: $instance_config"
        exit "$ERROR_GENERAL"
    fi

    (
        # Obtain lock - Factorio uses the same mechanism, so we should
        # be able to detect the game is running in this way.
        flock --exclusive --nonblock 200
        if [[ $? != 0 ]]; then
            error "Could not lock instance directory via lock file $lock_file. Is Factorio instance still running?"
            exit "$ERROR_GENERAL"
        fi

        # Removing lock file will most likely fail if we manage to
        # remove the instance.
        function remove_lock() {
            rm -f "$lock_file"
        }
        trap remove_lock EXIT

        # 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.
        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 user has set directory with game installations - test
    # both symlink and target destination.
    if [[ ! -L $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    # 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_game_config="$source_instance_directory/config.ini"
    source_lock_file="$source_instance_directory/.lock"

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

    # Verify we are working with legitimate source and destination.
    if [[ ! -d $source_instance_directory ]]; then
        error "No such instance: $source_instance"
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ ! -f $source_instance_config ]]; then
        error "Missing instance configuration file: $source_instance_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ ! -f $source_game_config ]]; then
        error "Missing game configuration file: $source_game_config"
        exit "$ERROR_GENERAL"
    fi

    if [[ -e $destination_instance_directory ]]; then
        error "Instance already exists."
        exit "$ERROR_ARGUMENTS"
    fi

    (
        # Obtain lock - Factorio uses the same mechanism, so we should
        # be able to detect the game is running in this way.
        flock --exclusive --nonblock 200
        if [[ $? != 0 ]]; then
            error "Could not lock instance directory via lock file $source_lock_file. Is Factorio instance still running?"
            exit "$ERROR_GENERAL"
        fi

        function remove_lock() {
            rm "$source_lock_file"
        }

        trap remove_lock EXIT

        # Load source instance configuration.
        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
        echo "The following versions of Factorio are locally available:"
        echo

        for candidate in "$game_installations_directory"/*; do
            if [[ -f $candidate/bin/x64/factorio ]]; then
                candidate_version=$(basename "$candidate")
                if [[ $candidate_version == $game_version ]]; then
                    echo "  - $candidate_version $(colorecho -n green "[current]")"
                else
                    echo "  - $candidate_version"
                fi
            fi
        done
        echo

        # Display current version.
        echo "Current version used for instance $(colorecho -n green "$source_instance") is $(colorecho -n green "$game_version")."
        echo
        read -p "Please specify what version you would like to use for new instance (press enter to keep the current version): " game_version_selected

        if [[ -z $game_version_selected ]]; then
            game_version_selected="$game_version"
        fi

        # Validate user input.
        if [[ ! -f "$game_installations_directory/$game_version_selected/bin/x64/factorio" ]]; then
            error "Requested version not locally available: $game_version_selected"
            exit "$ERROR_ARGUMENTS"
        fi

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

        until [[ $copy_backups == "y" || $copy_backups == "n" ]]; do
            echo
            read -n1 -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 user has set directory with game installations - test
    # both symlink and target destination.
    if [[ ! -L $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    # 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_config="$source_directory/config/config.ini"
    source_lock_file="$source_directory/.lock"

    # List of entries to import from the source directory.
    declare -A import_entries=()
    import_entries["achievements-modded.dat"]="contains achivement information for modded plays"
    import_entries["achievements.dat"]="contains achievement information for vanilla plays"
    import_entries["archive"]="contains desync reports"
    import_entries["blueprint-storage.dat"]="contains global (non-savegame specific) blueprints"
    import_entries["config/config.ini"]="contains game configuration, including things like shortcuts etc."
    import_entries["crop-cache.dat"]="purpose is not known"
    import_entries["factorio-current.log"]="contains logs from the currently running game"
    import_entries["factorio-previous.log"]="contains logs from the previously running game"
    import_entries["mods"]="contains mods and mod settings"
    import_entries["player-data.json"]="contains global information about the player, such as username, login token, chat history, etc."
    import_entries["saves"]="contains savegames"

    # Ensure we are working with valid directories.
    if [[ -e $instance_directory ]]; then
        error "Instance already exists."
        exit "$ERROR_ARGUMENTS"
    fi

    if [[ ! -f $source_directory/bin/x64/factorio ]]; then
        error "Could not locate Factorio binary in source directory under: $source_directory/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

    # Display list of available Factorio versions and let user pick one.
    echo "Factorio version must  be selected manually for imported instances."
    echo
    echo "The following versions of Factorio are locally available:"
    echo

    for candidate in "$game_installations_directory"/*; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            echo "  - $(basename "$candidate")"
        fi
    done

    echo

    echo -n "Please specify what version you would like to use: "
    read game_version_selected

    # Validate user input.
    if [[ ! -f "$game_installations_directory/$game_version_selected/bin/x64/factorio" ]]; then
        error "Requested version not locally available: $game_version_selected"
        exit "$ERROR_ARGUMENTS"
    fi

    (

        # Obtain lock - Factorio uses the same mechanism, so we should
        # be able to detect the game is running in this way.
        flock --exclusive --nonblock 200
        if [[ $? != 0 ]]; then
            error "Could not lock instance directory via lock file $source_lock_file. Is Factorio instance still running?"
            exit "$ERROR_GENERAL"
        fi

        function remove_lock() {
            rm "$source_lock_file"
        }

        trap remove_lock EXIT

        # Create instance directory.
        mkdir "$instance_directory"

        # Sort the associative array keys.
        IFS=$'\n' import_entries_keys=($(sort <<<"${!import_entries[*]}"))
        unset IFS

        # 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 -n1
        fi

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

    ) 200>"$source_lock_file"


#===============#
# create-server #
#===============#
elif [[ $command == create-server ]]; then
    instance="${1-}"

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

    if [[ ! -d $game_installations_directory ]]; then
        error "Game installations directory has not been properly set. Please run the set-game-dir command first."
        exit "$ERROR_CONFIGURATION"
    fi

    # 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

    if [[ -e $instance_directory ]]; then
        error "Instance already exists."
        exit "$ERROR_ARGUMENTS"
    fi

    # Display list of available Factorio versions and let user pick one.
    echo "The following versions of Factorio are locally available:"
    echo

    for candidate in "$game_installations_directory"/*; do
        if [[ -f $candidate/bin/x64/factorio ]]; then
            echo "  - $(basename "$candidate")"
        fi
    done

    echo

    echo -n "Please specify what version you would like to use: "
    read game_version_selected

    # Validate user input.
    if [[ ! -f "$game_installations_directory/$game_version_selected/bin/x64/factorio" ]]; then
        error "Requested version not locally available: $game_version_selected"
        exit "$ERROR_ARGUMENTS"
    fi

    # 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 "$saves_directory/default.zip"; then
        error "Failed to generate default savegame/map under: $saves_directory/default.zip"
        exit "$ERROR_GENERAL"
    fi

    success "Created new server instance $(colorecho -n green "$instance")"
else
    error "Invalid command: $command"

    exit "$ERROR_ARGUMENTS"
fi