This repository was archived by the owner on Apr 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdsm.dev
More file actions
executable file
·932 lines (859 loc) · 31 KB
/
dsm.dev
File metadata and controls
executable file
·932 lines (859 loc) · 31 KB
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
#!/bin/bash
# -----------------------------------------------------------------------------
# Safe directory sync/copy helper — PREVIEW + COMMENTS (least-privilege)
#
# What this script does
# • Interactively asks for source and destination directories
# • Lets you choose a backend: (cp + rm), rsync, or rclone
# • Shows a PREVIEW before copying: how many files, total size, and an
# optional per-file list
# • Backs up current destination to /tmp before changing anything
# • Performs safety checks (same path, '/', nesting, sensitive dirs)
# • Avoids persistent sudo; elevates only when strictly needed (mkdir/rm,
# optional package installs). The copy itself runs unprivileged.
#
# Preview logic
# • cp: destination is cleaned before copy → preview = ALL source files
# • rsync/rclone: preview = files where size OR mtime differs between src/dst
#
# Notes
# • Indentation uses 4 spaces
# • Requires Bash features: [[ ... ]], declare -g, extglob, etc.
# • Config file (auto-created if missing):
# ${XDG_CONFIG_HOME:-$HOME/.config}/dsm/config
# Legacy fallback is read-only if present: ~/.dsm/config
# Keys: tool, log, skip, dry_run, no_sudo, src, dst, rsync_opts, rclone_opts, cp_opts
# -----------------------------------------------------------------------------
# Fail fast on errors, undefined vars, and pipeline errors
set -Eeuo pipefail
# Restrict word splitting to newlines/tabs only
IFS=$'\n\t'
# Enable bash extended globs (used for trimming and hidden-file patterns)
shopt -s extglob
# ------------------------------- CLI args (help & stubs) -------------------------------
# NOTE: -h/--help, --version, --dry-run, -t/--tool, -s/--src, -d/--dst,
# --config, --log, and --skip are functional. Others remain stubs.
SCRIPT_NAME="${0##*/}"
VERSION="1.0.0"
DRY_RUN=0
TOOL_CHOICE=""
CLI_SRC=""
CLI_DST=""
CLI_LOG=""
CLI_SKIP=""
CONFIG_FILE=""
declare -a ARGS_UNIMPL=()
# Effective configuration (populated from config + CLI)
LOG_FILE=""
SKIP_PREVIEW=0
SKIP_BACKUP=0
SKIP_SAFETY=0
DISALLOW_SUDO=0
NO_CONFIRM=0
COPY_MODE=0
CFG_TOOL=""
CFG_DRY_RUN=""
CFG_SRC=""
CFG_DST=""
RSYNC_OPTS_EXTRA=""
RCLONE_OPTS_EXTRA=""
CP_OPTS_EXTRA=""
print_help(){
cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS]
Safe directory sync/copy helper — PREVIEW + COMMENTS (least-privilege)
Options:
-h, --help Show this help and exit.
--version Print version and exit.
--dry-run No-change mode (also usable via config: dry_run=true).
-t, --tool TOOL Preselect backend: cp | rsync | rclone.
-s, --src DIR Source directory path (non-interactive).
-d, --dst DIR Destination directory path (non-interactive).
--config FILE Load configuration from FILE. If FILE does not exist, it
will be created automatically with sane defaults.
Default location (auto-created on first run):
${XDG_CONFIG_HOME:-$HOME/.config}/dsm/config
(legacy fallback is read-only: ~/.dsm/config)
--log FILE Append actions to FILE (overrides config 'log=...').
--skip STEPS Comma list of steps to skip: preview,backup,safety
(merges with config 'skip=...').
--no-sudo Never attempt privilege escalation (sudo/doas).
Overrides config 'no_sudo=...' for this run.
--no-backup Skip creating a temporary backup of the destination
before syncing (same as '--skip backup' for this run).
--no-confirm Do not ask any interactive questions; automatically use
each prompt's default answer.
--copy Non-destructive copy mode: do NOT delete extra files in
destination. For cp: do not clean destination first and
update in place; for rsync: no '--delete'; for rclone:
use 'rclone copy'.
Additional (stubs):
--copy (N/A) [none — implemented]
--no-confirm (N/A) [none — implemented]
Config file (key=value), example:
tool=rsync
log=~/dsm.log
skip=preview,backup
dry_run=false
no_sudo=false
src=~/src/project
dst=/mnt/backup/project
rsync_opts=--partial --mkpath
rclone_opts=--transfers 8
cp_opts=
Notes:
• CLI overrides config; skip lists are merged (union).
EOF
}
print_version(){
echo "$SCRIPT_NAME $VERSION"
}
# --------------- Config loading (key=value, '#' comments, '~' expand) ---------------
expand_tilde(){
local p="${1-}"
[[ -z "$p" ]] && { printf '%s\n' ""; return 0; }
if [[ "$p" == "~" || "$p" == "~/"* ]]; then
printf '%s\n' "${p/#\~/$HOME}"
else
printf '%s\n' "$p"
fi
}
trim(){
local s="${1-}"
s="${s##*( )}"; s="${s%%*( )}"
printf '%s' "$s"
}
# Create a default config file with secure permissions if it does not exist
ensure_default_config(){
local target="$1"
local parent; parent="$(dirname -- "$target")"
mkdir -p -- "$parent" 2>/dev/null || true
if [[ -e "$target" ]]; then
return 0
fi
local now; now="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
local state_base="${XDG_STATE_HOME:-$HOME/.local/state}"
local default_log="$state_base/dsm/dsm.log"
umask 077
{
echo "# dsm configuration (auto-created)"
echo "# File: $target"
echo "# Created: $now"
echo "# Format: key=value (lines starting with '#' are comments)"
echo "# Keys:"
echo "# tool = cp | rsync | rclone"
echo "# log = /path/to/logfile"
echo "# skip = comma list: preview,backup,safety"
echo "# dry_run = true | false"
echo "# no_sudo = true | false"
echo "# src = /path/to/source"
echo "# dst = /path/to/destination"
echo "# rsync_opts = extra rsync options"
echo "# rclone_opts = extra rclone options"
echo "# cp_opts = extra cp options"
echo
echo "tool=cp"
echo "log=$default_log"
echo "skip="
echo "dry_run=false"
echo "no_sudo=false"
echo "src="
echo "dst="
echo "rsync_opts="
echo "rclone_opts="
echo "cp_opts="
} > "$target" 2>/dev/null || {
echo "Warning: cannot create config at $target (permission denied?)." >&2
return 1
}
chmod 600 "$target" 2>/dev/null || true
}
load_config_file(){
local f="$1"
[[ -z "$f" ]] && return 0
[[ -f "$f" ]] || return 0
while IFS= read -r line || [[ -n "${line-}" ]]; do
line="${line%%#*}"
line="$(trim "$line")"
[[ -z "$line" ]] && continue
local key="${line%%=*}"
local val="${line#*=}"
key="$(trim "${key,,}")"
val="$(trim "$val")"
case "$key" in
tool) CFG_TOOL="${val,,}" ;;
log) LOG_FILE="$(expand_tilde "$val")" ;;
skip) parse_skip_list "$val" ;;
dry_run) [[ "${val,,}" == "true" || "$val" == "1" ]] && CFG_DRY_RUN=1 || CFG_DRY_RUN=0 ;;
no_sudo) [[ "${val,,}" == "true" || "$val" == "1" ]] && DISALLOW_SUDO=1 || DISALLOW_SUDO=0 ;;
src) CFG_SRC="$(expand_tilde "$val")" ;;
dst) CFG_DST="$(expand_tilde "$val")" ;;
rsync_opts) RSYNC_OPTS_EXTRA="$val" ;;
rclone_opts) RCLONE_OPTS_EXTRA="$val" ;;
cp_opts) CP_OPTS_EXTRA="$val" ;;
*) : ;;
esac
done < "$f"
}
# Merge skips from a comma list into flags
parse_skip_list(){
local list="${1-}"
[[ -z "$list" ]] && return 0
local IFS=,
for p in $list; do
p="$(trim "${p,,}")"
case "$p" in
preview) SKIP_PREVIEW=1 ;;
backup) SKIP_BACKUP=1 ;;
safety) SKIP_SAFETY=1 ;;
*) : ;;
esac
done
}
# ---------------------------- Two-phase arg handling ----------------------------
# Pre-scan for --config to set CONFIG_FILE (also auto-create if missing)
prescan_for_config(){
local i=1
while (( i <= $# )); do
eval "arg=\${$i-}"
if [[ "$arg" == "--config" ]]; then
local j=$((i+1))
eval "val=\${$j-}"
if [[ -z "${val-}" || "$val" == -* ]]; then
echo "Missing value for --config" >&2
exit 2
fi
CONFIG_FILE="$val"
# Auto-create custom config path if missing
ensure_default_config "$CONFIG_FILE" || true
return 0
fi
i=$((i+1))
done
}
parse_args(){
while (( $# )); do
case "$1" in
-h|--help)
print_help
exit 0
;;
--version)
print_version
exit 0
;;
--dry-run)
DRY_RUN=1
;;
-t|--tool)
if [[ -z "${2:-}" || "${2:-}" == -* ]]; then
echo "Missing value for --tool" >&2
exit 2
fi
TOOL_CHOICE="${2,,}"
case "$TOOL_CHOICE" in
cp|rsync|rclone) : ;;
*) echo "Unknown tool: $TOOL_CHOICE (expected: cp|rsync|rclone)" >&2; exit 2 ;;
esac
shift
;;
-s|--src)
if [[ -z "${2:-}" || "${2:-}" == -* ]]; then
echo "Missing value for --src" >&2
exit 2
fi
CLI_SRC="$(expand_tilde "$2")"
shift
;;
-d|--dst)
if [[ -z "${2:-}" || "${2:-}" == -* ]]; then
echo "Missing value for --dst" >&2
exit 2
fi
CLI_DST="$(expand_tilde "$2")"
shift
;;
--config)
if [[ -z "${2:-}" || "${2:-}" == -* ]]; then
echo "Missing value for --config" >&2
exit 2
fi
CONFIG_FILE="$2"
# If user supplies a path and it doesn't exist, create it now
ensure_default_config "$CONFIG_FILE" || true
shift
;;
--log)
if [[ -z "${2:-}" || "${2:-}" == -* ]]; then
echo "Missing value for --log" >&2
exit 2
fi
CLI_LOG="$(expand_tilde "$2")"
shift
;;
--skip)
if [[ -z "${2:-}" || "${2:-}" == -* ]]; then
echo "Missing value for --skip" >&2
exit 2
fi
CLI_SKIP="$2"
shift
;;
--no-sudo)
DISALLOW_SUDO=1
;;
--no-backup)
SKIP_BACKUP=1
;;
--no-confirm)
NO_CONFIRM=1
;;
--copy)
COPY_MODE=1
;;
--copy=*|--no-confirm=*|--no-sudo=*|--no-backup=*|--log=*|--skip=*|--config=*|-t=*|-s=*|-d=*)
echo "Use space-separated form (e.g., --log FILE), '=' form not supported." >&2
exit 2
;;
--*)
ARGS_UNIMPL+=("$1")
if [[ -n "${2:-}" && "${2:-}" != -* ]]; then ARGS_UNIMPL+=("$2"); shift; fi
;;
*)
ARGS_UNIMPL+=("$1")
;;
esac
shift || true
done
}
# --------------------------- Error/Signal handlers ---------------------------
on_err(){
echo
echo "Error (line $LINENO): $BASH_COMMAND" >&2
logmsg "ERROR line=$LINENO cmd=$(printf '%q' "$BASH_COMMAND")"
}
on_int(){
echo
echo "Aborted by user."
logmsg "ABORT_BY_USER"
exit 130
}
trap on_err ERR
trap on_int INT TERM
# ------------------------------- Logging ---------------------------------
logmsg(){
[[ -z "${LOG_FILE:-}" ]] && return 0
local ts; ts="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
printf '%s %s\n' "$ts" "$*" >> "$LOG_FILE" || true
}
init_log(){
[[ -z "${LOG_FILE:-}" ]] && return 0
local dir; dir="$(dirname -- "$LOG_FILE")"
mkdir -p -- "$dir" 2>/dev/null || true
if ! touch -- "$LOG_FILE" 2>/dev/null; then
echo "Warning: cannot write to log file: $LOG_FILE" >&2
LOG_FILE=""
fi
}
# ------------------------------- Privileges ---------------------------------
SUDO=""
setup_sudo(){
# Honor 'no-sudo' from config or CLI: never set a sudo/doas helper
if (( DISALLOW_SUDO )); then
SUDO=""
return 0
fi
# If already root, no helper is needed
if [[ $EUID -eq 0 ]]; then
SUDO=""
return 0
fi
# Prefer sudo, then doas; otherwise leave empty to avoid elevation
if command -v sudo >/dev/null 2>&1; then
SUDO="sudo"; return 0
fi
if command -v doas >/dev/null 2>&1; then
SUDO="doas"; return 0
fi
SUDO="" # no helper available; privileged ops will fail with a message
}
# mkdir_safe <path>
mkdir_safe(){
local target="$1" parent
parent=$(dirname -- "$target")
if [[ -w "$parent" ]]; then
mkdir -p -- "$target"
else
if [[ -n "$SUDO" ]]; then
$SUDO mkdir -p -- "$target"
else
echo "Cannot create '$target' (no permission and no sudo/doas)." >&2
exit 1
fi
fi
}
# rm_tree_contents_safe <dir>
rm_tree_contents_safe(){
local dir="$1"
(
shopt -s dotglob nullglob
if [[ -w "$dir" ]]; then
rm -rf -- "$dir"/{*,.[!.]*,..?*} || true
else
if [[ -n "$SUDO" ]]; then
$SUDO rm -rf -- "$dir"/{*,.[!.]*,..?*} || true
else
echo "Cannot clean '$dir' (no permission and no sudo/doas)." >&2
exit 1
fi
fi
)
}
# ---------------------------- Package management ----------------------------
PKG_MGR=""; PKG_UPDATE=""; PKG_INSTALL=""; PKG_UPDATED=0
detect_pkg_manager(){
if command -v apt-get >/dev/null 2>&1; then
PKG_MGR="apt"
PKG_UPDATE="${SUDO:+$SUDO }apt-get update -qq"
PKG_INSTALL="${SUDO:+$SUDO }env DEBIAN_FRONTEND=noninteractive apt-get install -y"
elif command -v apt >/dev/null 2>&1; then
PKG_MGR="apt"
PKG_UPDATE="${SUDO:+$SUDO }apt update -qq"
PKG_INSTALL="${SUDO:+$SUDO }env DEBIAN_FRONTEND=noninteractive apt install -y"
elif command -v dnf >/dev/null 2>&1; then
PKG_MGR="dnf"
PKG_UPDATE="${SUDO:+$SUDO }dnf -y makecache"
PKG_INSTALL="${SUDO:+$SUDO }dnf -y install"
elif command -v yum >/dev/null 2>&1; then
PKG_MGR="yum"
PKG_UPDATE="${SUDO:+$SUDO }yum -y makecache"
PKG_INSTALL="${SUDO:+$SUDO }yum -y install"
elif command -v zypper >/dev/null 2>&1; then
PKG_MGR="zypper"
PKG_UPDATE="${SUDO:+$SUDO }zypper --non-interactive refresh"
PKG_INSTALL="${SUDO:+$SUDO }zypper --non-interactive install --no-confirm"
elif command -v pacman >/dev/null 2>&1; then
PKG_MGR="pacman"
PKG_UPDATE="${SUDO:+$SUDO }pacman -Sy --noconfirm"
PKG_INSTALL="${SUDO:+$SUDO }pacman -S --noconfirm --needed"
elif command -v apk >/dev/null 2>&1; then
PKG_MGR="apk"
PKG_UPDATE=":" # Alpine: refresh during install with --no-cache
PKG_INSTALL="${SUDO:+$SUDO }apk add --no-cache"
elif command -v brew >/dev/null 2>&1; then
PKG_MGR="brew"
PKG_UPDATE="brew update"
PKG_INSTALL="brew install"
fi
}
pkg_update_once(){
[[ -z "$PKG_UPDATE" ]] && return 0
if (( PKG_UPDATED == 0 )); then
if (( DRY_RUN )); then
echo "DRY-RUN: skipping package metadata update."
PKG_UPDATED=1
return 0
fi
if yesno "Update package lists now? (Y/n): " Y; then
eval "$PKG_UPDATE"
fi
PKG_UPDATED=1
fi
}
ensure_installed(){
if (( DRY_RUN )); then
echo "DRY-RUN: would install: $*"
return 0
fi
if [[ -z "$PKG_INSTALL" ]]; then
echo "Cannot install packages automatically (no pkg manager or no sudo/doas)." >&2
return 1
fi
pkg_update_once
# shellcheck disable=SC2086
eval "$PKG_INSTALL" $*
}
# ------------------------------- UI helpers ---------------------------------
yesno(){
local message="$1" default="$2" answer
# Non-interactive mode: auto-answer using the provided default
if (( NO_CONFIRM )); then
if [[ "${default^^}" == "Y" ]]; then
logmsg "AUTOANSWER yes msg=$(printf '%q' "$message")"
return 0
else
logmsg "AUTOANSWER no msg=$(printf '%q' "$message")"
return 1
fi
fi
while true; do
read -rp "$message" answer || true
[[ -z "${answer:-}" ]] && answer="$default"
answer="${answer##*( )}"; answer="${answer%%*( )}"; answer="${answer,,}"
case "$answer" in
y|yes) return 0 ;;
n|no) return 1 ;;
q|quit|exit) echo "Exiting..."; exit 0 ;;
*) echo "Choose Y or N" ;;
esac
done
}
path_abs(){
local p="$1"
if [[ "$p" == /* ]]; then
printf '%s\n' "$p"
else
printf '%s\n' "$PWD/$p"
fi
}
choose_dir(){
local message="$1" type="$2" create="${3-}" answer resolved
while true; do
read -rp "Enter $message: " answer || true
if [[ -d "${answer:-}" ]]; then
resolved=$(readlink -f -- "$answer"); declare -g "absolute_${type}=$resolved"; return 0
fi
if [[ -n "$create" ]]; then
if (( DRY_RUN )); then
echo "DRY-RUN: directory does not exist and will not be created: $answer"
resolved=$(path_abs "$answer"); declare -g "absolute_${type}=$resolved"
echo "Using intended path for preview: $resolved"
return 0
fi
if yesno "This directory doesn't exist... Create it? (Y/n): " Y; then
mkdir_safe "$answer"
resolved=$(readlink -f -- "$answer"); declare -g "absolute_${type}=$resolved"
echo "Directory created successfully."; return 0
fi
else
echo "This directory doesn't exist... Input a correct path"; echo
fi
done
}
# ------------------------------ Preview helpers -----------------------------
stat_bytes(){ stat -c %s -- "$1" 2>/dev/null || stat -f %z -- "$1"; }
stat_mtime(){ stat -c %Y -- "$1" 2>/dev/null || stat -f %m -- "$1"; }
build_src_list(){
( cd "$absolute_src" && find . -type f -printf '%s\t%P\n' )
}
build_delta_list_generic(){
( cd "$absolute_src" && find . -type f -print0 ) |
while IFS= read -r -d '' rel; do
rel="${rel#./}"
src_f="$absolute_src/$rel"
dst_f="$absolute_dst/$rel"
ssz="$(stat_bytes "$src_f" 2>/dev/null || echo 0)"
if [[ ! -f "$dst_f" ]]; then
printf '%s\t%s\n' "$ssz" "$rel"
else
dsz="$(stat_bytes "$dst_f" 2>/dev/null || echo -1)"
smt="$(stat_mtime "$src_f" 2>/dev/null || echo 0)"
dmt="$(stat_mtime "$dst_f" 2>/dev/null || echo 0)"
if [[ "$ssz" != "$dsz" || "$smt" -ne "$dmt" ]]; then
printf '%s\t%s\n' "$ssz" "$rel"
fi
fi
done
}
hr_bytes(){
local b=$1 d=0 s=(B KB MB GB TB PB EB ZB YB)
while (( b >= 1024 && d < ${#s[@]}-1 )); do b=$(( b/1024 )); d=$(( d+1 )); done
echo "$b ${s[$d]}"
}
preview_print_summary(){
local src_tmp="$1" delta_tmp="$2" title="$3" src_count src_size delta_count delta_size
src_count=$(wc -l < "$src_tmp" | tr -d ' ')
src_size=$(awk -F '\t' '{s+=$1} END{print s+0}' "$src_tmp")
delta_count=$(wc -l < "$delta_tmp" | tr -d ' ')
delta_size=$(awk -F '\t' '{s+=$1} END{print s+0}' "$delta_tmp")
echo
echo "Preview — $title"
echo "Source files: $src_count"
echo "Source size: $(hr_bytes "$src_size") ($src_size bytes)"
echo "Will transfer: $delta_count"
echo "Transfer size: $(hr_bytes "$delta_size") ($delta_size bytes)"
if (( delta_count > 0 )); then
if yesno "Show list of files to transfer? (y/N): " N; then
if command -v less >/dev/null 2>&1 && [[ -t 1 ]]; then
cut -f2- "$delta_tmp" | less -R
else
cut -f2- "$delta_tmp"
fi
fi
fi
logmsg "PREVIEW src_files=$src_count src_bytes=$src_size delta_files=$delta_count delta_bytes=$delta_size title='$title'"
}
run_preview(){
local force_preview=0
(( DRY_RUN )) && force_preview=1
if (( SKIP_PREVIEW )); then
logmsg "PREVIEW skipped"
return 0
fi
if (( ! force_preview )); then
if ! yesno "Preview copy plan first? (Y/n): " Y; then
return 0
fi
fi
local src_tmp delta_tmp title
src_tmp=$(mktemp)
delta_tmp=$(mktemp)
build_src_list > "$src_tmp"
case "$SELECTED_TOOL" in
cp)
if (( COPY_MODE )); then
build_delta_list_generic > "$delta_tmp"; title="delta (size+mtime, copy mode)"
else
build_src_list > "$delta_tmp"; title="full copy from source"
fi
;;
*)
build_delta_list_generic > "$delta_tmp"; title="delta (size+mtime)"
;;
esac
preview_print_summary "$src_tmp" "$delta_tmp" "$title"
rm -f "$src_tmp" "$delta_tmp"
if (( DRY_RUN )); then
return 0
fi
yesno "Proceed with copy? (Y/n): " Y || { echo "Aborted before copy."; logmsg "PROCEED declined"; exit 0; }
}
# ------------------------------ Tool selection ------------------------------
SELECTED_TOOL=""
cp_tool(){
if command -v cp >/dev/null 2>&1 && command -v rm >/dev/null 2>&1; then
SELECTED_TOOL="cp"; echo "Selected: Standard (rm+cp)"; return 0
fi
echo "cp or rm not found."
if (( DRY_RUN )); then
echo "DRY-RUN: would install coreutils."
SELECTED_TOOL="cp"; echo "Selected: Standard (rm+cp)"; return 0
fi
if yesno "Install coreutils now? (Y/n): " Y; then
ensure_installed coreutils || return 1
SELECTED_TOOL="cp"; echo "Selected: Standard (rm+cp)"; return 0
fi
echo "Not installing; choose another tool."; return 1
}
rsync_tool(){
if ! command -v rsync >/dev/null 2>&1; then
if (( DRY_RUN )); then
echo "DRY-RUN: would install rsync."
SELECTED_TOOL="rsync"; echo "Selected: rsync"; return 0
fi
if yesno "rsync is not installed. Install it now? (Y/n): " Y; then
ensure_installed rsync || return 1
else
echo "Not installing; choose another tool."; return 1
fi
fi
SELECTED_TOOL="rsync"; echo "Selected: rsync"; return 0
}
rclone_tool(){
if ! command -v rclone >/dev/null 2>&1; then
if (( DRY_RUN )); then
echo "DRY-RUN: would install rclone."
SELECTED_TOOL="rclone"; echo "Selected: rclone"; return 0
fi
if yesno "rclone is not installed. Install it now? (Y/n): " Y; then
ensure_installed rclone || return 1
else
echo "Not installing; choose another tool."; return 1
fi
fi
SELECTED_TOOL="rclone"; echo "Selected: rclone"; return 0
}
select_tool_by_name(){
case "${1,,}" in
cp) cp_tool ;;
rsync) rsync_tool ;;
rclone) rclone_tool ;;
*) echo "Unknown tool: $1 (expected: cp|rsync|rclone)" >&2; return 2 ;;
esac
}
choose_tool(){
local default="$1" choice
while true; do
echo "Choose copy tool:"; echo "1) Standard (cp + rm)"; echo "2) rsync"; echo "3) rclone"
read -rp "Select: " choice || true
[[ -z "${choice:-}" ]] && choice=$default
choice="${choice##*( )}"; choice="${choice%%*( )}"
case "$choice" in
1) cp_tool && return 0 ;;
2) rsync_tool && return 0 ;;
3) rclone_tool && return 0 ;;
*) echo "-----------"; echo "Enter number from 1 to 3"; echo ;;
esac
done
}
# ------------------------------- Main routine -------------------------------
main(){
# 0) Pre-scan for explicit --config; create if missing
prescan_for_config "$@"
# 0.1) Decide effective default config path; auto-create if neither exists
if [[ -z "${CONFIG_FILE:-}" ]]; then
local base="${XDG_CONFIG_HOME:-$HOME/.config}"
local xdg_cfg="$base/dsm/config"
local legacy_cfg="$HOME/.dsm/config"
if [[ -f "$legacy_cfg" ]]; then
CONFIG_FILE="$legacy_cfg"
else
CONFIG_FILE="$xdg_cfg"
ensure_default_config "$CONFIG_FILE" || true
fi
fi
# 1) Load config (it exists now or we proceed without if creation failed)
load_config_file "$CONFIG_FILE"
# 2) Parse CLI (overrides config)
parse_args "$@"
# 3) Apply config-derived defaults unless overridden by CLI
[[ -n "${CLI_LOG:-}" ]] && LOG_FILE="$CLI_LOG"
[[ -n "${CLI_SKIP:-}" ]] && parse_skip_list "$CLI_SKIP"
if (( DRY_RUN == 0 )) && [[ "${CFG_DRY_RUN:-}" == "1" ]]; then DRY_RUN=1; fi
if [[ -z "${TOOL_CHOICE:-}" && -n "${CFG_TOOL:-}" ]]; then TOOL_CHOICE="$CFG_TOOL"; fi
# 4) Initialize logging and privileges
init_log
logmsg "START version=$VERSION config='${CONFIG_FILE:-none}' dry_run=$DRY_RUN skip_preview=$SKIP_PREVIEW skip_backup=$SKIP_BACKUP skip_safety=$SKIP_SAFETY no_sudo=$DISALLOW_SUDO no_confirm=$NO_CONFIRM copy_mode=$COPY_MODE"
setup_sudo
detect_pkg_manager
# 5) Source/destination selection (CLI > config > interactive)
if [[ -n "$CLI_SRC" ]]; then
if [[ -d "$CLI_SRC" ]]; then
absolute_src=$(readlink -f -- "$CLI_SRC")
else
echo "Source directory does not exist: $CLI_SRC" >&2
exit 2
fi
elif [[ -n "$CFG_SRC" ]]; then
if [[ -d "$CFG_SRC" ]]; then
absolute_src=$(readlink -f -- "$CFG_SRC")
else
echo "Source directory (from config) does not exist: $CFG_SRC" >&2
exit 2
fi
else
choose_dir "source directory" src
fi
if [[ -n "$CLI_DST" ]]; then
if [[ -d "$CLI_DST" ]]; then
absolute_dst=$(readlink -f -- "$CLI_DST")
else
if (( DRY_RUN )); then
echo "DRY-RUN: directory does not exist and will not be created: $CLI_DST"
absolute_dst=$(path_abs "$CLI_DST")
echo "Using intended path for preview: $absolute_dst"
else
mkdir_safe "$CLI_DST"
absolute_dst=$(readlink -f -- "$CLI_DST")
echo "Destination directory created: $absolute_dst"
fi
fi
elif [[ -n "$CFG_DST" ]]; then
if [[ -d "$CFG_DST" ]]; then
absolute_dst=$(readlink -f -- "$CFG_DST")
else
if (( DRY_RUN )); then
echo "DRY-RUN: directory does not exist and will not be created: $CFG_DST"
absolute_dst=$(path_abs "$CFG_DST")
echo "Using intended path for preview: $absolute_dst"
else
mkdir_safe "$CFG_DST"
absolute_dst=$(readlink -f -- "$CFG_DST")
echo "Destination directory created: $absolute_dst"
fi
fi
else
choose_dir "destination directory" dst create
fi
logmsg "PATHS src='$absolute_src' dst='$absolute_dst'"
echo
# 6) Safety checks (unless skipped)
if (( ! SKIP_SAFETY )); then
if [[ "$absolute_src" == "$absolute_dst" ]]; then
echo "Source and destination are the same. Aborting..." >&2; echo; exit 1
fi
if [[ "$absolute_dst" == "/" ]]; then
echo "Destination path is '/'. Aborting..." >&2; echo; exit 1
fi
if [[ "$absolute_src/" == "$absolute_dst"/* || "$absolute_dst/" == "$absolute_src"/* ]]; then
echo "Source and destination are nested. Aborting." >&2; echo; exit 1
fi
if [[ "$absolute_dst" =~ ^/(etc|home|var|bin|usr|lib|opt|tmp|srv|dev|mnt|media|proc|run|sys)(/)?$ ]]; then
echo "Destination is a sensitive directory: $absolute_dst"
yesno "Do you want to continue? (y/N): " N || { echo "Aborted..."; exit 1; }
yesno "Are you absolutely sure? (y/N): " N || { echo "Aborted..."; exit 1; }
fi
else
echo "Safety checks skipped by configuration (--skip safety)." >&2
logmsg "SAFETY skipped"
fi
# 7) Select backend
if [[ -n "$TOOL_CHOICE" ]]; then
select_tool_by_name "$TOOL_CHOICE" || exit $?
fi
if [[ -z "$SELECTED_TOOL" ]]; then
choose_tool 1
fi
logmsg "TOOL selected=$SELECTED_TOOL"
# 8) PREVIEW
run_preview
# In dry-run mode, stop here (no backup, no copy)
if (( DRY_RUN )); then
echo "DRY-RUN: no changes made."
logmsg "FINISH dry_run"
exit 0
fi
# 9) Backup existing destination (unless skipped)
local backup="(none)"
if (( ! SKIP_BACKUP )); then
if [[ -e "$absolute_dst" ]]; then
backup=$(mktemp -d "/tmp/$(basename -- "$absolute_dst").$(date +%Y%m%dT%H%M%S%3N).XXXX")
cp -a -- "$absolute_dst"/. "$backup"/
fi
else
backup="(skipped)"
logmsg "BACKUP skipped"
fi
# 10) Execute the chosen strategy
case "$SELECTED_TOOL" in
rsync)
if (( COPY_MODE )); then
# Non-destructive copy: no --delete
# shellcheck disable=SC2086
rsync -aH --info=progress2 $RSYNC_OPTS_EXTRA -- "$absolute_src"/ "$absolute_dst"/
else
# Mirror mode: delete extraneous files
# shellcheck disable=SC2086
rsync -aH --delete --info=progress2 $RSYNC_OPTS_EXTRA -- "$absolute_src"/ "$absolute_dst"/
fi
;;
rclone)
if (( COPY_MODE )); then
# Non-destructive copy
# shellcheck disable=SC2086
rclone copy --progress --copy-links --local-no-check-updated $RCLONE_OPTS_EXTRA -- "$absolute_src" "$absolute_dst"
else
# Mirror mode (sync)
# shellcheck disable=SC2086
rclone sync --progress --copy-links --local-no-check-updated $RCLONE_OPTS_EXTRA -- "$absolute_src" "$absolute_dst"
fi
;;
cp|*)
if (( COPY_MODE )); then
# Non-destructive copy: do not clean destination; prefer updating only when newer
# shellcheck disable=SC2086
cp -au $CP_OPTS_EXTRA -- "$absolute_src"/. "$absolute_dst"/
else
# Emulate "sync": clear destination first (incl. dotfiles), then copy
rm_tree_contents_safe "$absolute_dst"
# shellcheck disable=SC2086
cp -a $CP_OPTS_EXTRA -- "$absolute_src"/. "$absolute_dst"/
fi
;;
esac
echo "The task was completed successfully. Previous data backed up to: $backup"
logmsg "FINISH ok backup='$backup'"
echo
}
# ------------------------------- Entrypoint ---------------------------------
main "$@"