forked from RetroPie/RetroPie-Setup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.sh
executable file
·1745 lines (1564 loc) · 59.5 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_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 inputBox()
## @param title title of dialog
## @param text default text
## @param minchars minimum chars to accept
## @brief Opens an inputbox dialog and echoes resulting text. Uses the OSK if installed.
## @details The input dialog has OK/Cancel buttons and can be cancelled by the user.
## The dialog will enforce the minimum number of characters expected, re-prompting the user.
## @retval 0 when the user entered the text and chose the OK button
## @retval != 0 when the user chose the Cancel button
function inputBox() {
local title="$1"
local text="$2"
local minchars="$3"
[[ -z "$minchars" ]] && minchars=0
local params=(--backtitle "$__backtitle" --inputbox "Enter the $title")
local osk="$(rp_getInstallPath joy2key)/osk.py"
if [[ -f "$osk" ]]; then
params+=(--minchars "$minchars")
text=$(python3 "$osk" "${params[@]}" "$text" 2>&1 >/dev/tty) || return $?
else
while true; do
text=$(dialog "${params[@]}" 10 60 "$text" 2>&1 >/dev/tty) || return $?
[[ "${#text}" -ge "$minchars" ]] && break
dialog --msgbox "$title must have at least $minchars characters" 8 60 2>&1 >/dev/tty
done
fi
echo "$text"
}
## @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 ver
local status
# extract the first line only (for cases where both amd64 & i386 versions of a package are installed)
local out=$(dpkg-query -W --showformat='${Status} ${Version}\n' $1 2>/dev/null | head -n1)
if [[ "$?" -eq 0 ]]; then
ver="${out##* }"
status="${out% *}"
fi
local installed=0
[[ "$status" == *"ok installed" ]] && installed=1
# if we are not checking version
if [[ -z "$req_ver" ]]; then
# if the package is installed return true
[[ "$installed" -eq 1 ]] && return 0
else
# if checking version and the package is not installed we need to clear "ver" as it may contain
# the version number of a removed package and give a false positive with compareVersions.
# we still need to do the version check even if not installed due to the varied boolean operators
[[ "$installed" -eq 0 ]] && ver=""
compareVersions "$ver" "$comp" "$req_ver" && return 0
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 --allow-releaseinfo-change
__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 $?
}
function _mapPackage() {
local pkg="$1"
case "$pkg" in
libraspberrypi-bin)
isPlatform "osmc" && pkg="rbp-userland-osmc"
isPlatform "xbian" && pkg="xbian-package-firmware"
;;
libraspberrypi-dev)
isPlatform "osmc" && pkg="rbp-userland-dev-osmc"
isPlatform "xbian" && pkg="xbian-package-firmware"
;;
mali-fbdev)
isPlatform "vero4k" && pkg=""
;;
# handle our custom package alias LINUX-HEADERS
LINUX-HEADERS)
if isPlatform "rpi"; then
if [[ "$__os_debian_ver" -lt 12 ]]; then
pkg="raspberrypi-kernel-headers"
else
# on RaspiOS bookworm and later, kernel packages are separated by arch and model
isPlatform "rpi0" || isPlatform "rpi1" && pkg="linux-headers-rpi-v6"
if isPlatform "32bit"; then
isPlatform "rpi2" || isPlatform "rpi3" && pkg="linux-headers-rpi-v7"
isPlatform "rpi4" && pkg="linux-headers-rpi-v7l"
else
isPlatform "rpi3" || isPlatform "rpi4" && pkg="linux-headers-rpi-v8"
isPlatform "rpi5" && pkg="linux-headers-rpi-2712"
fi
fi
elif isPlatform "armbian"; then
local branch="$(grep -oP "BRANCH=\K.*" /etc/armbian-release)"
local family="$(grep -oP "LINUXFAMILY=\K.*" /etc/armbian-release)"
pkg="linux-headers-${branch}-${family}"
elif [[ -z "$__os_ubuntu_ver" ]]; then
pkg="linux-headers-$(uname -r)"
else
pkg="linux-headers-generic"
fi
;;
# map libpng-dev to libpng12-dev for Jessie
libpng-dev)
[[ "$__os_debian_ver" -lt 9 ]] && pkg="libpng12-dev"
;;
libsdl1.2-dev)
rp_isEnabled "sdl1" && pkg="RP sdl1 $pkg"
;;
libsdl2-dev)
if rp_isEnabled "sdl2"; then
# 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"
if [[ "$ini_value" == "1" ]]; then
own_sdl2=1
elif [[ "$ini_value" == "0" ]]; then
own_sdl2=0
fi
[[ "$own_sdl2" -eq 1 ]] && pkg="RP sdl2 $pkg"
fi
;;
libfreetype6-dev)
[[ "$__os_debian_ver" -gt 10 ]] || compareVersions "$__os_ubuntu_ver" gt 23.04 && pkg="libfreetype-dev"
;;
esac
echo "$pkg"
}
## @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 own_pkgs=()
local apt_pkgs=()
local all_pkgs=()
local pkg
for pkg in "$@"; do
pkg=($(_mapPackage "$pkg"))
# manage our custom packages (pkg = "RP module_id pkg_name")
if [[ "${pkg[0]}" == "RP" ]]; then
# if removing, check if any version is installed and queue for removal via the custom module
if [[ "$md_mode" == "remove" ]]; then
if hasPackage "${pkg[2]}"; then
own_pkgs+=("${pkg[1]}")
all_pkgs+=("${pkg[2]}(custom)")
fi
else
# if installing check if our version is installed and queue for installing via the custom module
if hasPackage "${pkg[2]}" $(get_pkg_ver_${pkg[1]}) "ne"; then
own_pkgs+=("${pkg[1]}")
all_pkgs+=("${pkg[2]}(custom)")
fi
fi
continue
fi
if [[ "$md_mode" == "remove" ]]; then
# add package to apt_pkgs for removal if installed
if hasPackage "$pkg"; then
apt_pkgs+=("$pkg")
all_pkgs+=("$pkg")
fi
else
# add package to apt_pkgs for installation if not installed
if ! hasPackage "$pkg"; then
apt_pkgs+=("$pkg")
all_pkgs+=("$pkg")
fi
fi
done
# return if no packages required
[[ ${#apt_pkgs[@]} -eq 0 && ${#own_pkgs[@]} -eq 0 ]] && return
# if we are removing, then remove packages, do an autoremove to clean up additional packages and return
if [[ "$md_mode" == "remove" ]]; then
printMsgs "console" "Removing dependencies: ${all_pkgs[*]}"
for pkg in ${own_pkgs[@]}; do
rp_callModule "$pkg" remove
done
apt-get remove --purge -y "${apt_pkgs[@]}"
apt-get autoremove --purge -y
return 0
fi
printMsgs "console" "Did not find needed dependencies: ${all_pkgs[*]}. Trying to install them now."
# install any custom packages
for pkg in ${own_pkgs[@]}; do
rp_callModule "$pkg" _auto_
done
aptInstall --no-install-recommends "${apt_pkgs[@]}"
local failed=()
# 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 pkg in ${apt_pkgs[@]}; do
if ! hasPackage "$pkg"; 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 [[ "$pkg" == "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+=("$pkg")
fi
fi
done
if [[ ${#failed[@]} -gt 0 ]]; then
md_ret_errors+=("Could not install package(s): ${failed[*]}.")
return 1
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 needed=$2
local size=$((needed - __memory_avail))
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)
## @param depth depth parameter for git. (optional)
## @brief Git clones or pulls a repository.
## @details depth parameter will default to 1 (shallow clone) so long as __persistent_repos isn't set.
## A depth parameter of 0 will do a full clone with all history.
function gitPullOrClone() {
local dir="$1"
[[ -z "$dir" ]] && dir="$md_build"
local repo="$2"
local branch="$3"
local commit="$4"
local depth="$5"
# if repo is blank then use the rp_module_repo info
if [[ -z "$repo" && -n "$md_repo_url" ]]; then
repo="$(rp_resolveRepoParam "$md_repo_url")"
branch="$(rp_resolveRepoParam "$md_repo_branch")"
commit="$(rp_resolveRepoParam "$md_repo_commit")"
fi
[[ -z "$repo" ]] && return 1
[[ -z "$branch" ]] && branch="master"
# if no depth is provided default to shallow clone (depth 1)
[[ -z "$depth" ]] && depth=1
# if we are using persistent repos or checking out a specific commit, don't shallow clone
if [[ "$__persistent_repos" -eq 1 || -n "$commit" ]]; then
depth=0
fi
# record the source directory in __mod_info[ID/repo_dir] if not previously set which will be used
# by the packaging functions later to grab repository information
if [[ -z "${__mod_info[$md_id/repo_dir]}" ]]; then
__mod_info[$md_id/repo_dir]="$dir"
fi
if [[ -d "$dir/.git" ]]; then
pushd "$dir" > /dev/null
# if we are using persistent repos, fetch the latest remote changes and clean the source so
# any patches can be re-applied as needed.
if [[ "$__persistent_repos" -eq 1 ]]; then
runCmd git fetch
runCmd git reset --hard
runCmd git clean -f -d
fi
runCmd git checkout "$branch"
# only try to pull if we are on a tracking branch
if [[ -n "$(git config --get branch.$branch.merge)" ]]; then
runCmd git pull --ff-only
runCmd git submodule update --init --recursive
fi
popd > /dev/null
else
local git="git clone --recursive"
if [[ "$depth" -gt 0 ]]; then
git+=" --depth $depth --shallow-submodules"
fi
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
for helper in inifuncs.sh archivefuncs.sh; 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":"$__group" "$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":"$__group" "$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
if [[ ! -e "$romdir/genesis" ]]; then
pushd "$romdir"
ln -snf "$1" "genesis"
popd
fi
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":"$__group" "$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":"$__group" "$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":"$__group" "$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 setBackend()
## @param emulator.cfg key to configure backend for
## @param backend name of the backend to set
## @param force set to 1 to force the change
## @brief Set a backend rendering driver for a module
## @details Set a backend rendering driver for a module - can be currently default, dispmanx or x11.
## This function will only set a backend if
## - It's not already configured, or
## - The 3rd parameter (force) is set to 1
## The emulator.cfg key is usually the module_id but some modules add multiple emulator.cfg entries
## which are all handled separately. A module can use a _backend_set_MODULE function hook which is called
## from the backends module to handle calling setBackend for additional emulator.cfg entries.
## See "fuse" scriptmodule for an example.
function setBackend() {
local config="$configdir/all/backends.cfg"
local id="$1"
local mode="$2"
local force="$3"
iniConfig "=" "\"" "$config"
iniGet "$id"
if [[ "$force" -eq 1 || -z "$ini_value" ]]; then
iniSet "$id" "$mode"
chown "$__user":"$__group" "$config"
fi
}
## @fn getBackend()
## @param emulator.cfg key to get backend for
## @brief Get a backend rendering driver for a module
## @details Get a backend rendering driver for a module
## The function echos the result so the value can be captured using var=$(getBackend "$module_id")
function getBackend() {
local config="$configdir/all/backends.cfg"
local id="$1"
iniConfig " = " '"' "$config"
iniGet "$id"
if [[ -n "$ini_value" ]]; then
# translate old value of 1 as dispmanx for backward compatibility
[[ "$ini_value" == "1" ]] && ini_value="dispmanx"
else
ini_value="default"
fi
echo "$ini_value"
}
## @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. This function is deprecated.
## @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).
## This function is deprecated and instead setBackend should be used.
function setDispmanx() {
isPlatform "dispmanx" || return
setBackend "$1" "dispmanx"
}
## @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
## @brief Deprecated - use defaultRAConfig
## @details Creates a default retroarch.cfg for specified system in `$configdir/$system/retroarch.cfg`.
function ensureSystemretroconfig() {
# don't do any config work on module removal
[[ "$md_mode" == "remove" ]] && return