forked from Bisa/factorio-init
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factorio
975 lines (869 loc) · 30.2 KB
/
factorio
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
#!/bin/bash
### BEGIN INIT INFO
# Provides: Factorio
# Required-Start: $local_fs $network $remote_fs
# Required-Stop: $local_fs $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop Factorio server
# Description: A init script for Factorio, try the help command
### END INIT INFO
debug(){
if [ ${DEBUG} -gt 0 ]; then
echo "DEBUG: $@" >&2
fi
}
# Make sure the script is CD'ed to a PWD that is valid and not symlinked. (ie. where the script actually is at)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "${SOURCE}" ]; do # resolve ${SOURCE} until the file is no longer a symlink
DIR="$( cd -P "$( dirname "${SOURCE}" )" && pwd )"
SOURCE="$(readlink "${SOURCE}")"
[[ ${SOURCE} != /* ]] && SOURCE="${DIR}/${SOURCE}" # if ${SOURCE} was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
cd "${SCRIPT_DIR}"
# Save the script arguments to be called later.
SCRIPT_ARGS="$@";
# Load config file
if [ -L $0 ]; then
source `readlink -e $0 | sed "s:[^/]*$:config:"`
else
source `echo $0 | sed "s:[^/]*$:config:"`
fi
if [ -z "${SERVICE_NAME}" ]; then
echo "Couldn't load config file, please edit config.example and rename it to config"
exit 1
fi
# Check/load defaults for backwards compatible config options
if [ -z "${PACKAGE_DIR_NAME}" ]; then
PACKAGE_DIR_NAME=factorio
fi
if [ -z "${USERGROUP}" ]; then
USERGROUP=${USERNAME}
fi
if [ -z "${HEADLESS}" ]; then
# This is a server init script, assume headless default
HEADLESS=1
fi
if [ -z "${LATEST_HEADLESS_URL}" ]; then
if [ ${UPDATE_EXPERIMENTAL} -gt 0 ]; then
LATEST_HEADLESS_URL="https://www.factorio.com/get-download/latest/headless/linux64"
else
LATEST_HEADLESS_URL="https://www.factorio.com/get-download/stable/headless/linux64"
fi
fi
if [ -z "${NONCMDPATTERN}" ]; then
NONCMDPATTERN='(^\s*(\s*[0-9]+\.[0-9]+|\)|\())|(Players:$)'
fi
if [ -z ${BINARY} ]; then
# Factorio headless only comes in x64 flavour - if you run anything else, override it in the config
BINARY="${FACTORIO_PATH}/bin/x64/factorio"
BINARYB="${FACTORIO_PATH}/bin/x64/factorio"
fi
if [ -z ${ALT_GLIBC} ]; then
ALT_GLIBC=0
fi
if [ -z ${WAIT_PINGPONG} ]; then
WAIT_PINGPONG=0
fi
if [ ${ALT_GLIBC} -gt 0 ]; then
# If ALT_GLIBC is non 0 then activate alternative glibc root here
BINARY="${ALT_GLIBC_DIR}/lib/ld-${ALT_GLIBC_VER}.so --library-path ${ALT_GLIBC_DIR}/lib ${FACTORIO_PATH}/bin/x64/factorio"
BINARYB="${FACTORIO_PATH}/bin/x64/factorio"
EXE_ARGS_GLIBC="--executable-path ${BINARYB}"
fi
case "$1" in
install|help|listcommands|version|init-server|"")
;;
*)
if ! [ -e ${BINARYB} ]; then
echo "Could not find factorio binary! ${BINARYB}"
echo "(if you store your binary some place else, override BINARY='/your/path' in the config)"
exit 1
fi
if [ -z ${FCONF} ]; then
FCONF="${FACTORIO_PATH}/config/config.ini"
fi
if ! [ -e "${SERVER_SETTINGS}" ]; then
echo "Could not find factorio server settings file: ${SERVER_SETTINGS}"
echo "Update your config and point SERVER_SETTINGS to a modified version of data/server-settings.example.json"
exit 1
fi
if ! [ -e ${FCONF} ]; then
echo "Could not find factorio config file: ${FCONF}"
echo "If this is the first time you run this script you need to generate the config.ini by starting the server manually."
echo "(also make sure you have a save to run or the server will not start)"
echo
echo "Create save: sudo -u ${USERNAME} ${BINARY} --create ${FACTORIO_PATH}/saves/my_savegame ${EXE_ARGS_GLIBC}"
echo "Start server: sudo -u ${USERNAME} ${BINARY} --start-server-load-latest ${EXE_ARGS_GLIBC}"
echo
echo "(If you rather store the config.ini in another location, set FCONF='/your/path' in this scripts config file)"
exit 1
fi
if [ -z "${WRITE_DIR}" ]; then
# figure out the write-data path (where factorio looks for saves and mods)
# Note - this is a hefty little operation, possible cause of head ache down the road
# as it relies on the factorio write dir to live ../../ up from the binary if __PATH__executable__
# is used in the config file.. for now, that's the default so cross your fingers it will not change ;)
debug "Determining WRITE_DIR based on ${FCONF}, IF you edited write-data from the default, this probably fails"
WRITE_DIR=$(dirname "$(echo `grep "^write-data=" "$FCONF"` |cut -d'=' -f2 |sed -e 's#__PATH__executable__#'$(dirname "$BINARYB")/..'#g')")
fi
debug "write path: $WRITE_DIR"
PIDFILE="${WRITE_DIR}/server.pid"
if [ -z "${FIFO}" ];then
FIFO="${WRITE_DIR}/server.fifo"
fi
if [ -z "${CMDOUT}" ];then
CMDOUT="${WRITE_DIR}/server.out"
fi
if [ -z "${SAVELOG}" ]; then
SAVELOG=0
fi
# Finally, set up the invocation
INVOCATION="${BINARY} --config ${FCONF} --port ${PORT} --start-server-load-latest --server-settings ${SERVER_SETTINGS} ${EXTRA_BINARGS}"
;;
esac
usage(){
echo "Usage: $0 COMMAND"
echo
echo "Available commands:"
echo -e " start \t\t\t\t Starts the server"
echo -e " stop \t\t\t\t Stops the server"
echo -e " restart \t\t\t\t Restarts the server"
echo -e " status \t\t\t\t Displays server status"
echo -e " players-online \t\t\t Shows online players"
echo -e " players \t\t\t\t Shows all players"
echo -e " cmd [command/message] \t\t Open interactive commandline or send a single command to the server"
echo -e " chatlog [--tail|-t] \t\t\t Print the current chatlog, optionally tail the log to follow in real time"
echo -e " new-game name [map-gen-settings] [map-settings] \t Stops the server and creates a new game with the specified name using the specified map gen settings and map settings json files"
echo -e " save-game name \t\t\t Stops the server and saves game to specified save"
echo -e " load-save name \t\t\t Stops the server and loads the specified save"
echo -e " install [tarball] \t\t\t Installs the server with optional specified tarball (omit to download and use the latest headless server from Wube)"
echo -e " update [--dry-run] \t\t\t Updates the server"
echo -e " invocation \t\t\t\t Outputs the invocation for debugging purpose"
echo -e " listcommands \t\t\t List all init-commands"
echo -e " listsaves \t\t\t\t List all saves"
echo -e " version \t\t\t\t Prints the binary version"
echo -e " help \t\t\t\t Shows this help message"
}
ME=`whoami`
verify_user() {
SCRIPT_ARGS="$@";
factorio_init_context_string="^system_u:system_r:factorio_init_t:.*";
unconfined_context_string="^[^:\s]+:[^:\s]+:unconfined_t:.*";
# Desired ideal: unconfined_u:unconfined_r:factorio_init_t:s0-s0:c0.c1023 factorio
if [ "${ME}" == "${USERNAME}" ] && [ "${SELINUX}" -ne 1 ]; then
# If SELINUX is not wanted and user is correct, just return. It is fine.
umask 0022; # Set this in case things are too restrictive for Factorio.
return 0;
elif [ "${ME}" != "${USERNAME}" ] && [ "$(id -u)" == "0" ]; then
# If the user is incorrect, but it is root, change it for the user to the user. (This will happen with right or wrong context).
exec su "${USERNAME}" -s /bin/bash -c "${SCRIPT_DIR}/factorio ${SCRIPT_ARGS}";
exit $?;
elif [ "${ME}" == "${USERNAME}" ] && [ "${SELINUX}" -eq 1 ]; then
# If the user is correct, but SELINUX is needed, then check context.
if (! [[ "$(id -Z)" =~ ${factorio_init_context_string} ]]) && [[ "$(id -Z)" =~ ${unconfined_context_string} ]]; then
# If the user is correct, but context is wrong and it is unconfined, change the context for the user.
runcon -t factorio_init_t -r system_r -u system_u -- ${SCRIPT_DIR}/factorio ${SCRIPT_ARGS};
exit $?;
elif [[ "$(id -Z)" =~ ${factorio_init_context_string} ]]; then
# If the context is correct, just return.
umask 0022; # Set this in case things are too restrictive for Factorio.
return 0;
fi
fi
# All other cases, things are wrong.
echo "You must run this script either as the ${USERNAME} user, or as root!";
if [ "${SELINUX}" -eq 1 ]; then
echo "You must run this script within the proper context: system_u:system_r:factorio_init_t.";
echo "HINT: su \"${USERNAME}\" -s /bin/bash -c 'runcon -u system_u -r system_r -t factorio_init_t -- ${SCRIPT_DIR}/factorio ${SCRIPT_ARGS}'";
echo "HINT2: sudo -u \"${USERNAME}\" -- runcon -u system_u -r system_r -t factorio_init_t -- ${SCRIPT_DIR}/factorio ${SCRIPT_ARGS}";
fi
exit 1;
}
run_context() {
if [ $ME == $USERNAME ]; then
# Make sure we are running as factorio user.
# Then if running with SELINUX, change context.
if [ "${SELINUX}" -eq 1 ]; then
factorio_context_string="^system_u:system_r:factorio_t:.*";
if (! [[ "$(id -Z)" =~ ${factorio_context_string} ]]); then
runcon -u system_u -r system_r -t factorio_t -- /bin/bash -c "${1}"
else
/bin/bash -c "${1}"
fi
else
/bin/bash -c "${1}"
fi
else
# To prevent odd permission behaviour, either
# run this script as the configured user or as root
# (please do not run as root btw!)
echo "Run this script as the $USERNAME user!"
exit 1
fi
}
is_running() {
if [ -e ${PIDFILE} ]; then
if kill -0 $(cat ${PIDFILE}) 2> /dev/null; then
debug "${SERVICE_NAME} is running with pid $(cat ${PIDFILE})"
return 0
else
debug "Found ${PIDFILE}, but the server is not running. It's possible that your server has crashed"
debug "Check the log for details"
rm ${PIDFILE} 2> /dev/null
return 2
fi
fi
return 1
}
wait_pingpong() {
until ping -c1 pingpong1.factorio.com &>/dev/null; do :; done
until ping -c1 pingpong2.factorio.com &>/dev/null; do :; done
}
start_service() {
if [ -e ${PIDFILE} ]; then
ps -q $(cat ${PIDFILE}) > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "${SERVICE_NAME} is already running!"
return 1
fi
debug "Found rogue pid file, server might have crashed"
rm ${PIDFILE} 2> /dev/null
fi
if ! check_permissions; then
echo "Error! Incorrect permissions, unable to write to ${WRITE_DIR}"
return 1
fi
if [ "${SAVELOG}" == "0" ]; then
debug "Erasing log ${CMDOUT}"
echo "" > ${CMDOUT}
fi
if [ ${WAIT_PINGPONG} -gt 0 ]; then
wait_pingpong
fi
run_context "tail -f ${FIFO} |${INVOCATION} ${EXE_ARGS_GLIBC}>> ${CMDOUT} 2>&1 & echo \$! > ${PIDFILE}"
ps -q $(cat ${PIDFILE}) > /dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "Unable to start ${SERVICE_NAME}"
return 1
else
echo "Started ${SERVICE_NAME}, please see log for details"
fi
}
stop_service() {
if [ -e ${PIDFILE} ]; then
echo -n "Stopping ${SERVICE_NAME}: "
if kill -TERM $(cat ${PIDFILE} 2> /dev/null) 2> /dev/null; then
sec=1
while [ "$sec" -le 15 ]; do
if [ -e ${PIDFILE} ]; then
if kill -0 $(cat ${PIDFILE} 2> /dev/null) 2> /dev/null; then
echo -n ". "
sleep 1
else
break
fi
else
break
fi
sec=$(($sec+1))
done
fi
if kill -0 $(cat ${PIDFILE} 2> /dev/null) 2> /dev/null; then
echo "Unable to shut down nicely, killing the process!"
kill -KILL $(cat ${PIDFILE} 2> /dev/null) 2> /dev/null
else
echo "complete!"
fi
# Start the reader (in case tail stopped already)
cat ${FIFO} &
# Open pipe for writing.
exec 3> ${FIFO}
# Write a newline to the pipe, this triggers a SIGPIPE and causes tail to exit
echo "" >&3
# Close pipe.
exec 3>&-
rm ${PIDFILE} 2> /dev/null
return 0 # we've either shut down gracefully or killed the process
else
echo "${SERVICE_NAME} is not running (${PIDFILE} does not exist)"
return 1
fi
}
send_cmd(){
NEED_OUTPUT=0
if [ "xx$1" == "xx-o" ]; then
NEED_OUTPUT=1
shift
fi
if is_running; then
if [ -p ${FIFO} ]; then
# Generate two unique log markers
TIMESTAMP=$(date +"%s")
START="FACTORIO_INIT_CMD_${TIMESTAMP}_START"
END="FACTORIO_INIT_CMD_${TIMESTAMP}_END"
# Whisper that unknown player to place start marker in log
echo "/w $START" > ${FIFO}
# Run the actual command
echo $@ > ${FIFO}
# Whisper that unknown player again to place end marker in log after the command terminated
echo "/w $END" > ${FIFO}
if [ ${NEED_OUTPUT} -eq 1 ]; then
# search for the start marker in the log file, then follow and print the log output in real time until the end marker is found
sleep 1
awk "/Player $START doesn't exist./{flag=1;next}/Player $END doesn't exist./{exit}flag" < ${CMDOUT}
fi
else
echo "${FIFO} is not a pipe!"
return 1
fi
else
echo "Unable to send cmd to a stopped server!"
return 1
fi
}
cmd_players(){
players=$(send_cmd -o "/p")
if [ -z "${players}" ]; then
echo "No players found!"
return 1
fi
if [ "$1" == "online" ]; then
echo "${players}" |egrep '.+ \(online\)$' |sed -e 's/ (online)//g'
else
echo "${players}"
fi
}
check_permissions(){
if [ ! -e "${BINARYB}" ]; then
echo "Can't find ${BINARYB}. Please check your config!"
exit 1
fi
if ! run_context "test -w ${WRITE_DIR}" ; then
echo "Check Permissions. Cannot write to ${WRITE_DIR}"
exit 1
fi
if ! run_context "touch ${PIDFILE}" ; then
echo "Check Permissions. Cannot touch pidfile ${PIDFILE}"
exit 1
fi
if ! [ -p ${FIFO} ]; then
if ! run_context "mkfifo ${FIFO}"; then
echo "Failed to create pipe for stdin, if applicable, remove ${FIFO} and try again"
exit 1
fi
fi
if ! run_context "touch ${CMDOUT}" ; then
echo "Check Permissions. Cannot touch cmd output file ${CMDOUT}"
exit 1
fi
}
test_deps(){
return 0 # TODO: Implement ldd check on $BINARY
}
set_perms(){
echo "Applying file ownership ..."
result=$(chown -R ${USERNAME}:${USERGROUP} ${FACTORIO_PATH})
if [[ ${result} -ne 0 ]]; then
echo "Failed to apply ownership ${USERNAME}:${USERGROUP} for ${FACTORIO_PATH}"
exit 1
fi
echo "Applying directory permissions (factorio) ..."
result=$(find ${FACTORIO_PATH} -type d -exec chmod 755 {} \;)
if [[ ${result} -ne 0 ]]; then
echo "Failed to apply directory permission for ${FACTORIO_PATH}"
exit 1
fi
echo "Applying file permissions (factorio) ..."
result=$(find ${FACTORIO_PATH} -type f -file chmod 644 {} \;)
if [[ ${result} -ne 0 ]]; then
echo "Failed to apply file permission for ${FACTORIO_PATH}"
exit 1
fi
echo "Applying execute permissions (factorio/bin/x64/factorio) ..."
result=$(chmod 755 ${FACTORIO_PATH}/bin/x64/factorio);
if [[ ${result} -ne 0 ]]; then
echo "Failed to apply permission for ${FACTORIO_PATH}/bin/x64/factorio"
exit 1
fi
if [[ ${SELINUX} -eq 1 ]]; then
echo "Applying SELINUX security contexts ..."
restorecon -R -v ${FACTORIO_PATH};
result=$?;
if [[ ${result} -ne 0 ]]; then
echo "Failed to apply SELINUX security contexts for ${FACTORIO_PATH}"
exit 1
fi
fi
}
install(){
if [ "$(id -u)" != "0" ]; then
echo "You must execute this as root!"
exit 1;
fi
if [[ "${SELINUX}" -eq 1 ]] || [[ "$(getenforce)" =~ (E|e)nforcing ]]; then
# Make sure user is running unconfined.
factorio_init_context_string="^unconfined_u:unconfined_r:unconfined_t:.*";
if ( ! [[ "$(id -Z)" =~ ${factorio_init_context_string} ]] ) || [ "$(id -u)" != "0" ]; then
echo "You must run this as root with the proper unconfined_u:unconfined_r:unconfined_t context!";
echo "HINT: sudo su -- runcon -u unconfined_u -r unconfined_r -t unconfined_t -- /opt/factorio-init/factorio install";
exit 1;
fi
# Make sure the directory has proper context.
factorio_init_dir_string="^system_u:object_r:factorio_init_t:.*";
if ! [[ "$(stat -c %C ${SCRIPT_DIR})" =~ ${factorio_init_dir_string} ]]; then
echo "You must properly set the context of the factorio-init directory.";
echo "HINT: chcon -u system_u -r object_r -t factorio_init_t ${SCRIPT_DIR}";
echo "HINT2: restorecon -F -R -v ${SCRIPT_DIR}";
exit 1;
fi
# Make sure this file has proper context.
factorio_init_exec_string="^system_u:object_r:factorio_init_exec_t:.*";
if ! [[ "$(stat -c %C ${SCRIPT_DIR}/factorio)" =~ ${factorio_init_exec_string} ]]; then
echo "You must properly set the context of the factorio-init directory.";
echo "HINT: chcon -u system_u -r object_r -t factorio_init_exec_t ${SCRIPT_DIR}/factorio";
echo "HINT2: restorecon -F -R -v ${SCRIPT_DIR}";
exit 1;
fi
# Make sure conf file has proper context.
factorio_init_conf_string="^system_u:object_r:factorio_init_conf_t:.*";
if ! [[ "$(stat -c %C ${SCRIPT_DIR}/config)" =~ ${factorio_init_conf_string} ]]; then
echo "You must properly set the context of the factorio-init directory.";
echo "HINT: chcon -u system_u -r object_r -t factorio_init_exec_t ${SCRIPT_DIR}/config";
echo "HINT2: restorecon -F -R -v ${SCRIPT_DIR}";
exit 1;
fi
fi
# Make sure this directory is executable.
if [[ "$(stat -c %a ${SCRIPT_DIR})" != "755" ]]; then
echo "The factorio-init directory is not of the correct permission."
echo "HINT: chmod 755 ${SCRIPT_DIR}"
exit 1;
fi
# Make sure this file is executable and not '/bin/bash -c'ed into.
if [[ "$(stat -c %a ${SCRIPT_DIR}/factorio)" != "755" ]]; then
echo "The factorio-init executable is not of the correct permission."
echo "HINT: chmod 755 ${SCRIPT_DIR}/factorio"
exit 1;
fi
# Make sure the config is secure.
if [[ "$(stat -c %a ${SCRIPT_DIR}/config)" != "640" ]]; then
echo "The factorio-init config is not of the correct permission."
echo "HINT: chmod 640 ${SCRIPT_DIR}/config"
exit 1;
elif ! ( [[ "$(stat -c %G ${SCRIPT_DIR}/config)" == "${USERGROUP}" ]] && [[ "$(stat -c %U ${SCRIPT_DIR}/config)" == "root" ]] ); then
echo "The facatorio-init config is not the proper owner/group."
echo "HINT: chown ${USERNAME}:${USERGROUP} ${SCRIPT_DIR}/config"
exit 1;
fi
# Factorio comes packaged in a directory named "factorio"
# Unless overriden in the config we will presume this is also the
# name used in FACTORIO_PATH
umask 0022;
expected_path="`dirname ${FACTORIO_PATH}`/${PACKAGE_DIR_NAME}"
if ! [ "${FACTORIO_PATH}" == "${expected_path}" ]; then
echo "Aborting install! FACTORIO_PATH does not match expected path: ${expected_path}"
echo "See config option PACKAGE_DIR_NAME for more details"
exit 1
fi
# Prevent accidential overwrites
if [ -e "${expected_path}" ]; then
echo "Aborting install, ${FACTORIO_PATH} already exists"
exit 1
fi
tarball=$1
if ! [ -z "$tarball" ]; then
if ! [ -f "${tarball}" ]; then
echo "Install package does not exist! ${tarball}"
exit 1
fi
else
downloadlatest=1
fi
target="`dirname ${FACTORIO_PATH}`"
if ! test -w "${target}"; then
echo "Failed to write, aborting install!"
echo "Install needs to be run as a user with write permissions to ${target}"
exit 1
fi
if [ $downloadlatest ]; then
LATEST_HEADLESS_URL_REDIRECT_FILENAME=$(curl ${LATEST_HEADLESS_URL} -s -L -I -o /dev/null -w '%{url_effective}')
if [[ $LATEST_HEADLESS_URL_REDIRECT_FILENAME == *"tar.xz"* ]]; then
TAR_OPTIONS="-xJv"
else
TAR_OPTIONS="-xzv"
fi
if ! wget ${LATEST_HEADLESS_URL} -O - | tar ${TAR_OPTIONS} --directory "${target}"; then
echo "Install failed!"
exit 1
fi
else
echo "Installing ${tarball} ..."
if [[ $tarball == *"tar.xz"* ]]; then
TAR_OPTIONS="-xJvf"
else
TAR_OPTIONS="-xzvf"
fi
if ! tar ${TAR_OPTIONS} "${tarball}" --directory "${target}"; then
echo "Install failed!"
exit 1
fi
fi
set_perms; # Set file permissions
# Generate default config.ini by creating a save. And restart script to ensure that it is in the proper context.
${SCRIPT_DIR}/factorio init-server
if [ $? -eq 0 ]; then
echo "Installation complete, edit data/server-settings.json and start your server"
exit 0
else
echo "Failed to create save, review the output above to recover"
exit 1
fi
}
init-server(){
if [ ! -f "${SERVER_SETTINGS}" ]; then
run_context "${BINARY} --create ${FACTORIO_PATH}/saves/server-save ${EXE_ARGS_GLIBC}";
resutling_status=$?;
exit ${resutling_status};
else
echo "You cannot re-initialize a server that is ALREADY initialized at ${SERVER_SETTINGS}!";
exit 1;
fi
}
get_bin_version(){
echo `run_context "$BINARY --version |egrep '^Version: [0-9\.]+' |egrep -o '[0-9\.]+' |head -n 1"`
}
get_bin_arch(){
echo `run_context "$BINARY --version |egrep '^Binary version: ' |egrep -o '[0-9]{2}'"`
}
update(){
if ! [ -e "${UPDATE_SCRIPT}" ]; then
echo "Failed to find update script, blatantly refusing to continue!"
echo "Try cloning into git@github.com:narc0tiq/factorio-updater.git and set the UPDATE_SCRIPT config before you try again."
exit 1;
fi
# Assume the user wants a dry run? (our only argument to this function)
if ! [ -z "$1" ]; then
echo "Running updater in --dry-run mode, no patches will be applied"
dryrun=1
else
dryrun=0
fi
if [ ${HEADLESS} -gt 0 ]; then
package="core-linux_headless`get_bin_arch`"
else
package="core-linux`get_bin_arch`"
fi
version=`get_bin_version`
if [ -z "${UPDATE_TMPDIR}" ]; then
UPDATE_TMPDIR=/tmp
fi
# Create tmpdir and ensure automatic cleanup
tmpdir=`run_context "mktemp -d -p ${UPDATE_TMPDIR} factorio-update.XXXXXXXXXX"`
if [ $? -ne 0 ]; then
echo "Aborting update! Unable to create tmpdir: ${tmpdir}"
exit 1
fi
trap "rm -rf ${tmpdir}" EXIT
invocation="python ${UPDATE_SCRIPT} --for-version ${version} --package ${package} --output-path ${tmpdir}"
if [ ${UPDATE_EXPERIMENTAL} -gt 0 ]; then
invocation="${invocation} --experimental"
fi
if [ ${HEADLESS} -eq 0 ]; then
#GoodGuy Wube Software allows you to download the headless for free - yay! but you still have to
#buy the game if you want to download the sound/gfx client
invocation="${invocation} --user ${UPDATE_USERNAME} --token ${UPDATE_TOKEN}"
fi
echo "Checking for updates..."
result=`run_context "${invocation} --dry-run"`
exitcode=$?
if [ ${exitcode} -eq 1 -o ${exitcode} -gt 2 ]; then
debug "Invocation: ${invocation}"
debug "${result}"
echo "Update check failed!"
exit 1
else
newversion=`echo ${result} |egrep '^Dry run: ' |egrep -o '[0-9\.]+' |tail -n 1`
fi
if [ -z "${newversion}" ]; then
echo "No new updates for ${package} ${version}"
exit 0
else
echo "New version ${package} ${newversion}"
fi
# Go or no Go?
if [ ${dryrun} -gt 0 ]; then
echo "Dry run, not taking further actions!"
# allow scripts to read return code 0 for no updates and 2 if there are updates to apply
if ! [ -z "${newversion}" ]; then
exit 2
fi
exit 0
fi
# Time to download the updates
if ! run_context "${invocation}"; then
echo "Aborting update!"
exit 1
fi
# Stop the server if it is running.
is_running
was_running=$?
if [ ${was_running} -eq 0 ]; then
send_cmd "Updating to new Factorio version, be right back"
stop_service
fi
for patch in $(find ${tmpdir} -type f -name "*.zip" | sort -V); do
echo "Applying ${patch} ..."
result=`run_context "$BINARY --apply-update ${patch} ${EXE_ARGS_GLIBC}"`
exitcode=$?
if [ $exitcode -gt 0 ]; then
echo "${result}"
echo
echo "Error! Failed to apply update"
echo "You can try to apply it manually with:"
echo "su ${USERNAME} -c \"${BINARY} --apply-update ${patch} ${EXE_ARGS_GLIBC}\""
exit 1
fi
done
# Restarts the server if it was running
if [ ${was_running} -eq 0 ]; then
start_service
fi
echo "Successfully updated factorio"
}
case "$1" in
start)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
# Starts the server
if is_running; then
echo "Server already running."
exit 0
else
if ! start_service; then
echo "Could not start $SERVICE_NAME"
exit 1
fi
fi
;;
stop)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
# Stops the server
if is_running; then
send_cmd "Server is being shut down on request"
if ! stop_service; then
echo "Could not stop $SERVICE_NAME"
exit 1
fi
else
echo "No running server."
exit 0
fi
;;
restart)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
# Restarts the server
if is_running; then
send_cmd "Server is being restarted on request, be right back!"
if stop_service; then
if ! start_service; then
echo "Could not start $SERVICE_NAME after restart!"
exit 1
fi
else
echo "Failed to stop $SERVICE_NAME, aborting restart!"
exit 1
fi
else
echo "No running server to restart, starting it..."
if ! start_service; then
echo "Could not start $SERVICE_NAME"
exit 1
fi
fi
;;
init-server)
verify_user ${SCRIPT_ARGS}; # Check to make sure we are running the correct context.
init-server;
exit 2;
;;
status)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
# Shows server status
if is_running; then
echo "$SERVICE_NAME is running."
else
echo "$SERVICE_NAME is not running."
exit 1
fi
;;
cmd)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
if [ -z "$2" ]; then
trap 'clear' SIGTERM EXIT
clear
echo "Type any command or send chat messages"
echo "This interactive commandline adds additional commands:"
echo ""
echo -e "\texit\t\texit the commandline"
echo -e "\tclear\t\tclear the commandline screen"
echo ""
while true; do
read -e -p "server@${SERVICE_NAME}> " cmd
[ "${cmd}" == "exit" ] && exit 0
[ "${cmd}" == "clear" ] && clear && continue
echo ${cmd} > ${FIFO}
sleep 1
done
else
send_cmd "${@:2}"
fi
;;
chatlog)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
case $2 in
--tail|-t)
tail -F -n +0 ${CMDOUT} |egrep -v "${NONCMDPATTERN}"
;;
*)
cat ${CMDOUT} |egrep -v "${NONCMDPATTERN}"
;;
esac
;;
players)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
cmd_players
;;
players-online|online)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
cmd_players online
;;
new-game)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
if [ -z $2 ]; then
echo "You must specify a save name for your new game"
exit 1
fi
savename="${WRITE_DIR}/saves/$2"
createsavecmd="$BINARY --create \"${savename}\""
# Check if user wants to use custom map gen settings
if [ $3 ]; then
if [ -e "${WRITE_DIR}/$3" ]; then
createsavecmd="$createsavecmd --map-gen-settings=${WRITE_DIR}/$3"
else
echo "Specified map gen settings json does not exist"
exit 1
fi
fi
# Check if user wants to use custom map settings
if [ $4 ]; then
if [ -e "${WRITE_DIR}/$4" ]; then
createsavecmd="$createsavecmd --map-settings=${WRITE_DIR}/$4"
else
echo "Specified map settings json does not exist"
exit 1
fi
fi
# Stop Service
if is_running; then
send_cmd "Generating new save, please stand by"
if ! stop_service; then
echo "Failed to stop server, unable to create new save"
exit 1
fi
fi
if ! run_context "$createsavecmd ${EXE_ARGS_GLIBC}"; then
echo "Failed to create new game"
exit 1
else
echo "New game created: ${savename}.zip"
fi
;;
save-game)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
savename="${WRITE_DIR}/saves/$2.zip"
# Stop Service
if is_running; then
send_cmd "Stopping server to save game"
if ! stop_service; then
echo "Failed to stop server, unable to save as \"$2\""
exit 1
fi
fi
lastsave=$(find "${WRITE_DIR}/saves" -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" ")
if ! run_context "cp \"${lastsave}\" \"${savename}\""; then
echo "Error! Failed to save game"
exit 1
fi
;;
load-save)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
# Ensure we get a new save file name
newsave=${WRITE_DIR}/saves/$2.zip
if [ ! -f "${newsave}" ]; then
echo "Save \"${newsave}\" does not exist, aborting action!"
exit 1
fi
# Since stopping the server causes a save we have to stop the server to do this
if is_running; then
send_cmd "Stopping server to load a saved game"
if ! stop_service; then
echo "Aborting, unable to stop $SERVICE_NAME"
exit 1
fi
fi
# Touch the new save file
run_context "touch \"${newsave}\""
;;
install)
install "$2"
;;
update)
update "$2"
;;
inv|invocation)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
echo ${INVOCATION}
;;
help|--help|-h)
usage
;;
listcommands)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
echo `$0 help 2> /dev/null |egrep '^ ' |awk '{ print $1 }'`
;;
listsaves)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
find ${WRITE_DIR} -type f -name "*.zip" -exec basename {} \; |sed -e 's/.zip//'
;;
version)
# Also verify that this script is running the correct context.
verify_user ${SCRIPT_ARGS};
echo `get_bin_version`
;;
source)
# do not call `exit` and just return successfully, so that other scripts (possibly with set -e) may source this script to import all out variables and functions
return 0
;;
*)
echo "No such command!"
echo
usage
exit 1
;;
esac
exit 0