-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathcommon.bash
1863 lines (1587 loc) · 46.7 KB
/
common.bash
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
# common.bash
# This file contains aconfmgr's common code, used by all commands.
####################################################################################################
# Globals
PACMAN=${PACMAN:-pacman}
output_dir="$tmp_dir"/output
system_dir="$tmp_dir"/system # Current system configuration, to be compared against the output directory
# The directory used for building AUR packages.
# When running as root, our "$tmp_dir" will be inaccessible to
# the user under which the building is performed ("nobody"),
# so we need a separate directory under this circumstance.
if [[ $EUID == 0 ]]
then
aur_dir="$tmp_dir"-aur
else
aur_dir="$tmp_dir"/aur
fi
default_file_mode=644
ANSI_clear_line="[0K"
ANSI_color_R="[1;31m"
ANSI_color_G="[1;32m"
ANSI_color_Y="[1;33m"
ANSI_color_B="[1;34m"
ANSI_color_M="[1;35m"
ANSI_color_C="[1;36m"
ANSI_color_W="[1;39m"
ANSI_reset="[0m"
verbose=0
lint_config=false
umask $((666 - default_file_mode))
aconfmgr_action=
aconfmgr_action_args=()
####################################################################################################
# Defaults
# Initial ignore path list.
# Can be appended to using the IgnorePath helper.
ignore_paths=(
'/dev'
'/home'
'/media'
'/mnt'
'/proc'
'/root'
'/run'
'/sys'
'/tmp'
# '/var/.updated'
'/var/cache'
# '/var/lib'
# '/var/lock'
# '/var/log'
# '/var/spool'
)
# These files must be installed before anything else,
# because they affect or are required for what follows.
# shellcheck disable=SC2034
priority_files=(
/etc/passwd
/etc/group
/etc/pacman.conf
/etc/pacman.d/mirrorlist
/etc/makepkg.conf
)
# File content filters
# These are useful for files which contain some unpredictable element,
# such as a timestamp, which can't be considered as part of the system
# configuration, and can be safely omitted from the file.
# This is an associative array of patterns mapping to function
# names. The function is called with the file name as the only
# parameter, the file contents on its stdin, and is expected to
# provide the filtered contents on its stdout.
declare -A file_content_filters
# Some limits for common-sense warnings.
# Feel free to override these in your configuration.
warn_size_threshold=$((10*1024*1024)) # Warn on copying files bigger than this
warn_file_count_threshold=1000 # Warn on finding this many stray files
warn_tmp_df_threshold=$((1024*1024)) # Warn on error if free space in $tmp_dir is below this
makepkg_user=nobody # when running as root
####################################################################################################
function LogLeaveDirStats() {
local dir="$1"
Log 'Finalizing...\r'
LogLeave 'Done (%s native packages, %s foreign packages, %s files).\n' \
"$(Color G "$(wc -l < "$dir"/packages.txt)")" \
"$(Color G "$(wc -l < "$dir"/foreign-packages.txt)")" \
"$(Color G "$(find "$dir"/files -not -type d | wc -l)")"
}
skip_config=n
# Run user configuration scripts, to collect desired state into #output_dir
function AconfCompileOutput() {
LogEnter 'Compiling user configuration...\n'
if [[ $skip_config == y ]]
then
LogLeave 'Skipped.\n'
return
fi
# shellcheck disable=SC2174
mkdir --mode=700 --parents "$tmp_dir"
rm -rf "$output_dir"
mkdir --parents "$output_dir"
mkdir "$output_dir"/files
touch "$output_dir"/packages.txt
touch "$output_dir"/foreign-packages.txt
touch "$output_dir"/file-props.txt
touch "$output_dir"/warnings
# shellcheck disable=SC2174
mkdir --mode=700 --parents "$config_dir"
# Configuration
Log 'Using configuration in %s\n' "$(Color C "%q" "$config_dir")"
typeset -ag ignore_packages=()
typeset -ag ignore_foreign_packages=()
typeset -Ag used_files
local found=n
local file
for file in "$config_dir"/*.sh
do
if [[ -e "$file" ]]
then
LogEnter 'Sourcing %s...\n' "$(Color C "%q" "$file")"
# shellcheck source=/dev/null
source "$file"
found=y
LogLeave ''
fi
done
if $lint_config
then
# Check for unused files (files not referenced by the CopyFile
# helper).
# Only do this in the "check" action, as unused files do not
# necessarily indicate a bug in the configuration - they may
# simply be used under certain conditions.
if [[ -d "$config_dir"/files ]]
then
local line
find "$config_dir"/files -type f -print0 | \
while read -r -d $'\0' line
do
local key=${line#"$config_dir"/files}
if [[ -z "${used_files[$key]+x}" ]]
then
ConfigWarning 'Unused file: %s\n' \
"$(Color C "%q" "$line")"
fi
done
fi
fi
if [[ $found == y ]]
then
LogLeaveDirStats "$output_dir"
else
LogLeave 'Done (configuration not found).\n'
fi
}
skip_inspection=n
skip_checksums=n
# Given a list of paths to ignore (which can contain shell patterns),
# creates the list of arguments to give to 'find' to ignore them.
# The result is stored in the variable given by name as the first argument.
function AconfCreateFindIgnoreArgs() {
# A correct and simple implementation of this function would just give
# each argument as a parameter to find's -wholename, e.g. result in
# (-wholename path1 -o -wholename path2 -o ... -o -wholename pathn)
# However, this is painfully slow if the number of ignore patterns is large
# Instead, this function (ab)uses the fact that if the number of patterns
# given to GNU find is big, then as an implementation detail, using regular
# expressions (-regex option and similar) scales much better than using
# shell patterns (-wholename option and similar)
local ignore_args_varname=$1
local -n ignore_args_var=$ignore_args_varname
shift
local ignore_paths=("$@")
# Divide the ignore paths as simple (contain obviously literal ASCII
# characters or an asterisk wildcard) or complex (such as those using
# character ranges, question mark wildcards, international characters, etc.)
# Simple ignore paths are later going to be converted to regex,
# complex ignore paths are passed literally to find's -wholename
local simple_ignore_paths=()
local ignore_path
for ignore_path in "${ignore_paths[@]}"
do
# In this regular expression, we don't use ranges like "a-z", since this
# can match non-ASCII characters. Also, the hyphen is at the end of the
# regular expression to avoid it being interpreted as a range
if [[ "$ignore_path" =~ [^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/\ .*-] ]]
then
ignore_args_var+=(-wholename "$ignore_path" -o)
else
simple_ignore_paths+=("${ignore_path}")
fi
done
if [ ${#simple_ignore_paths[@]} -ne 0 ]
then
# Converting the simple ignore paths to regular expressions just needs to
# handle the asterisk wildcard, and escape a few characters
local ignore_regexps
echo -n "${simple_ignore_paths[*]}" | \
sed 's|[^*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/ ]|[&]|g; s|\*|.*|g' | \
mapfile -t ignore_regexps
ignore_args_var+=(-regex "$( IFS='|' ; echo "${ignore_regexps[*]}" )" -o)
fi
ignore_args_var+=(-false)
}
# Collect system state into $system_dir
function AconfCompileSystem() {
LogEnter 'Inspecting system state...\n'
if [[ $skip_inspection == y ]]
then
LogLeave 'Skipped.\n'
return
fi
# shellcheck disable=SC2174
mkdir --mode=700 --parents "$tmp_dir"
rm -rf "$system_dir"
mkdir --parents "$system_dir"
mkdir "$system_dir"/files
touch "$system_dir"/file-props.txt
touch "$system_dir"/orig-file-props.txt
### Packages
LogEnter 'Querying package list...\n'
( "$PACMAN" --query --quiet --explicit --native || true ) | sort | ( grep -vFxf <(PrintArray ignore_packages ) || true ) > "$system_dir"/packages.txt
( "$PACMAN" --query --quiet --explicit --foreign || true ) | sort | ( grep -vFxf <(PrintArray ignore_foreign_packages) || true ) > "$system_dir"/foreign-packages.txt
LogLeave
### Files
local -a found_files
found_files=()
# whether the contents is different from the original
local -A found_file_edited
found_file_edited=()
# Stray files
local -a ignore_args
AconfCreateFindIgnoreArgs ignore_args "${ignore_paths[@]}"
LogEnter 'Enumerating owned files...\n'
mkdir --parents "$tmp_dir"
( "$PACMAN" --query --list --quiet || true ) | sed 's#\/$##' | sort --unique > "$tmp_dir"/owned-files
LogLeave
LogEnter 'Searching for stray files...\n'
local line
local -Ag ignored_dirs
AconfNeedProgram gawk gawk n
# Progress display - only show file names once per second
local progress_fd
exec {progress_fd}> \
>( gawk '
BEGIN {
RS = "\0";
t = systime();
};
{
u = systime();
if (t != u) {
t = u;
printf "%s\0", $0;
system(""); # https://unix.stackexchange.com/a/83853/4830
}
}' | \
while read -r -d $'\0' line
do
local path=${line:1}
path=${path%/*} # Never show files, only directories
while [[ ${#path} -gt 40 ]]
do
path=${path%/*}
done
Log 'Scanning %s...\r' "$(Color M "%q" "$path")"
done
)
local stray_file_count=0
(
# NB: Regular expressions can be generated by AconfCreateFindIgnoreArgs
# The posix-extended regex type is used since it's easier to work
# with (e.g. no need to escape '|' alternations, parenthesis, etc.)
sudo find / \
-regextype posix-extended \
-not \
\( \
\( \
"${ignore_args[@]}" \
\) \
-printf 'I' -print0 -prune \
\) \
-printf 'O' -print0 \
| tee /dev/fd/$progress_fd \
| ( grep \
--null --null-data \
--invert-match \
--fixed-strings \
--line-regexp \
--file \
<( < "$tmp_dir"/owned-files \
sed -e 's#^#O#' \
) \
|| true ) \
) | \
while read -r -d $'\0' line
do
local file action
file=${line:1}
action=${line:0:1}
case "$action" in
O) # Stray file
#echo "ignore_paths+='$file' # "
if ((verbose))
then
Log '%s\r' "$(Color C "%q" "$file")"
fi
found_files+=("$file")
found_file_edited[$file]=y
stray_file_count=$((stray_file_count+1))
if [[ $stray_file_count -eq $warn_file_count_threshold ]]
then
LogEnter '%s: reached %s stray files while in directory %s.\n' \
"$(Color Y "Warning")" \
"$(Color G "$stray_file_count")" \
"$(Color C "%q" "$(dirname "$file")")"
LogLeave 'Perhaps add %s (or a parent directory) to configuration to ignore it.\n' \
"$(Color Y "IgnorePath %q" "$(dirname "$file")"/'*')"
warn_file_count_threshold=$((warn_file_count_threshold * 10))
fi
;;
I) # Ignored
# For convenience, we want to also ignore
# directories which contain only ignored files.
#
# This is so that a rule such as:
#
# IgnorePath '/foo/bar/baz/*.log'
#
# does not cause `aconfmgr save` to still emit lines like
#
# CreateDir /foo/bar
# CreateDir /foo/bar/baz
#
# However, we can't simply exclude parent dirs of
# excluded files from the file list, as then they
# will show up as missing in the diff against the
# compiled configuration. So, later we remove
# parent directories of any found un-ignored
# files.
local path="$file"
while [[ -n "$path" ]]
do
ignored_dirs[$path]=y
path=${path%/*}
done
;;
esac
done
LogLeave 'Done (%s stray files).\n' "$(Color G %s $stray_file_count)"
exec {progress_fd}<&-
LogEnter 'Cleaning up ignored files'\'' directories...\n'
local file
for file in "${found_files[@]}"
do
if [[ -z "${ignored_dirs[$file]+x}" ]]
then
local path="$file"
while [[ -n "$path" ]]
do
unset "ignored_dirs[\$path]"
path=${path%/*}
done
fi
done
LogLeave
# Modified files
LogEnter 'Searching for modified files...\n'
AconfNeedProgram paccheck pacutils n
AconfNeedProgram unbuffer expect n
local modified_file_count=0
local -A saw_file
# Tentative tracking of original file properties.
# The canonical version is read from orig-file-props.txt in AconfAnalyzeFiles
unset orig_file_props ; typeset -Ag orig_file_props
: > "$tmp_dir"/file-owners
local paccheck_opts=(unbuffer paccheck --files --file-properties --backup --noupgrade)
if [[ $skip_checksums == n ]]
then
paccheck_opts+=(--md5sum)
fi
sudo sh -c "LC_ALL=C stdbuf -o0 $(printf ' %q' "${paccheck_opts[@]}") 2>&1 || true" | \
while read -r line
do
if [[ $line =~ ^(.*):\ \'(.*)\'\ (type|size|modification\ time|md5sum|UID|GID|permission|symlink\ target)\ mismatch\ \(expected\ (.*)\)$ ]]
then
local package="${BASH_REMATCH[1]}"
local file="${BASH_REMATCH[2]}"
local kind="${BASH_REMATCH[3]}"
local value="${BASH_REMATCH[4]}"
local ignored=n
local ignore_path
for ignore_path in "${ignore_paths[@]}"
do
# shellcheck disable=SC2053
if [[ "$file" == $ignore_path ]]
then
ignored=y
break
fi
done
if [[ $ignored == n ]]
then
if [[ -z "${saw_file[$file]+x}" ]]
then
saw_file[$file]=y
Log '%s: %s\n' "$(Color M "%q" "$package")" "$(Color C "%q" "$file")"
found_files+=("$file")
modified_file_count=$((modified_file_count+1))
fi
local prop
case "$kind" in
UID)
prop=owner
value=${value#*/}
;;
GID)
prop=group
value=${value#*/}
;;
permission)
prop=mode
;;
type|size|modification\ time|md5sum|symlink\ target)
prop=
found_file_edited[$file]=y
;;
*)
prop=
;;
esac
if [[ -n "$prop" ]]
then
local key="$file:$prop"
orig_file_props[$key]=$value
printf '%s\t%s\t%q\n' "$prop" "$value" "$file" >> "$system_dir"/orig-file-props.txt
fi
fi
printf '%s\0%s\0' "$file" "$package" >> "$tmp_dir"/file-owners
elif [[ $line =~ ^(.*):\ \'(.*)\'\ missing\ file$ ]]
then
local package="${BASH_REMATCH[1]}"
local file="${BASH_REMATCH[2]}"
local ignored=n
local ignore_path
for ignore_path in "${ignore_paths[@]}"
do
# shellcheck disable=SC2053
if [[ "$file" == $ignore_path ]]
then
ignored=y
break
fi
done
if [[ $ignored == y ]]
then
continue
fi
Log '%s (missing)...\r' "$(Color M "%q" "$package")"
printf '%s\t%s\t%q\n' "deleted" "y" "$file" >> "$system_dir"/file-props.txt
printf '%s\0%s\0' "$file" "$package" >> "$tmp_dir"/file-owners
elif [[ $line =~ ^warning:\ (.*):\ \'(.*)\'\ read\ error\ \(No\ such\ file\ or\ directory\)$ ]]
then
local package="${BASH_REMATCH[1]}"
local file="${BASH_REMATCH[2]}"
# Ignore
elif [[ $line =~ ^(.*):\ all\ files\ match\ (database|mtree|mtree\ md5sums)$ ]]
then
local package="${BASH_REMATCH[1]}"
Log '%s...\r' "$(Color M "%q" "$package")"
#echo "Now at ${BASH_REMATCH[1]}"
else
Log 'Unknown paccheck output line: %s\n' "$(Color Y "%q" "$line")"
fi
done
LogLeave 'Done (%s modified files).\n' "$(Color G %s $modified_file_count)"
LogEnter 'Reading file attributes...\n'
typeset -a found_file_types found_file_sizes found_file_modes found_file_owners found_file_groups
if [[ ${#found_files[*]} == 0 ]]
then
Log 'No files found, skipping.\n'
else
Log 'Reading file types...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%F | mapfile -t found_file_types
Log 'Reading file sizes...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%s | mapfile -t found_file_sizes
Log 'Reading file modes...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%a | mapfile -t found_file_modes
Log 'Reading file owners...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%U | mapfile -t found_file_owners
Log 'Reading file groups...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%G | mapfile -t found_file_groups
fi
LogLeave # Reading file attributes
LogEnter 'Checking disk space...\n'
local -i i
local -i total_blocks=0
local -i tmp_block_size tmp_blocks_free
tmp_block_size=$(stat -f -c %S "$system_dir")
tmp_blocks_free=$(stat -f -c %f "$system_dir")
local tmp_fs_type
tmp_fs_type=$(stat -f -c %T "$system_dir")
if [[ "$tmp_fs_type" != "ramfs" ]]
then
for ((i=0; i<${#found_files[*]}; i++))
do
local -i size="${found_file_sizes[$i]}"
local -i blocks=$(((size+tmp_block_size-1)/tmp_block_size)) # Count blocks
total_blocks+=$blocks
if (( total_blocks >= tmp_blocks_free ))
then
local file="${found_files[$i]}"
Log 'Copying file %s (%s bytes / %s blocks) to temporary storage would exhaust free space on %s (%s bytes / %s blocks).\n' \
"$(Color C "%q" "$file")" "$(Color G "$size")" "$(Color G "$blocks")" \
"$(Color C "%q" "$system_dir")" "$(Color G "$((tmp_blocks_free * tmp_block_size))")" "$(Color G "$tmp_blocks_free")"
Log 'Perhaps add %s (or a parent directory) to configuration to ignore it, or run with %s pointing at another location.\n' \
"$(Color Y "IgnorePath %q" "$(dirname "$file")"/'*')" "$(Color Y "TMPDIR")"
FatalError 'Refusing to proceed.\n'
fi
done
fi
LogLeave
LogEnter 'Processing found files...\n'
for ((i=0; i<${#found_files[*]}; i++))
do
Log '%s/%s...\r' "$(Color G "$i")" "$(Color G "${#found_files[*]}")"
local file="${found_files[$i]}"
local type="${found_file_types[$i]}"
local size="${found_file_sizes[$i]}"
local mode="${found_file_modes[$i]}"
local owner="${found_file_owners[$i]}"
local group="${found_file_groups[$i]}"
if [[ "${ignored_dirs[$file]-n}" == y ]]
then
continue
fi
if [[ -n "${found_file_edited[$file]+x}" ]]
then
mkdir --parents "$(dirname "$system_dir"/files/"$file")"
if [[ "$type" == "symbolic link" ]]
then
ln -s -- "$(sudo readlink "$file")" "$system_dir"/files/"$file"
elif [[ "$type" == "regular file" || "$type" == "regular empty file" ]]
then
if [[ $size -gt $warn_size_threshold ]]
then
Log '%s: copying large file %s (%s bytes). Add %s to configuration to ignore.\n' "$(Color Y "Warning")" "$(Color C "%q" "$file")" "$(Color G "$size")" "$(Color Y "IgnorePath %q" "$file")"
fi
local filter_pattern filter_func
unset filter_func
for filter_pattern in "${!file_content_filters[@]}"
do
# shellcheck disable=SC2053
if [[ "$file" == $filter_pattern ]]
then
filter_func=${file_content_filters[$filter_pattern]}
fi
done
if [[ -v filter_func ]]
then
sudo cat "$file" | "$filter_func" "$file" > "$system_dir"/files/"$file"
else
# shellcheck disable=SC2024
sudo cat "$file" > "$system_dir"/files/"$file"
fi
elif [[ "$type" == "directory" ]]
then
mkdir --parents "$system_dir"/files/"$file"
else
Log '%s: Skipping file %s with unknown type %s. Add %s to configuration to ignore.\n' "$(Color Y "Warning")" "$(Color C "%q" "$file")" "$(Color G "$type")" "$(Color Y "IgnorePath %q" "$file")"
continue
fi
fi
{
local prop
for prop in mode owner group
do
# Ignore mode "changes" in symbolic links
# If a file's type changes, a change in mode can be reported too.
# But, symbolic links cannot have a mode, so ignore this change.
if [[ "$type" == "symbolic link" && "$prop" == mode ]]
then
continue
fi
local value
eval "value=\$$prop"
local default_value
if [[ $i -lt $stray_file_count ]]
then
# For stray files, the default owner/group is root/root,
# and the default mode depends on the type.
# Let AconfDefaultFileProp get the correct default value for us.
default_value=
else
# For owned files, we assume that the defaults are the
# files' current properties, unless paccheck said
# otherwise.
default_value=$value
fi
local orig_value
orig_value=$(AconfDefaultFileProp "$file" "$prop" "$type" "$default_value")
[[ "$value" == "$orig_value" ]] || printf '%s\t%s\t%q\n' "$prop" "$value" "$file"
done
} >> "$system_dir"/file-props.txt
done
LogLeave # Processing found files
LogLeaveDirStats "$system_dir" # Inspecting system state
}
####################################################################################################
typeset -A file_property_kind_exists
# Print to stdout the original/default value of the given file property.
# Uses orig_file_props entry if present.
function AconfDefaultFileProp() {
local file=$1 # Absolute path to the file
local prop=$2 # Name of the property (owner, group, or mode)
local type="${3:-}" # Type of the file, as identified by `stat --format=%F`
local default="${4:-}" # Default value, returned if we don't know the original file property.
local key="$file:$prop"
if [[ -n "${orig_file_props[$key]+x}" ]]
then
printf '%s' "${orig_file_props[$key]}"
return
fi
if [[ -n "$default" ]]
then
printf '%s' "$default"
return
fi
case "$prop" in
mode)
if [[ -z "$type" ]]
then
type=$(sudo env LC_ALL=C stat --format=%F "$file")
fi
if [[ "$type" == "symbolic link" ]]
then
FatalError 'Symbolic links do not have a mode\n' # Bug
elif [[ "$type" == "directory" ]]
then
printf 755
else
printf '%s' "$default_file_mode"
fi
;;
owner|group)
printf 'root'
;;
esac
}
# Read a file-props.txt file into an associative array.
function AconfReadFileProps() {
local filename="$1" # Path to file-props.txt to be read
local varname="$2" # Name of global associative array variable to read into
local line
while read -r line
do
if [[ $line =~ ^(.*)\ (.*)\ (.*)$ ]]
then
local kind="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
local file="${BASH_REMATCH[3]}"
file="$(eval "printf %s $file")" # Unescape
if [[ -z "$value" ]]
then
unset "${varname}[\$file:\$kind]"
else
eval "${varname}[\$file:\$kind]=\"\$value\""
fi
file_property_kind_exists[$kind]=y
fi
done < "$filename"
}
# Compare file properties.
function AconfCompareFileProps() {
LogEnter 'Comparing file properties...\n'
typeset -ag system_only_file_props=()
typeset -ag changed_file_props=()
typeset -ag config_only_file_props=()
local key
for key in "${!system_file_props[@]}"
do
if [[ -z "${output_file_props[$key]+x}" ]]
then
system_only_file_props+=("$key")
fi
done
for key in "${!system_file_props[@]}"
do
if [[ -n "${output_file_props[$key]+x}" && "${system_file_props[$key]}" != "${output_file_props[$key]}" ]]
then
changed_file_props+=("$key")
fi
done
for key in "${!output_file_props[@]}"
do
if [[ -z "${system_file_props[$key]+x}" ]]
then
config_only_file_props+=("$key")
fi
done
LogLeave
}
# Compare file information in $output_dir and $system_dir.
function AconfAnalyzeFiles() {
#
# Stray/modified files - diff
#
LogEnter 'Examining files...\n'
LogEnter 'Loading data...\n'
mkdir --parents "$tmp_dir"
( cd "$output_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/output-files
( cd "$system_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/system-files
LogLeave
Log 'Comparing file data...\n'
typeset -ag system_only_files=()
local file
( comm -13 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
while read -r -d $'\0' file
do
Log 'Only in system: %s\n' "$(Color C "%q" "$file")"
system_only_files+=("$file")
done
typeset -ag changed_files=()
AconfNeedProgram diff diffutils n
( comm -12 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
while read -r -d $'\0' file
do
local output_type system_type
output_type=$(LC_ALL=C stat --format=%F "$output_dir"/files/"$file")
system_type=$(LC_ALL=C stat --format=%F "$system_dir"/files/"$file")
if [[ "$output_type" != "$system_type" ]]
then
Log 'Changed type (%s / %s): %s\n' \
"$(Color Y "%q" "$output_type")" \
"$(Color Y "%q" "$system_type")" \
"$(Color C "%q" "$file")"
changed_files+=("$file")
continue
fi
if [[ "$output_type" == "directory" || "$system_type" == "directory" ]]
then
continue
fi
if ! diff --no-dereference --brief "$output_dir"/files/"$file" "$system_dir"/files/"$file" > /dev/null
then
Log 'Changed: %s\n' "$(Color C "%q" "$file")"
changed_files+=("$file")
fi
done
typeset -ag config_only_files=()
( comm -23 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
while read -r -d $'\0' file
do
Log 'Only in config: %s\n' "$(Color C "%q" "$file")"
config_only_files+=("$file")
done
LogLeave 'Done (%s only in system, %s changed, %s only in config).\n' \
"$(Color G "${#system_only_files[@]}")" \
"$(Color G "${#changed_files[@]}")" \
"$(Color G "${#config_only_files[@]}")"
#
# Modified file properties
#
LogEnter 'Examining file properties...\n'
LogEnter 'Loading data...\n'
unset orig_file_props # Also populated by AconfCompileSystem, so that it can be used by AconfDefaultFileProp
typeset -Ag output_file_props ; AconfReadFileProps "$output_dir"/file-props.txt output_file_props
typeset -Ag system_file_props ; AconfReadFileProps "$system_dir"/file-props.txt system_file_props
typeset -Ag orig_file_props ; AconfReadFileProps "$system_dir"/orig-file-props.txt orig_file_props
LogLeave
typeset -ag all_file_property_kinds
all_file_property_kinds=("${!file_property_kind_exists[@]}")
Print0Array all_file_property_kinds | sort --zero-terminated | mapfile -t -d $'\0' all_file_property_kinds
AconfCompareFileProps
LogLeave 'Done (%s only in system, %s changed, %s only in config).\n' \
"$(Color G "${#system_only_file_props[@]}")" \
"$(Color G "${#changed_file_props[@]}")" \
"$(Color G "${#config_only_file_props[@]}")"
}
# The *_packages arrays are passed by name,
# so ShellCheck thinks the variables are unused:
# shellcheck disable=2034
# Prepare configuration and system state
function AconfCompile() {
LogEnter 'Collecting data...\n'
# Configuration
AconfCompileOutput
# System
AconfCompileSystem
# Vars
< "$output_dir"/packages.txt sort --unique | mapfile -t packages
< "$system_dir"/packages.txt sort --unique | mapfile -t installed_packages
< "$output_dir"/foreign-packages.txt sort --unique | mapfile -t foreign_packages
< "$system_dir"/foreign-packages.txt sort --unique | mapfile -t installed_foreign_packages
AconfAnalyzeFiles
LogLeave # Collecting data
}
####################################################################################################
pacman_opts=("$PACMAN")
aurman_opts=(aurman)
pacaur_opts=(pacaur)
yaourt_opts=(yaourt)
yay_opts=(yay)
paru_opts=(paru)
makepkg_opts=(makepkg)
diff_opts=(diff '--color=auto')
aur_helper=
aur_helpers=(aurman pacaur yaourt yay paru makepkg)
# Only aconfmgr can use makepkg under root
if [[ $EUID == 0 ]]
then
aur_helper=makepkg
fi
function DetectAurHelper() {
if [[ -n "$aur_helper" ]]
then
return
fi
LogEnter 'Detecting AUR helper...\n'
local helper
for helper in "${aur_helpers[@]}"
do
if hash "$helper" 2> /dev/null
then
aur_helper=$helper
LogLeave '%s... Yes\n' "$(Color C %s "$helper")"
return
fi
Log '%s... No\n' "$(Color C %s "$helper")"
done
Log 'Can'\''t find even makepkg!?\n'
Exit 1
}
base_devel_installed=n
function AconfMakePkg() {
local install=true
if [[ "$1" == --noinstall ]]
then
install=false
shift
fi
local package="$1"
local asdeps="${2:-false}"