/
helpers.sh
1399 lines (1257 loc) · 46.3 KB
/
helpers.sh
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
#!/bin/bash
# This file is part of The RetroPie Project
#
# The RetroPie Project is the legal property of its developers, whose names are
# too numerous to list here. Please refer to the COPYRIGHT.md file distributed with this source.
#
# See the LICENSE.md file at the top-level directory of this distribution and
# at https://raw.githubusercontent.com/RetroPie/RetroPie-Setup/master/LICENSE.md
#
## @file helpers.sh
## @brief RetroPie helpers library
## @copyright GPLv3
## @fn printMsgs()
## @param type style of display to use - dialog, console or heading
## @param message string or array of messages to display
## @brief Prints messages in a variety of ways.
function printMsgs() {
local type="$1"
shift
if [[ "$__nodialog" == "1" && "$type" == "dialog" ]]; then
type="console"
fi
for msg in "$@"; do
[[ "$type" == "dialog" ]] && dialog --backtitle "$__backtitle" --cr-wrap --no-collapse --msgbox "$msg" 20 60 >/dev/tty
[[ "$type" == "console" ]] && echo -e "$msg"
[[ "$type" == "heading" ]] && echo -e "\n= = = = = = = = = = = = = = = = = = = = =\n$msg\n= = = = = = = = = = = = = = = = = = = = =\n"
done
return 0
}
## @fn printHeading()
## @param message string or array of messages to display
## @brief Calls PrintMsgs with "heading" type.
function printHeading() {
printMsgs "heading" "$@"
}
## @fn fatalError()
## @param message string or array of messages to display
## @brief Calls PrintMsgs with "heading" type, and exits immediately.
function fatalError() {
printHeading "Error"
echo -e "$1"
joy2keyStop
exit 1
}
# @fn fnExists()
# @param name name of function to check for
# @brief Checks if function name exists.
# @retval 0 if the function name exists
# @retval 1 if the function name does not exist
function fnExists() {
declare -f "$1" > /dev/null
return $?
}
function ask() {
echo -e -n "$@" '[y/n] ' ; read ans
case "$ans" in
y*|Y*) return 0 ;;
*) return 1 ;;
esac
}
## @fn runCmd()
## @param command command to run
## @brief Calls command and record any non zero return codes for later printing.
## @return whatever the command returns.
function runCmd() {
local ret
"$@"
ret=$?
if [[ "$ret" -ne 0 ]]; then
md_ret_errors+=("Error running '$*' - returned $ret")
fi
return $ret
}
## @fn hasFlag()
## @param string string to search in
## @param flag flag to search for
## @brief Checks for a flag in a string (consisting of space separated flags).
## @retval 0 if the flag was found
## @retval 1 if the flag was not found
function hasFlag() {
local string="$1"
local flag="$2"
[[ -z "$string" || -z "$flag" ]] && return 1
if [[ "$string" =~ (^| )$flag($| ) ]]; then
return 0
else
return 1
fi
}
## @fn isPlatform()
## @param platform
## @brief Test for current platform / platform flags.
function isPlatform() {
local flag="$1"
if hasFlag "$__platform $__platform_flags" "$flag"; then
return 0
fi
return 1
}
## @fn addLineToFile()
## @param line line to add
## @param file file to add line to
## @brief Adds a new line of text to a file.
function addLineToFile() {
if [[ -f "$2" ]]; then
cp -p "$2" "$2.bak"
else
sed -i --follow-symlinks '$a\' "$2"
fi
echo "$1" >> "$2"
}
## @fn editFile()
## @param file file to edit
## @brief Opens an editing dialog for specified file.
function editFile() {
local file="$1"
local cmd=(dialog --backtitle "$__backtitle" --editbox "$file" 22 76)
local choice=$("${cmd[@]}" 2>&1 >/dev/tty)
[[ -n "$choice" ]] && echo "$choice" >"$file"
}
## @fn hasPackage()
## @param package name of Debian package
## @param version requested version (optional)
## @param comparison type of comparison - defaults to `ge` (greater than or equal) if a version parameter is provided.
## @brief Test for an installed Debian package / package version.
## @retval 0 if the requested package / version was installed
## @retval 1 if the requested package / version was not installed
function hasPackage() {
local pkg="$1"
local req_ver="$2"
local comp="$3"
[[ -z "$comp" ]] && comp="ge"
local status=$(dpkg-query -W --showformat='${Status} ${Version}' $1 2>/dev/null)
if [[ $? -eq 0 ]]; then
local ver="${status##* }"
local status="${status% *}"
# if status doesn't contain "ok installed" package is not installed
if [[ "$status" == *"ok installed" ]]; then
# if we didn't request a version number, be happy with any
[[ -z "$req_ver" ]] && return 0
compareVersions "$ver" "$comp" "$req_ver" && return 0
fi
fi
return 1
}
## @fn aptUpdate()
## @brief Calls apt-get update (if it has not been called before).
function aptUpdate() {
if [[ "$__apt_update" != "1" ]]; then
apt-get update
__apt_update="1"
fi
}
## @fn aptInstall()
## @param packages package / space separated list of packages to install
## @brief Calls apt-get install with the packages provided.
function aptInstall() {
aptUpdate
apt-get install -y "$@"
return $?
}
## @fn aptRemove()
## @param packages package / space separated list of packages to install
## @brief Calls apt-get remove with the packages provided.
function aptRemove() {
aptUpdate
apt-get remove -y "$@"
return $?
}
## @fn getDepends()
## @param packages package / space separated list of packages to install
## @brief Installs packages if they are not installed.
## @retval 0 on success
## @retval 1 on failure
function getDepends() {
local required
local packages=()
local failed=()
# check whether to use our own sdl2 - can be disabled to resolve issues with
# mixing custom 64bit sdl2 and os distributed i386 version on multiarch
local own_sdl2=1
# default to off for x11 targets due to issues with dependencies with recent
# Ubuntu (19.04). eg libavdevice58 requiring exactly 2.0.9 sdl2.
isPlatform "x11" && own_sdl2=0
iniConfig " = " '"' "$configdir/all/retropie.cfg"
iniGet "own_sdl2"
[[ "$ini_value" == 1 ]] && own_sdl2=1
[[ "$ini_value" == 0 ]] && own_sdl2=0
for required in $@; do
# workaround for different package names on osmc / xbian
if [[ "$required" == "libraspberrypi-bin" ]]; then
isPlatform "osmc" && required="rbp-userland-osmc"
isPlatform "xbian" && required="xbian-package-firmware"
fi
if [[ "$required" == "libraspberrypi-dev" ]]; then
isPlatform "osmc" && required="rbp-userland-dev-osmc"
isPlatform "xbian" && required="xbian-package-firmware"
fi
# map libpng12-dev to libpng-dev for Stretch+
if [[ "$required" == "libpng12-dev" ]] && compareVersions "$__os_debian_ver" ge 9; then
required="libpng-dev"
printMsgs "console" "RetroPie module references libpng12-dev and should be changed to libpng-dev"
fi
# map libpng-dev to libpng12-dev for Jessie
if [[ "$required" == "libpng-dev" ]] && compareVersions "$__os_debian_ver" lt 9; then
required="libpng12-dev"
fi
if [[ "$md_mode" == "install" ]]; then
# make sure we have our sdl1 / sdl2 installed
if ! isPlatform "x11" && [[ "$required" == "libsdl1.2-dev" ]] && hasPackage libsdl1.2-dev $(get_pkg_ver_sdl1) "ne"; then
packages+=("$required")
continue
fi
if [[ "$own_sdl2" -eq 1 && "$required" == "libsdl2-dev" ]] && hasPackage libsdl2-dev $(get_pkg_ver_sdl2) "ne"; then
packages+=("$required")
continue
fi
# make sure libraspberrypi-dev/libraspberrypi0 is up to date.
if [[ "$required" == "libraspberrypi-dev" ]] && hasPackage libraspberrypi-dev 1.20170703-1 "lt"; then
packages+=("$required")
continue
fi
fi
if [[ "$md_mode" == "remove" ]]; then
hasPackage "$required" && packages+=("$required")
else
hasPackage "$required" || packages+=("$required")
fi
done
if [[ ${#packages[@]} -ne 0 ]]; then
if [[ "$md_mode" == "remove" ]]; then
apt-get remove --purge -y "${packages[@]}"
apt-get autoremove --purge -y
return 0
fi
echo "Did not find needed package(s): ${packages[@]}. I am trying to install them now."
# workaround to force installation of our fixed libsdl1.2 and custom compiled libsdl2
local temp=()
for required in ${packages[@]}; do
if isPlatform "rpi" && [[ "$required" == "libsdl1.2-dev" ]]; then
if [[ "$__has_binaries" -eq 1 ]]; then
rp_callModule sdl1 install_bin
else
rp_callModule sdl1
fi
elif [[ "$required" == "libsdl2-dev" && "$own_sdl2" == "1" ]]; then
if [[ "$__has_binaries" -eq 1 ]]; then
rp_callModule sdl2 install_bin
else
rp_callModule sdl2
fi
else
temp+=("$required")
fi
done
packages=("${temp[@]}")
aptInstall --no-install-recommends "${packages[@]}"
# check the required packages again rather than return code of apt-get,
# as apt-get might fail for other reasons (eg other half installed packages)
for required in ${packages[@]}; do
if ! hasPackage "$required"; then
# workaround for installing samba in a chroot (fails due to failed smbd service restart)
# we replace the init.d script with an empty script so the install completes
if [[ "$required" == "samba" && "$__chroot" -eq 1 ]]; then
mv /etc/init.d/smbd /etc/init.d/smbd.old
echo "#!/bin/sh" >/etc/init.d/smbd
chmod u+x /etc/init.d/smbd
apt-get -f install
mv /etc/init.d/smbd.old /etc/init.d/smbd
else
failed+=("$required")
fi
fi
done
if [[ ${#failed[@]} -eq 0 ]]; then
printMsgs "console" "Successfully installed package(s): ${packages[*]}."
else
md_ret_errors+=("Could not install package(s): ${failed[*]}.")
return 1
fi
fi
return 0
}
## @fn rpSwap()
## @param command *on* to add swap if needed and *off* to remove later
## @param memory total memory needed (swap added = memory needed - available memory)
## @brief Adds additional swap to the system if needed.
function rpSwap() {
local command=$1
local swapfile="$__swapdir/swap"
case $command in
on)
rpSwap off
local memory=$(free -t -m | awk '/^Total:/{print $2}')
local needed=$2
local size=$((needed - memory))
mkdir -p "$__swapdir/"
if [[ $size -ge 0 ]]; then
echo "Adding $size MB of additional swap"
fallocate -l ${size}M "$swapfile"
chmod 600 "$swapfile"
mkswap "$swapfile"
swapon "$swapfile"
fi
;;
off)
echo "Removing additional swap"
swapoff "$swapfile" 2>/dev/null
rm -f "$swapfile"
;;
esac
}
## @fn gitPullOrClone()
## @param dest destination directory
## @param repo repository to clone or pull from
## @param branch branch to clone or pull from (optional)
## @param commit specific commit to checkout (optional - requires branch to be set)
## @brief Git clones or pulls a repository.
function gitPullOrClone() {
local dir="$1"
local repo="$2"
local branch="$3"
[[ -z "$branch" ]] && branch="master"
local commit="$4"
if [[ -d "$dir/.git" ]]; then
pushd "$dir" > /dev/null
runCmd git checkout "$branch"
runCmd git pull
runCmd git submodule update --init --recursive
popd > /dev/null
else
local git="git clone --recursive"
if [[ "$__persistent_repos" -ne 1 && "$repo" == *github* && -z "$commit" ]]; then
git+=" --depth 1"
fi
[[ "$branch" != "master" ]] && git+=" --branch $branch"
printMsgs "console" "$git \"$repo\" \"$dir\""
runCmd $git "$repo" "$dir"
fi
if [[ -n "$commit" ]]; then
printMsgs "console" "Winding back $repo->$branch to commit: #$commit"
git -C "$dir" branch -D "$commit" &>/dev/null
runCmd git -C "$dir" checkout -f "$commit" -b "$commit"
fi
branch=$(runCmd git -C "$dir" rev-parse --abbrev-ref HEAD)
commit=$(runCmd git -C "$dir" rev-parse HEAD)
printMsgs "console" "HEAD is now in branch '$branch' at commit '$commit'"
}
# @fn setupDirectories()
# @brief Makes sure some required retropie directories and files are created.
function setupDirectories() {
mkdir -p "$rootdir"
mkUserDir "$datadir"
mkUserDir "$romdir"
mkUserDir "$biosdir"
mkUserDir "$configdir"
mkUserDir "$configdir/all"
# some home folders for configs that modules rely on
mkUserDir "$home/.cache"
mkUserDir "$home/.config"
mkUserDir "$home/.local"
mkUserDir "$home/.local/share"
# make sure we have inifuncs.sh in place and that it is up to date
mkdir -p "$rootdir/lib"
local helper_libs=(inifuncs.sh archivefuncs.sh)
for helper in "${helper_libs[@]}"; do
if [[ ! -f "$rootdir/lib/$helper" || "$rootdir/lib/$helper" -ot "$scriptdir/scriptmodules/$helper" ]]; then
cp --preserve=timestamps "$scriptdir/scriptmodules/$helper" "$rootdir/lib/$helper"
fi
done
# create template for autoconf.cfg and make sure it is owned by $user
local config="$configdir/all/autoconf.cfg"
if [[ ! -f "$config" ]]; then
echo "# this file can be used to enable/disable retropie autoconfiguration features" >"$config"
fi
chown $user:$user "$config"
}
## @fn rmDirExists()
## @param dir directory to remove
## @brief Removes a directory and all contents if it exists.
function rmDirExists() {
if [[ -d "$1" ]]; then
rm -rf "$1"
fi
}
## @fn mkUserDir()
## @param dir directory to create
## @brief Creates a directory owned by the current user.
function mkUserDir() {
mkdir -p "$1"
chown $user:$user "$1"
}
## @fn mkRomDir()
## @param dir rom directory to create
## @brief Creates a directory under $romdir owned by the current user.
function mkRomDir() {
mkUserDir "$romdir/$1"
if [[ "$1" == "megadrive" ]]; then
pushd "$romdir"
ln -snf "$1" "genesis"
popd
fi
}
## @fn moveConfigDir()
## @param from source directory
## @param to destination directory
## @brief Moves the contents of a folder and symlinks to the new location.
function moveConfigDir() {
local from="$1"
local to="$2"
# if we are in remove mode - remove the symlink
if [[ "$md_mode" == "remove" ]]; then
[[ -h "$from" ]] && rm -f "$from"
return
fi
mkUserDir "$to"
# move any old configs to the new location
if [[ -d "$from" && ! -h "$from" ]]; then
cp -a "$from/." "$to/"
rm -rf "$from"
fi
ln -snf "$to" "$from"
# set ownership of the actual link to $user
chown -h $user:$user "$from"
}
## @fn moveConfigFile()
## @param from source file
## @param to destination file
## @brief Moves the file and symlinks to the new location.
function moveConfigFile() {
local from="$1"
local to="$2"
# if we are in remove mode - remove the symlink
if [[ "$md_mode" == "remove" && -h "$from" ]]; then
rm -f "$from"
return
fi
# move old file
if [[ -f "$from" && ! -h "$from" ]]; then
mv "$from" "$to"
fi
ln -sf "$to" "$from"
# set ownership of the actual link to $user
chown -h $user:$user "$from"
}
## @fn diffFiles()
## @param file1 file to compare
## @param file2 file to compare
## @brief Compares two files using diff.
## @retval 0 if the files were the same
## @retval 1 if they were not
## @retval >1 an error occurred
function diffFiles() {
diff -q "$1" "$2" >/dev/null
return $?
}
## @fn compareVersions()
## @param version first version to compare
## @param operator operator to use (lt le eq ne ge gt)
## @brief version second version to compare
## @retval 0 if the comparison was true
## @retval 1 if the comparison was false
function compareVersions() {
dpkg --compare-versions "$1" "$2" "$3" >/dev/null
return $?
}
## @fn dirIsEmpty()
## @param path path to directory
## @param files_only set to 1 to ignore sub directories
## @retval 0 if the directory is empty
## @retval 1 if the directory is not empty
function dirIsEmpty() {
if [[ "$2" -eq 1 ]]; then
[[ -z "$(ls -lA1 "$1" | grep "^-")" ]] && return 0
else
[[ -z "$(ls -A "$1")" ]] && return 0
fi
return 1
}
## @fn copyDefaultConfig()
## @param from source file
## @param to destination file
## @brief Copies a default configuration.
## @details Copies from the source file to the destination file if the destination
## file doesn't exist. If the destination is the same nothing is done. If different
## the source is copied to `$destination.rp-dist`.
function copyDefaultConfig() {
local from="$1"
local to="$2"
# if the destination exists, and is different then copy the config as name.rp-dist
if [[ -f "$to" ]]; then
if ! diffFiles "$from" "$to"; then
to+=".rp-dist"
printMsgs "console" "Copying new default configuration to $to"
cp "$from" "$to"
fi
else
printMsgs "console" "Copying default configuration to $to"
cp "$from" "$to"
fi
chown $user:$user "$to"
}
## @fn renameModule()
## @param from source file
## @param to destination file
## @brief Renames an existing module.
## @details Renames an existing module, moving it's install folder to the new location
## and changing any references to it in `emulators.cfg`.
function renameModule() {
local from="$1"
local to="$2"
# move from old location and update emulators.cfg
if [[ -d "$rootdir/$md_type/$from" ]]; then
rm -rf "$rootdir/$md_type/$to"
mv "$rootdir/$md_type/$from" "$rootdir/$md_type/$to"
# replace any default = "$from"
sed -i --follow-symlinks "s/\"$from\"/\"$to\"/g" "$configdir"/*/emulators.cfg
# replace any $from = "cmdline"
sed -i --follow-symlinks "s/^$from\([ =]\)/$to\1/g" "$configdir"/*/emulators.cfg
# replace any paths with /$from/
sed -i --follow-symlinks "s|/$from/|/$to/|g" "$configdir"/*/emulators.cfg
fi
}
## @fn addUdevInputRules()
## @brief Creates a udev rule to adjust input device permissions.
## @details Creates a udev rule in `/etc/udev/rules.d/99-input.rules` to
## make everything in `/dev/input` it writable by any user in group `input`.
function addUdevInputRules() {
if [[ ! -f /etc/udev/rules.d/99-input.rules ]]; then
echo 'SUBSYSTEM=="input", GROUP="input", MODE="0660"' > /etc/udev/rules.d/99-input.rules
fi
# remove old 99-evdev.rules
rm -f /etc/udev/rules.d/99-evdev.rules
}
## @fn setDispmanx()
## @param module_id name of module to add dispmanx flag for
## @param status initial status of flag (0 or 1)
## @brief Sets a dispmanx flag for a module.
## @details Set a dispmanx flag for a module as to whether it should use the
## sdl1 dispmanx backend by default or not (0 for framebuffer, 1 for dispmanx).
function setDispmanx() {
isPlatform "rpi" || return
local mod_id="$1"
local status="$2"
iniConfig "=" "\"" "$configdir/all/dispmanx.cfg"
iniSet $mod_id "$status"
chown $user:$user "$configdir/all/dispmanx.cfg"
}
## @fn iniFileEditor()
## @param delim ini file delimiter eg. ' = '
## @param quote ini file quoting character eg. '"'
## @param config ini file to edit
## @brief Allows editing of ini files with a user friendly dialog based gui.
## @details Some arrays need to be configured before calling this, which are
## used to display what can be edited and the options available.
##
## The first array is `$ini_titles` which provides the titles for each
## entry..
##
## The second array is `$ini_descs` which contains a help description for each
## entry.
##
## The third array is `$ini_options` which contains multiple space separated
## strings in each element to control how each entry should be managed.
##
## The `$ini_options` array is constructed as follows:
##
## If the first string is `_function_` then the next string should be a function
## name that will handle that entry. The function will be called with a parameter
## `get` or `set`. The function should return the value for get via `echo`
## and should handle any gui functionality when called with `set`. This can be
## used for example to build custom dialogs.
##
## If the first option is anything else, it is assumed to be a key name, followed
## by a control type and a list of parameters.
##
## Control types are:
## * `_id_` map the following values to an id
## * `_string_` allow the value to be inputted by the user
## * `_file_` select from a list of files. The following values are wildcard,
## then file path.
##
## If none of the above, then the rest of the array element should be a list of
## possible values for the key.
##
## Some examples for ini_options:
##
## ini_options=('video_smooth true false')
## Allow setting of the key `video_smooth` with the values of *true* or *false*
##
## ini_options=('aspect_ratio_index _id_ 4:3 16:9 16:10)
## Allow setting of the key `aspect_ratio_index` with the values 0 1 or 2 which
## correspond to the ratios. The user is shown the ratios, but the ini configuration
## is set to the id (4:3 = 0, 16:9 = 1, 16:10 = 2).
##
## ini_options=('_function_ _video_fullscreen_configedit')
## The function `_video_fullscreen_configedit` is called with *get* or *set*
## to manage this entry.
##
## ini_options=("video_shader _file_ *.*p $rootdir/emulators/retroarch/shader")
## The key `video_shader` will be able to be set to a list of files in
## `$rootdir/emulators/retroarch/shader` that match the wildcard `*.*p`
##
## For more examples you can check out the code in supplementary/configedit.sh
function iniFileEditor() {
local delim="$1"
local quote="$2"
local config="$3"
[[ ! -f "$config" ]] && return
iniConfig "$delim" "$quote" "$config"
local sel
local value
local option
local title
while true; do
local options=()
local params=()
local values=()
local keys=()
local i=0
# generate menu from options
for option in "${ini_options[@]}"; do
# split into new array (globbing safe)
read -ra option <<<"$option"
key="${option[0]}"
keys+=("$key")
params+=("${option[*]:1}")
# if the first parameter is _function_ we call the second parameter as a function
# so we can handle some options with a custom menu etc
if [[ "$key" == "_function_" ]]; then
value="$(${option[1]} get)"
else
# get current value
iniGet "$key"
if [[ -n "$ini_value" ]]; then
value="$ini_value"
else
value="unset"
fi
fi
values+=("$value")
# add the matching value to our id in _id_ lists
if [[ "${option[1]}" == "_id_" && "$value" != "unset" ]]; then
value+=" - ${option[value+2]}"
fi
# use custom title if provided
if [[ -n "${ini_titles[i]}" ]]; then
title="${ini_titles[i]}"
else
title="$key"
fi
options+=("$i" "$title ($value)" "${ini_descs[i]}")
((i++))
done
local cmd=(dialog --backtitle "$__backtitle" --default-item "$sel" --item-help --help-button --menu "Please choose the setting to modify in $config" 22 76 16)
sel=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty)
if [[ "${sel[@]:0:4}" == "HELP" ]]; then
printMsgs "dialog" "${sel[@]:5}"
continue
fi
[[ -z "$sel" ]] && break
# if the key is _function_ we handle the option with a custom function
if [[ "${keys[sel]}" == "_function_" ]]; then
"${params[sel]}" set "${values[sel]}"
continue
fi
# process the editing of the option
i=0
options=("U" "unset")
local default=""
# split into new array (globbing safe)
read -ra params <<<"${params[sel]}"
local mode="${params[0]}"
case "$mode" in
_string_)
options+=("E" "Edit (Currently ${values[sel]})")
;;
_file_)
local match="${params[1]}"
local path="${params[*]:2}"
local file
while read file; do
[[ "${values[sel]}" == "$file" ]] && default="$i"
file="${file//$path\//}"
options+=("$i" "$file")
((i++))
done < <(find -L "$path" -type f -name "$match" | sort)
;;
_id_|*)
[[ "$mode" == "_id_" ]] && params=("${params[@]:1}")
for option in "${params[@]}"; do
if [[ "$mode" == "_id_" ]]; then
[[ "${values[sel]}" == "$i" ]] && default="$i"
else
[[ "${values[sel]}" == "$option" ]] && default="$i"
fi
options+=("$i" "$option")
((i++))
done
;;
esac
[[ -z "$default" ]] && default="U"
# display values
cmd=(dialog --backtitle "$__backtitle" --default-item "$default" --menu "Please choose the value for ${keys[sel]}" 22 76 16)
local choice=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty)
# if it is a _string_ type we will open an inputbox dialog to get a manual value
if [[ -z "$choice" ]]; then
continue
elif [[ "$choice" == "E" ]]; then
[[ "${values[sel]}" == "unset" ]] && values[sel]=""
cmd=(dialog --backtitle "$__backtitle" --inputbox "Please enter the value for ${keys[sel]}" 10 60 "${values[sel]}")
value=$("${cmd[@]}" 2>&1 >/dev/tty)
elif [[ "$choice" == "U" ]]; then
value=""
else
if [[ "$mode" == "_id_" ]]; then
value="$choice"
else
# get the actual value from the options array
local index=$((choice*2+3))
if [[ "$mode" == "_file_" ]]; then
value="$path/${options[index]}"
else
value="${options[index]}"
fi
fi
fi
if [[ "$choice" == "U" ]]; then
iniUnset "${keys[sel]}" "$value"
else
iniSet "${keys[sel]}" "$value"
fi
done
}
## @fn setESSystem()
## @param fullname full name of system
## @param name short name of system
## @param path rom path
## @param extension file extensions to show
## @param command command to run
## @param platform name of platform (used by es for scraping)
## @param theme name of theme to use
## @brief Adds a system entry for Emulation Station (to /etc/emulationstation/es_systems.cfg).
function setESSystem() {
local function
for function in $(compgen -A function _add_system_); do
"$function" "$@"
done
}
## @fn ensureSystemretroconfig()
## @param system system to create retroarch.cfg for
## @param shader set a default shader to use (deprecated)
## @brief Creates a default retroarch.cfg for specified system in `/opt/retropie/configs/$system/retroarch.cfg`.
function ensureSystemretroconfig() {
local system="$1"
local shader="$2"
if [[ ! -d "$configdir/$system" ]]; then
mkUserDir "$configdir/$system"
fi
local config="$(mktemp)"
# add the initial comment regarding include order
echo -e "# Settings made here will only override settings in the global retroarch.cfg if placed above the #include line\n" >"$config"
# add the per system default settings
iniConfig " = " '"' "$config"
iniSet "input_remapping_directory" "$configdir/$system/"
if [[ -n "$shader" ]]; then
iniUnset "video_smooth" "false"
iniSet "video_shader" "$emudir/retroarch/shader/$shader"
iniUnset "video_shader_enable" "true"
fi
# include the main retroarch config
echo -e "\n#include \"$configdir/all/retroarch.cfg\"" >>"$config"
copyDefaultConfig "$config" "$configdir/$system/retroarch.cfg"
rm "$config"
}
## @fn setRetroArchCoreOption()
## @param option option to set
## @param value value to set
## @brief Sets a retroarch core option in `$configdir/all/retroarch-core-options.cfg`.
function setRetroArchCoreOption() {
local option="$1"
local value="$2"
iniConfig " = " "\"" "$configdir/all/retroarch-core-options.cfg"
iniGet "$option"
if [[ -z "$ini_value" ]]; then
iniSet "$option" "$value"
fi
chown $user:$user "$configdir/all/retroarch-core-options.cfg"
}
## @fn setConfigRoot()
## @param dir directory under $configdir to use
## @brief Sets module config root `$md_conf_root` to subfolder from `$configdir`
## @details This is used for ports that are not actually in scriptmodules/ports
## as they would get the wrong config root otherwise.
function setConfigRoot() {
local dir="$1"
md_conf_root="$configdir"
[[ -n "$dir" ]] && md_conf_root+="/$dir"
mkUserDir "$md_conf_root"
}
## @fn loadModuleConfig()
## @param params space separated list of key=value parameters
## @brief Load the settings for a module.
## @details This allows modules to quickly load some settings from an ini file.
## It can provide a shortcut way to load a set of keys from an ini file into
## variables.
##
## It requires iniConfig to be called first to specify the format and file.
## eg.
##
## iniConfig " = " '"' "$configdir/all/mymodule.cfg"
## eval $(loadModuleConfig \
## 'some_option=1' \
## 'another_option=2'
##
## This would load the keys `some_option` and `another_option` into local
## variables `some_option` and `another_option`. If the keys did not exist
## in mymodule.cfg the variables would be initialised to 1 and 2.
function loadModuleConfig() {
local options=("$@")
local option
local key
local value
for option in "${options[@]}"; do
option=(${option/=/ })
key="${option[0]}"
value="${option[@]:1}"
iniGet "$key"
if [[ -z "$ini_value" ]]; then
iniSet "$key" "$value"
echo "local $key=\"$value\""
else
echo "local $key=\"$ini_value\""
fi
done
}
## @fn applyPatch()
## @param patch filename of patch to apply
## @brief Apply a patch if it has not already been applied to current folder.
## @details This is used for applying patches against upstream code.
## @retval 0 on success
## @retval 1 on failure
function applyPatch() {
local patch="$1"
local patch_applied="${patch##*/}.applied"
if [[ ! -f "$patch_applied" ]]; then
if patch -f -p1 <"$patch"; then
touch "$patch_applied"
printMsgs "console" "Successfully applied patch: $patch"
else
md_ret_errors+=("$md_id patch $patch failed to apply")
return 1
fi
fi
return 0
}
## @fn downloadAndExtract()
## @param url url of archive
## @param dest destination folder for the archive
## @param optional additional parameters to pass to the decompression tool.
## @brief Download and extract an archive
## @details Download and extract an archive.
## @retval 0 on success
function downloadAndExtract() {
local url="$1"
local dest="$2"
shift 2
local opts=("$@")
local ext="${url##*.}"
local cmd=(tar -xv)
local is_tar=1
local ret
case "$ext" in
gz|tgz)
cmd+=(-z)
;;
bz2)
cmd+=(-j)
;;
xz)
cmd+=(-J)
;;
exe|zip)
is_tar=0
local tmp="$(mktemp -d)"
local file="${url##*/}"
runCmd wget -q -O"$tmp/$file" "$url"
runCmd unzip "${opts[@]}" -o "$tmp/$file" -d "$dest"
rm -rf "$tmp"
ret=$?
esac
if [[ "$is_tar" -eq 1 ]]; then
mkdir -p "$dest"
cmd+=(-C "$dest" "${opts[@]}")
runCmd "${cmd[@]}" < <(wget -q -O- "$url")
ret=$?
fi
return $ret
}
## @fn ensureFBMode()
## @param res_x width of mode
## @param res_y height of mode
## @brief Add a framebuffer mode to /etc/fb.modes