This repository has been archived by the owner on Feb 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcinit
executable file
·824 lines (798 loc) · 24.7 KB
/
mcinit
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
#!/bin/bash
#TODO: On server start (probably in the start method), check that world selected in server.properties exists in either regular world location or in WLDSTR; create empty folders in WLDSTR if not
CONFIG_FILE='mcinit.cfg'
SCRIPT=$(basename $0)
PID=''
source $CONFIG_FILE
declare -A worldInRam
main(){
# Check script dependencies
bashMajor=$(bash --version | head -n 1 | awk '{print $4}' | awk -F. '{ print $1}')
bashMinor=$(bash --version | head -n 1 | awk '{print $4}' | awk -F. '{ print $2}')
[[ ( ${bashMajor} -lt 4 && ${bashMinor} -lt 2 ) || ${bashMajor} -lt 4 ]] && echo "This script is only compatible with bash 4.2 or higher. Your bash version is ${bashMajor}.${bashMinor}" >&2 && exit 1
[[ ! -x ${JAVAEXEC} ]] && echo "Cannot find java executable. Please install java or enter the path to your java executable in the init script config file." >&2 && exit 1
[[ ! -f ${MCJAR} ]] && echo "Cannot find minecraft .jar file. Please enter the correvt path to your .jar file in the init script config file." >&2 && exit 1
[[ ! -x ${TMUXEXEC} ]] && echo "Cannot find tmux executable. Please install tmux or enter the path to your tmux executable in the init script config file." >&2 && exit 1
[[ ! -x ${RSYNCEXEC} ]] && echo "Cannot find rsync executable. Please install rsync or enter the path to your rsync executable in the init script config file." >&2 && exit 1
cd ${SRVDIR}
case $1 in
start)
if isRunning
then
echo "Minecraft is already running."
exit 0
else
toRam
checkLinks
runServer
fi
;;
stop)
if isRunning
then
echoModeChange SHUTDOWN 10
getWorlds
inRam=false
for wld in ${worldInRam[*]}
do
${wld} && inRam=true
done
${inRam} && toDisk
haltServer
cleanRam
else
echo "Minecraft is already stopped."
fi
;;
restart)
if isRunning
then
echoModeChange RESTART 10
toDisk
haltServer
checkLinks
runServer
else
echo "Cannot restart: minecraft is stopped"
fi
;;
status)
if isRunning
then
echo "Minecraft is running"
else
echo "Minecraft is not running"
fi
;;
roll-log)
logRoll
;;
archive)
declare -A arcMax arcPrefix
case $2 in
logs)
archiveLogs
arcMax[${LOGDIR}]=${LOGARCMAX}
arcPrefix[${LOGDIR}]='logs'
;;
worlds)
archiveWorlds
arcMax[${WLDBK}]=${WLDARCMAX}
arcPrefix[${WLDBK}]='worlds'
;;
plugins)
archivePlugins
arcMax[${PLGBK}]=${PLGARCMAX}
arcPrefix[${PLGBK}]='plugins'
;;
server)
archiveServer
arcMax[${SRVBK}]=${SRVARCMAX}
arcPrefix[${SRVBK}]='server'
;;
all)
archiveLogs
archiveServer
archivePlugins
archiveWorlds
arcMax[${LOGDIR}]=${LOGARCMAX}
arcPrefix[${LOGDIR}]='logs'
arcMax[${SRVBK}]=${SRVARCMAX}
arcPrefix[${SRVBK}]='server'
arcMax[${PLGBK}]=${PLGARCMAX}
arcPrefix[${PLGBK}]='plugins'
arcMax[${WLDBK}]=${WLDARCMAX}
arcPrefix[${WLDBK}]='worlds'
;;
*)
echo "Usage: ${SCRIPT} archive logs|worlds|plugins|server|all"
exit 0
;;
esac
for dir in ${!arcMax[*]}
do
if [[ ${arcMax[$dir]} -gt 0 ]]
then
arcs=($(ls ${dir}))
while [[ ${#arcs[*]} -gt ${arcMax[$dir]} ]]
do
delRemain=$(expr ${#arcs[*]} - ${arcMax[$dir]})
echo "Purging ${delRemain} old archive(s) from ${dir}..."
archiveRoll ${arcPrefix[$dir]} 'tar.gz' ${dir}
#TODO: Write a function to let the user know that the newly created archive has been rolled over to its new name (e.g., if message echos saying "successfully archived to worlds.10.tar.gz, then worlds.10 is immediately rolled to worlds.9, that's confusing).
arcs=($(ls ${dir}))
done
fi
done
;;
restore)
declare -A arcPfx rstrDir
case $2 in
logs)
arcPfx[${LOGDIR}]='logs'
rstrDir[${LOGDIR}]=${LOGDIR}
;;
worlds)
arcPfx[${WLDBK}]='worlds'
# TODO: FIX THIS BUG. If the string is only one field long, this will pass a blank directory name!
# could fix at arg passing time
dir=$(echo ${WLDSTR} | awk -F/ '{$NF=""; OFS="/"; print}')
rstrDir[${WLDBK}]=${dir}
;;
plugins)
arcPfx[${PLGBK}]='plugins'
rstrDir[${PLGBK}]=${SRVDIR}
;;
server)
arcPfx[${SRVBK}]='server'
rstrDir[${WLDBK}]=${SRVDIR}
;;
all)
arcPfx[${LOGDIR}]='logs'
arcPfx[${WLDBK}]='worlds'
arcPfx[${PLGBK}]='plugins'
arcPfx[${SRVBK}]='server'
wldDir=$(echo ${WLDSTR} | awk -F/ '{$NF=""; OFS=/; print}')
rstrDir[${LOGDIR}]=${LOGDIR}
rstrDir[${WLDBK}]=${wldDir}
rstrDir[${PLGBK}]=${SRVDIR}
rstrDir[${WLDBK}]=${SRVDIR}
;;
*)
echo "Usage: ${SCRIPT} restore logs|worlds|plugins|server|all [<archive number>]"
exit 0
;;
esac
for dir in ${!arcPfx[*]}
do
[[ ! ${rstrDir[$dir]} ]] && rstrDir[$dir]='.'
restoreArchive ${dir} ${rstrDir[$dir]} ${arcPfx[$dir]} 'tar.gz' $3
done
;;
ram)
wlds=($(echo $* | awk '{$1=""; $2=""; print}'))
i=0
while [[ ${i} -lt ${#wlds[*]} ]]
do
[[ ! -d ${WLDSTR}/${wlds[$i]} ]] && echo "${wlds[$i]} does not exist in ${WLDSTR}. No operation will be performed for this world." && wlds[$i]=''
(( i++ ))
done
case $2 in
on)
[[ ! ${wlds[*]} ]] && echo "No valid worlds selected for operation." && exit 0
for wld in ${wlds[*]}
do
ramdiskOn ${wld}
done
;;
off)
[[ ! ${wlds[*]} ]] && echo "No valid worlds selected for operation." && exit 0
for wld in ${wlds[*]}
do
ramdiskOff ${wld}
done
;;
ls)
inRam
[[ ${#ramWorlds[*]} -lt 1 ]] && echo "No worlds present in ramdisk." && exit 0
for wld in ${ramWorlds[*]}
do
echo "${wld}"
done
;;
enabled)
getWorlds
for wld in ${!worldInRam[*]}
do
[[ ${worldInRam[$wld]} == true ]] && echo ${wld}
done
;;
disabled)
getWorlds
for wld in ${!worldInRam[*]}
do
[[ ! ${worldInRam[$wld]} == true ]] && echo ${wld}
done
;;
clear)
[[ ! ${wlds[*]} ]] && echo "No valid worlds selected for operation." && exit 0
if ${WARN_ON_RAM_CLEAR}
then
echo -n "WARNING: This operation does NOT copy to disk before clearing worlds from RAM. Any changes made to worlds since last to-disk operation was run will be lost. Still proceed? (Y/n) "
read cont
[[ ${cont} != 'Y' ]] && echo "Y not selected: aborting..." && exit 0
fi
declare -A xstat
for wld in ${wlds[*]}
do
if [[ -e ${RAMDISK}/${wld} ]]
then
rm -r ${RAMDISK}/${wld}
xstat[$wld]=$?
else
echo "Wolrd ${wld} is not in RAM."
fi
done
for wld in ${!xstat[*]}
do
if [[ ${xstat[$wld]} ]]
then
echo "World ${wld} successfully cleared from RAM"
else
echo "Error ocurred clearing ${wld} from ram. Please investigate in ${RAMDISK}."
fi
done
;;
*)
echo "Usage:
${SCRIPT} ram on|off|clear <world names>
${SCRIPT} ram ls|enabled|disabled"
exit 0
;;
esac
;;
to-disk)
toDisk
;;
exec)
isRunning || ( echo "Cannot execute command: Server is not running." && exit 0 )
if [[ $2 ]]
then
# Shift statement shifts argument array to the left (much like perl) remaining args can then be passed
shift
tmux send -t ${SESSION} "$*" ENTER
sleep 0.25
tail server.log
else
echo "Usage: exec <mc server command>"
fi
;;
logtail)
if [[ $2 -gt 0 ]]
then
tail -n $2 server.log
else
tail server.log
fi
;;
console)
if ${WARN_ON_CONSOLE_ATTACH}
then
echo -n "You are about to attach to your minecraft console inside of a tmux session. In order to detach without stopping the server, you will need to enter the tmux command key (default: Ctrl + b) followed by the detatch key (default: d). Continue? (Y/n): "
read response
[[ ${response} != Y ]] && echo "Y not selected: aborting..." && exit 0
fi
tmux attach -t ${SESSION}
;;
*|help)
echo 'Usage:
start|stop|restart|status
roll-log
archive logs|worlds|plugins|server|all
restore logs|worlds|plugins|server|all [<archive number>]
ram on|off|clear <world names>
ram ls|enabled|disabled
to-disk
exec <mc server command>
logtail [<num lines>]
console'
;;
esac
}
isRunning(){
#################################################
# Check for running server instance;
# Return value of true if running, false if not.
#################################################
port=$(cat server.properties | grep server-port | cut -d= -f2)
test $? -ne 0 && echo "CRITICAL ERROR: Server has no port configured. Please configure the parameter server-port in server.properties" && exit 2
if netstat -nlp 2>/dev/null | egrep ":${port}\b" > /dev/null 2>&1
then
PID=$(netstat -nlp 2>/dev/null | egrep ":${port}\b" | awk '{print $7}' | cut -d/ -f1)
test -f ${RUNDIR}/${PID} && SESSION=$(cat ${RUNDIR}/${PID} 2> /dev/null)
return 0
else
return 1
fi
}
runServer(){
##############################################
# Initiate an instance of the minecraft server
##############################################
# Initiate server in tmux session
findSessionName
tmux new-session -ds ${SESSION} "${INVOCATION}"
echo -n "Starting minecraft..."
# 'cycle' variable tracks how many loops have been executed while waiting for the server to start
cycle=0
# Initiate loop which continues until both tmux and java are confirmed to be running
until isRunning
do
sleep 3
# Creates a nice animation while waiting for server start
[[ ${cycle} -gt 0 ]] && echo -n "."
# Fail out after 10 cycles (30 seconds) with error message
if [[ ${cycle} -ge 10 ]]
then
echo " Sever start failed with the following errors:"
[[ ! $(tmux list-sessions | egrep ${SESSION}:\ \[0-9\]+ > /dev/null) ]] && echo "Tmux session did not start."
[[ ! $(ps a | grep -v grep | grep "${INVOCATION}" > /dev/null) ]] && echo "Java was unable to start."
echo "Call in your sysadmin for backup."
return 1
fi
(( cycle++ ))
done
echo "${SESSION}" > ${RUNDIR}/${PID} 2>/dev/null
echo " Server started successfully. Attach to console using: ${SCRIPT} console"
return 0
}
haltServer(){
####################################################
# Stop the running instance of the minecraft server
####################################################
# Send save-all and stop commands to console for graceful shutdown
echo "Saving worlds..."
tmux send -t ${SESSION} "save-all" ENTER
sleep 1
tmux send -t ${SESSION} "stop" ENTER
echo -n "Stopping minecraft..."
cycle=0
# Wait for server to shut down
until ! isRunning
do
# Add nice animation while waiting for server shutdown
sleep 3
[[ ${cycle} -gt 0 ]] && echo -n "."
# Fail out with error messages if server is not stopped after 20 cycles (60 seconds)
if [[ ${cycle} -ge 20 ]]
then
echo " Sever did not cleanly stop after 60 seconds; you may need to kill java using one of the following commands:"
echo "kill ${PID}"
echo "kill -9 ${PID}"
echo
echo "Or call in your sysadmin for backup."
exit 1
fi
(( cycle++ ))
done
[[ $(tmux list-sessions | grep ${SESSION}) ]] && tmux kill-session -t ${SESSION}
# Success message
echo " Server cleanly shut down."
}
logRoll(){
##################################################################
# Flushes the server logfile into a log retention directory
# Log entries flushed on the same day are appended to the same file
###################################################################
# Check for log dir, create if does not exist
( [[ ! -d ${LOGDIR} ]] && mkdir -p ${LOGDIR} ) || ( echo "Could not create ${LOGDIR}. Log-roll aborted" && return 1 )
rollName="rolled.$(date +%d-%b-%Y).log"
# Create one rolled log per day; if logs rolled multiple times per day, append contents to same file
cat server.log >> ${LOGDIR}/${rollName}
# Clear log if successfully rolled, else fail out with error message
if [[ $? ]]
then
cp /dev/null server.log
echo "Log successfully rolled to ${LOGDIR}/${rollName}"
else
echo "Log roll failed: unable to write ${LOGDIR}/${rollName}"
fi
}
archiveLogs(){
##################################################
# Archives all logs in the log retention directory
# Purges log files after archiving
##################################################
( test -d ${LOGDIR} || mkdir -p ${LOGDIR} ) || ( echo "Could not create ${LOGDIR}. Log-roll aborted" && return 1 )
fileNum=0
tarName="logs.${fileNum}.tar.gz"
# Find first available filename
while [[ -f ${LOGDIR}/${tarName} ]]
do
(( fileNum++ ))
tarName="logs.${fileNum}.tar.gz"
done
cd ${LOGDIR}
# Add all logiles to the new archive
tar cpzvf ${tarName} ./*.log
# Clear logfiles if successfully archived; fail out with error if not
if [[ $? ]]
then
rm ./*.log
if [[ $? ]]
then
echo "Log files successfully archived in ${LOGDIR}/${tarName}"
# Provide warning if unable to clear logs
else
echo "Error ocurred: Archive was created in ${LOGDIR}/${tarName}, but failed to purge old logs from ${LOGDIR}."
exit 1
fi
else
echo "Failed to archive logs: could not create tarball in ${LOGDIR}/${tarName}"
exit 1
fi
cd ${SRVDIR}
}
archiveRoll(){
#########################################################################
# Find oldest archive, delete it;
# rename remaning archives accordingly.
# Takes 3 arguments:
# $1: Archive file prefix [Cannot contain a '.' or numeric characters]
# $2: Archive file suffix [Cannot contain numeric characters]
# $3: Archive file directory
#########################################################################
cd ${3}
rmFile=$(ls | grep "$1\.0\.$2")
if [[ ${rmFile} ]]
then
rm ${rmFile}
archives=($(ls | egrep "$1\.[0-9]+\.$2"))
for archive in ${archives[*]}
do
arcNum=$(echo ${archive} | awk -F. '{print $2}')
(( arcNum-- ))
newName=$(echo ${archive} | sed "s:[0-9]\+:${arcNum}:")
mv ${archive} ${newName}
done
if [[ $? ]]
then
echo "Log archives successfully rolled."
else
echo "There was an error rolling the log archives. Please investigate in you logs directory."
fi
else
echo "Cannot roll archives: Unable to locate ${1}.0.${2}"
exit 1
fi
cd ${SRVDIR}
}
getWorlds(){
#TODO: This function is not exporting its array. This makes it entirely useless.
#BUG: The problem appears to be with taking an associative array declared or populated inside of a function and accessing it outside of the function.
#########################################
# Get all worlds and ramdisk information;
# store in an associative array
#########################################
test -d ${WLDSTR} || return 2
for wld in $(ls ${WLDSTR})
do
if [[ -d ${WLDSTR}/${wld} ]]
then
if [[ -e ${WLDSTR}/${wld}/ramdisk ]]
then
worldInRam[${wld}]=true
else
worldInRam[${wld}]=false
fi
fi
done
return 0
}
ramdiskOn(){
###################
# Add ramdisk flag
###################
test -d ${WLDSTR} || return 2
[[ ! -e ${WLDSTR}/$1/ramdisk ]] && echo "This file is a flag marking this world as needing to be loaded in RAM. Its contents are entirely meangingless." > ${WLDSTR}/$1/ramdisk
}
ramdiskOff(){
#####################
# Remove ramdisk flag
#####################
test -d || return 2
[[ -e ${WLDSTR}/$1/ramdisk ]] && rm ${WLDSTR}/$1/ramdisk
}
toRam(){
#################################
# Copy all ramdisk worlds to RAM
#################################
( test -d ${RAMDISK} && test -d ${WLDSTR} ) || ( echo "Something went wrong. Double check your RAMDISK and WLDSTR directories" >&2 && return 2 )
isRunning && tmux send -t ${SESSION} "save-all" ENTER
getWorlds
for wld in ${!worldInRam[*]}
do
if ${worldInRam[$wld]}
then
if [[ ! -d ${RAMDISK}/${wld} ]]
then
echo "Copying ${wld} to Ram..."
rsync -rv ${WLDSTR}/${wld}/ ${RAMDISK}/${wld}/
if [[ $? ]]
then
echo "${wld} copied."
else
echo "Error copying ${wld}."
fi
else
echo "${wld} already in RAM. skipping..."
fi
fi
done
}
cleanRam(){
############################################
# Clear any existing worlds from the ramdisk
# DOES NOT SAVE WORLDS
############################################
test -d ${RAMDISK} || ( echo "Cannot clear ram. RAMDISK directory does not exist at ${RAMDISK}" && return 2 )
getWorlds
for wld in ${!worldInRam[*]}
do
if [[ -e ${RAMDISK}/${wld} ]]
then
rm -rf ${RAMDISK}/${wld}
fi
done
}
inRam(){
test -d ${RAMDISK} || return 2
getWorlds
ramWorlds=()
for wld in ${!worldInRam[*]}
do
[[ -d ${RAMDISK}/${wld} ]] && ramWorlds[${#ramWorlds[*]}]=${wld}
done
}
toDisk(){
###########################################
# Copy all worlds in RAM back to hard disk
###########################################
test -d ${RAMDISK} || ( echo "Cannot move ramdisk worlds to hard disk. RAMDISK does not exist at ${RAMDISK}" && return 2 )
( test -d ${WLDSTR} || mkdir -p ${WLDSTR} ) || return 2
isRunning && tmux send -t ${SESSION} "save-all" ENTER
getWorlds
noWorlds=true
for wld in ${!worldInRam[*]}
do
if [[ -d ${RAMDISK}/${wld} ]]
then
noWorlds=false
echo "Copying ${wld} to hard disk..."
rsync -rv ${RAMDISK}/${wld}/ ${WLDSTR}/${wld}/
fi
done
[[ ${noWorlds} == true ]] && echo "No worlds present in ramdisk to copy back to hard disk"
}
checkLinks(){
###############################################################
# Checks all symlinks to ensure they link to proper locations
# Linking to RAM when world is present in ramdisk
# Linking to world storage when present only on disk
###############################################################
# Abort link checks if server is already running
( test -d ${WLDSTR} || mkdir -p ${WLDSTR} ) || ( echo "Error creating links: WLDSTR does not exist at ${WLDSTR}" >&2 && return 2 )
isRunning && echo "Cannot change world links while server is running. Please stop server and retry operation." >&2 && return 1
getWorlds
for wld in ${!worldInRam[*]}
do
echo "Checking links for ${wld}"
# Check first to see if file exists
if [[ -e ${wld} ]]
then
# If file exists, check whether it is a symlink
if [[ -L ${wld} ]]
# If file is a symlink, check that it is linked to the correct place (RAM for RAM worlds, storage folder for non-RAM worlds)
then
link=$(ls -l | grep ${wld} | awk '{print $11}')
if [[ -d ${RAMDISK}/${wld} ]]
then
[[ ${link} != ${RAMDISK}/${wld} ]] && ln -sf ${RAMDISK}/${wld} ${wld}
else
cd ${WLDSTR}
wldStrPath=$(pwd)
cd - > /dev/null
[[ ${link} != ${wldStrPath}/${wld} ]] && ln -sf ${wldStrPath}/${wld}
fi
echo "Links OK for ${wld}"
# If file already exists in server directory by name of symlink, raise error message and exit
else
echo "Unable to create link for world ${wld}: filename already exists in ${SRVDIR}" >&2
exit 1
fi
# If file does not exist, create new symlink from correct place
else
if [[ -d ${RAMDISK}/${wld} ]]
then
ln -sf ${RAMDISK}/${wld} ${wld}
else
ln -sf $(cd ${WLDSTR}; pwd) ${wld}
fi
echo "Links created for ${wld}"
fi
done
}
archiveWorlds(){
#####################################################################
# Archives world storage directory
# Moves archive to a world backup directory (${WLDBK} directory)
#####################################################################
( test -d ${WLDBK} || mkdir -p ${WLDBK} ) || ( echo "Cannot archive worlds: WLDSTR does not exist at location ${WLDSTR}" >&2 && return 2 )
arcNum=0
while [[ -f "${WLDBK}/worlds.${arcNum}.tar.gz" ]]
do
(( arcNum++ ))
done
arcName="worlds.${arcNum}.tar.gz"
tar cpzvf ${WLDBK}/${arcName} ${WLDSTR}
if [[ $? ]]
then
echo "Worlds archived successfully to ${WLDBK}/${arcName}"
else
echo "There was an error archiving world storage folder to ${WLDBK}/${arcName}: please investigate in ${WLDBK}"
exit 1
fi
}
archivePlugins(){
####################################################################
# Archives plugins directory
# Moves archive into a plugins backup directory (${PLGBK} directory)
####################################################################
arcNum=0
if [[ ! -d ${PLGBK} ]]
then
echo "Attempting to create ${PLGBK}..."
mkdir -p ${PLGBK}
[[ ! $? ]] && echo "Failed to create ${PLGBK}. Please create this directory and try again." && exit 1
echo "Created ${PLGBK} successfully"
fi
while [[ -f "${PLGBK}/plugins.${arcNum}.tar.gz" ]]
do
(( arcNum++ ))
done
arcName="plugins.${arcNum}.tar.gz"
tar cpzvf ${PLGBK}/${arcName} plugins
if [[ $? ]]
then
echo "Plugins archived successfully to ${PLGBK}/${arcName}"
else
echo "There was an error archiving plugins folder to ${PLGBK}/${arcName}: please investigate in ${PLGBK}"
fi
}
archiveServer(){
################################################################################
# Archives all server files which are not related to worlds, plugins, or backups
# Moves archive into a server backup directory (${SRVBK} directory)
################################################################################
arcNum=0
if [[ ! -d ${SRVBK} ]]
then
echo "Attempting to create ${SRVBK}..."
mkdir -p ${SRVBK}
[[ ! $? ]] && echo "Failed to create ${SRVBK}. Please create this directory and try again." && exit 1
echo "Created ${SRVBK} successfully"
fi
while [[ -f "${SRVBK}/server.${arcNum}.tar.gz" ]]
do
(( arcNum++ ))
done
arcName="server.${arcNum}.tar.gz"
tar --exclude="${LOGDIR}" --exclude="${WLDBK}" --exclude="${WLDSTR}" --exclude="${PLGBK}" --exclude="plugins" --exclude="${SRVBK}" -cpzvf ${SRVBK}/${arcName} ./*
if [[ $? ]]
then
echo "Server files archived successfully to ${SRVBK}/${arcName}"
else
echo "There was an error archiving server files to ${SRVBK}/${arcName}: please investigate in ${SRVBK}"
fi
}
restoreArchive(){
################################################
# Restore an archive from an archive directory.
# Takes 5 arguments, the 5th being optional
# $1: Directory to retrieve archives from
# $2: Directory to copy and unpack archive into
# $3: Archive name prefix
# $4: Archive name suffix
# $5: [Optional] Archive number to restore
################################################
[[ ${#*} -lt 4 ]] && echo "Function restoreArchive needs at least 4 arguments, ${#*} were given. Please fix your modified script code." && exit 1
[[ ! -d ${1} || ! -d ${2} ]] && echo "Function restoreArchive was passed an invalid directory name. Please fix your modified script code." && exit 1
[[ ! $(ls ${1} | grep "${3}.[0-9]\+.${4}") ]] && "The specified archives could not be found in ${1}. Check the directory to make sure archives exist. If archives are present, double check any modified script code to ensure the function restoreArchive was correctly invoked." && exit 1
for archive in $(ls ${1} | grep "${3}.[0-9]\+.${4}")
do
# Populate array of all archives where index number corresponds to archive number
arcNum=$(echo ${archive} | awk -F. '{print $2}')
archives[$arcNum]=${archive}
done
if [[ $5 ]]
then
cp $1/${archives[$5]} $2
cd $2
tar xzvf ${archives[$5]}
xstat=$?
rm ${archives[$5]}
else
cp $1/${archives[-1]} $2
cd $2
tar xzvf ${archives[-1]}
xstat=$?
rm ${archives[-1]}
fi
if [[ $xstat ]]
then
echo "Archive successfully restored to ${2}"
else
echo "There was an error restoring the archive to ${2}. Are proper write permissions in place?"
exit 1
fi
}
sessionExists(){
##########################################################
# Checks whether current value set in SESSION env variable
# exists as a tmux session
##########################################################
if [[ -n $(tmux list-sessions 2> /dev/null | egrep "^${SESSION}:\s") ]]
then
return 0
else
return 1
fi
}
findSessionName(){
##########################################################
# loops through possible tmux session names until a not-
# in-use session name is found and sets it as SESSION
##########################################################
if ! sessionExists
then
return 0
else
sessionBase=${SESSION}
i=$(printf "%02d" 00)
SESSION="${sessionBase}${i}"
until ! sessionExists
do
i=$(printf "%02d" $(( ++i )))
SESSION=${sessionBase}{$i}
done
return 0
fi
}
echoModeChange(){
##########################################################
# Announces server mode change both to players and to
# command-line invoker
# Takes 2 arguments
# $1: New mode (e.g. SHUTDOWN. RESTART)
# $2: Delay in seconds
##########################################################
echo -n "Server going on mode $1 in $2 seconds."
$0 exec "say Server going on $1 in $2 seconds." > /dev/null
sleep 1 && echo -n "." && seconds=1
$0 exec "say Contact server administrator for details." > /dev/null
until [[ ${seconds} -ge $2 ]]
do
echo -n "."
sleep 1 && (( ++seconds ))
done
echo
return 0
}
# Run script as unpriveliged user, execute script from server directory
[[ ! $(cat /etc/passwd | egrep \(^${USER}:x:\)) ]] && echo "Cannot run server as ${USER}; user does not exist" && exit 1
if [[ $(whoami) != ${USER} ]]
then
echo "Executing as ${USER}..." && su ${USER} -c "$0 $*"
else
main $*
fi