-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheback
executable file
·745 lines (625 loc) · 16.6 KB
/
eback
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
#!/bin/bash
if [[ "$(whoami)" != "root" ]]; then
echo "Must be run as root. Try 'sudo !!'"
exit 0
fi
main() {
trap sig_close SIGINT
trap sig_close SIGTERM
trap sig_close SIGHUP
BACKUP=false
FORCE_SCAN=false
SKIP_SCAN=false
UNSAFE_MOUNT=false
DEVICE_SCAN_GRACE_PERIOD=1200
MOUNTED_DEV=""
REM_MIN=1024
housing_dir="/etc/eback" # to be changed to /etc/.../ when upon finalizing
timestamp_loc="$housing_dir/lastdate"
used_devs_loc="$housing_dir/used_devs"
devdata_loc="$housing_dir/.devices"
reservedata_loc="$housing_dir/reserved"
lastback_stamp_loc="$housing_dir/.lastback"
dirlist_loc="$housing_dir/dirs"
missing_uuids_loc="$housing_dir/missing_uuids.err"
while getopts "fsuBR :" OPTION; do
case $OPTION in
f)
FORCE_SCAN=true
;;
s)
SKIP_SCAN=true
;;
u)
UNSAFE_MOUNT=true
;;
B)
BACKUP=true
;;
R)
recover "$@"
exit_fxn
;;
*)
echo "Incorrect options provided."
exit 1
;;
esac
done
if [[ "$BACKUP" == "true" ]]; then
if [[ -f "${housing_dir}/.backup_lock" ]]; then
if [[ "$FORCE_SCAN" != "true" ]]; then
echo "It looks like a backup process is already running. If this is incorrect, override this check with the -f flag."
exit
fi
fi
touch "${housing_dir}/.backup_lock"
backup
rm "${housing_dir}/.backup_lock"
exit_fxn
fi
clear
if [[ ! -d "${housing_dir}" ]]; then
mkdir -p ${housing_dir}
fi
if [[ ! -f "${timestamp_loc}" ]]; then
touch ${timestamp_loc}
fi
if [[ ! -f "${devdata_loc}" ]]; then
touch ${devdata_loc}
fi
if [[ ! -f "${used_devs_loc}" ]]; then
touch ${used_devs_loc}
fi
if [[ ! -f "${reservedata_loc}" ]]; then
touch ${reservedata_loc}
fi
if [[ ! -f "${dirlist_loc}" ]]; then
touch ${dirlist_loc}
fi
if [[ "$SKIP_SCAN" == "true" ]]; then
echo -e "\e[33mDevice scan manually overridden.\e[0m"
elif [[ "$FORCE_SCAN" == "false" && -f "$timestamp_loc" ]]; then
last_date=`cat $timestamp_loc`
if [[ "${last_date}" == "" ]]; then last_date=0; fi
sec_since=$((`date +%s` - $last_date))
if [[ $sec_since -lt $DEVICE_SCAN_GRACE_PERIOD ]]; then
echo -e "\e[33mScanned devices ${sec_since}s ago, skipping.\e[0m"
SKIP_SCAN=true
fi
fi
if [[ "$SKIP_SCAN" == "false" ]]; then
scan_devices
echo -e "\e[33mDevices discovered:\e[0m"
print_device_info
else
load_data
fi
run_loop
}
# Performs the recovery of some files
recover() {
if [[ ! -f "${used_devs_loc}" ]]; then
echo "ERROR: ${used_devs_loc} does not exist."
exit_fxn
fi
if [[ $# -gt 2 ]]; then
echo "Usage: eback -R [directory]"
exit_fxn
fi
# Gather device UUIDs
UUIDs=()
while IFS= read -r line; do
UUIDs=(${UUIDs[@]} $line)
done < "${used_devs_loc}"
# Mount devices
temps=()
for i in `seq 0 $((${#UUIDs[@]}-1))`; do
tmp=`mktemp -d`
tmp="$tmp/"
temps=(${temps[@]} $tmp)
mount -o suid UUID="${UUIDs[i]}" $tmp
ret=$?
if [[ $ret -ne 0 ]]; then
echo "ERROR: Failed to mount UUID ${UUIDs[i]}. Mount error code: $ret. Exiting..."
exit_fxn
fi
done
# Get the requested file/directory if not already specified
if [[ $# -eq 2 ]]; then
request="$2"
else
printf "File/directory you would like to recover: "
read request
fi
echo "$request chosen for recovery."
echo ""
[[ "$dest" == "" ]] && dest="$request" || :
if [[ "${request:0:1}" == "/" ]]; then
printf "Search depth (default=0): "
read depth
num_regex='^[0-9]+$'
if [[ "$depth" == "" ]]; then
depth=0
elif ! [[ $depth =~ $re ]]; then
echo "$depth is not a valid number, using 0 instead."
depth=0
elif [[ $depth -lt 0 ]]; then
echo "$depth is not a valid number, using 0 instead."
depth=0
fi
fi
rsync_list=()
# Look for the requested file/directory in the backups
for h in `seq 0 $((${#temps[@]}-1))`; do
if [[ "${request:0:1}" == "/" ]]; then
output=(`find ${temps[h]}/$request -maxdepth $depth 2> /dev/null`)
else
printf "This may take a while..."
output=(`find ${temps[h]} -name $request 2> /dev/null`)
printf "\r$(tput el)"
fi
echo -e "In UUID [\e[33m${UUIDs[h]^^}\e[39m]]:"
# Format the output so that it makes more sense for the user
for i in `seq 0 $((${#output[@]}-1))`; do
rsync_list=(${rsync_list[@]} ${output[i]//\/\/\//\/})
for j in `seq 0 $((${#temps[@]}-1))`; do
output[i]=${output[i]//${temps[j]}/}
done
output[i]=${output[i]//\/\/\//\/}
output[i]=${output[i]//\/\//\/}
printf "\t${output[i]}\n"
done
done
printf "Would you like to rsync these findings now? [y/N]: "
read answer
if [[ "$answer" == "y" || "$answer" == "Y" ]]; then
printf "rsync arguments (e.g. -v -rHA -Xogt --verbose): "
read args
printf "rsync destination: "
read destination
echo ""
echo ""
for i in `seq 0 $((${#rsync_list[@]}-1))`; do
if [[ i -eq 11 ]]; then
echo "\e[39m..."
break
fi
echo -e "\e[31mrsync $args ${rsync_list[i]} $destination"
done
printf "\e[39mWould you like to run these commands? [y/N]: "
read answer
if [[ "$answer" == "y" || "$answer" == "Y" ]]; then
echo "Running rsyncs..."
for i in `seq 0 $((${#rsync_list[@]}-1))`; do
rsync $args ${rsync_list[i]} $destination &
pids[${i}]=$!
done
# Wait for all the rsyncs to finish before exiting
for pid in ${pids[*]}; do
wait $pid
done
else
echo "You can mount backup drives to search through them manually with the following commands:"
for dev in ${UUIDs[@]}; do
echo -e "\t\e[36mmount -o suid UUID=$dev <directory>\e[39m"
done
fi
else
echo "You can mount backup drives to search through them manually with the following commands:"
for dev in ${UUIDs[@]}; do
echo -e "\t\e[36mmount -o suid UUID=$dev <directory>\e[39m"
done
fi
}
# PERFORMS THE SYSTEM BACKUP
backup() {
if [[ ! -f "${used_devs_loc}" ]]; then
echo "ERROR: ${used_devs_loc} does not exist."
exit_fxn
fi
if [[ ! -f "${dirlist_loc}" ]]; then
echo "ERROR: ${dirlist_loc} does not exist."
exit_fxn
fi
# Gather device UUIDs
UUIDs=()
while IFS= read -r line; do
UUIDs=(${UUIDs[@]} $line)
done < "${used_devs_loc}"
# Mount devices
rm $missing_uuids_loc
temps=()
dev_count=0
for i in `seq 0 $((${#UUIDs[@]}-1))`; do
tmp=`mktemp -d`
tmp="$tmp/"
mount -o suid UUID="${UUIDs[i]}" $tmp
ret=$?
if [[ $ret -ne 0 ]]; then
echo "ERROR: Failed to mount UUID ${UUIDs[i]}. Mount error code: $ret. Exiting..."
umount $tmp &> /dev/null
echo ${UUIDs[i]} >> $missing_uuids_loc
else
temps=(${temps[@]} $tmp)
dev_count=$((dev_count + 1))
fi
done
# Gather backup directories
dirs=()
while IFS= read -r line; do
dirs=(${dirs[@]} $line)
done < "${dirlist_loc}"
echo "`date`" > $lastback_stamp_loc
n_threads=$dev_count
for dir in ${dirs[@]}; do
cback -s $n_threads $dir ${temps[@]}
done
# Done.
}
run_loop() {
while [ 1 -eq 1 ]; do
read -p "Command (h for help): " input
case ${input:0:1} in
A)
add_device ${input:2:${#input}}
;;
R)
remove_device ${input:2:${#input}}
;;
L)
list_devices
;;
D)
list_inuse_devices
;;
a)
add_directory ${input:2:${#input}}
;;
d)
dir_list
;;
r)
remove_directory ${input:2:${#input}}
;;
i)
print_device_info
;;
s)
scan_devices
print_device_info
;;
l)
if [[ -f "$lastback_stamp_loc" ]]; then
echo -n "The last system backup occurred on: "
cat $lastback_stamp_loc
else
echo "The system has not been backed up yet."
fi
;;
h)
help_message
;;
q)
exit_fxn
exit 0
;;
*)
echo "$input: Unknown command."
;;
esac
done
}
list_inuse_devices() {
i=1
while IFS= read -r line; do
echo -e -n " -->\t$i. $line"
ret=`ls -l /dev/disk/by-uuid | grep "$i"`
[[ "$ret" == "" ]] && echo -e -n " \e[31m(Not attached)\e[39m\n" || echo -e -n " \e[32m(Attached)\e[39m\n"
i=$((i+1))
done < "${used_devs_loc}"
}
# lists devices that can potentially be added
list_devices() {
for i in `seq 0 $((${#devs[@]}-1))`; do
make_readable ${dev_sizes[$i]}
total_size="$retval"
echo -e " --> \t$((i + 1)). ${dev_labels[i]} [\e[33m${dev_IDs[i]}\e[0m, /dev/${devs[i]}]\e[0m, \e[32m${total_size}\e[0m"
done
}
# $1 is the device's index in the list of devices (as returned by list_devices())
add_device() {
if [[ "$1" == "" ]]; then
echo "Usage: A <device number>"
return
fi
regex='^[0-9]+$'
if ! [[ $1 =~ $regex ]]; then
echo "Error: second input must be a positive number."
return
fi
if [[ $1 -gt ${#devs[@]} || $1 -lt 1 ]]; then
echo "Error: device number must be between 1 and ${#devs[@]}."
fi
existing_devs=(`cat ${used_devs_loc}`)
for item in ${existing_devs[@]}; do
if [[ "$item" == "${dev_IDs[$(($1 - 1))]}" ]]; then
echo "Error: this device is already marked as in-use."
return
fi
done
echo "${dev_IDs[$(($1 - 1))]}" >> ${used_devs_loc}
echo " >> ${dev_IDs[$(($1 - 1))]}"
}
remove_device() {
if [[ "$1" == "" ]]; then
echo "Usage: A <device number>"
return
fi
regex='^[0-9]+$'
if ! [[ $1 =~ $regex ]]; then
echo "Error: second input must be a positive number."
return
fi
existing_devs=(`cat ${used_devs_loc}`)
if [[ ${existing_devs[@]} == "" ]]; then
echo "Error: no devices are currently marked as in-use."
return
fi
exact=0
i=1
for item in ${existing_devs[@]}; do
if [[ $i -eq $1 ]]; then
exact=1
else
echo "$item" >> ${used_devs_loc}.tmp
fi
i=$((i + 1))
done
if [[ $exact -eq 0 ]]; then
[[ -f "${used_devs_loc}.tmp" ]] && rm ${used_devs_loc}.tmp || :
echo "There are not $1 devices in the device list."
return
else
if [[ -f "${used_devs_loc}.tmp" ]]; then
mv ${used_devs_loc}.tmp ${used_devs_loc}
else
rm ${used_devs_loc}
touch ${used_devs_loc}
fi
echo "Removed device."
fi
}
dir_list() {
list=(`cat ${dirlist_loc}`)
if [[ ${#list[@]} -eq 0 ]]; then
echo -e "\e[31mThere are not currently any directories chosen for backups.\e[39m"
return
fi
for item in ${list[@]}; do
echo -e " -->\t\e[32m${item}\e[39m"
done
}
# $1 should be the directory to be added
add_directory() {
if [[ "$1" == "" ]]; then
echo "Usage: a <directory>"
return
fi
abs_path=`realpath $1`
[[ "$abs_path" == "/" ]] && abs_path="" || :
if [[ ! -d "$abs_path/" ]]; then
echo "The directory $abs_path/ does not exist."
return
fi
matches=(`grep "$abs_path/" ${dirlist_loc}`)
for item in ${matches[@]}; do
if [[ "$item" == "$abs_path/" ]]; then
echo "$abs_path/ is already in the backup list."
return
fi
done
echo "Adding $abs_path/ to the directory list."
echo "$abs_path/" >> ${dirlist_loc}
}
# $1 should be the directory to be removed
remove_directory() {
if [[ "$1" == "" ]]; then
echo "Usage: r <directory>"
return
fi
abs_path=`realpath $1`
[[ "$abs_path" == "/" ]] && abs_path="" || :
list=(`cat ${dirlist_loc}`)
exact=0
for item in ${list[@]}; do
if [[ "$item" == "$abs_path/" ]]; then
exact=1
else
echo "$item" >> ${dirlist_loc}.tmp
fi
done
if [[ $exact -eq 0 ]]; then
rm ${dirlist_loc}.tmp
echo "$abs_path/ is not in the directory list."
return
else
if [[ -f "${dirlist_loc}.tmp" ]]; then
mv ${dirlist_loc}.tmp ${dirlist_loc}
else
rm ${dirlist_loc}
touch ${dirlist_loc}
fi
echo "Removed $abs_path/ from the directory list."
fi
}
save_data() {
# Order: devs(), dev_IDs(), dev_labels(), dev_sizes(), dev_reserved(), dev_remaining()
touch ${devdata_loc}.tmp
for i in $(seq 0 $((${#devs[@]}-1))); do
printf "${devs[$i]}\$${dev_IDs[$i]}\$${dev_labels[$i]}\$${dev_sizes[$i]}\n" >> ${devdata_loc}.tmp
done
mv ${devdata_loc}.tmp ${devdata_loc}
}
load_data() {
# Order: devs(), dev_IDs(), dev_labels(), dev_sizes()
devs=()
dev_IDs=()
dev_labels=()
dev_sizes=()
if [[ ! -f "$devdata_loc" ]]; then
echo "An unknown error occurred, please try again."
rm $timestamp_loc
exit 1
else
i=0
while IFS= read -r line; do
devs=(${devs[@]} `echo "$line" | cut -d'$' -f1`)
dev_IDs=(${dev_IDs[@]} `echo "$line" | cut -d'$' -f2`)
inval=`echo "$line" | cut -d'$' -f3`
fix_space # returns to $retval
dev_labels[$i]="$retval"
dev_sizes=(${dev_sizes[@]} `echo "$line" | cut -d'$' -f4`)
i=$((i+1))
done < "$devdata_loc"
fi
}
print_device_info() {
if [[ ${#devs[@]} -eq 0 ]]; then
echo "No external devices were found, try attaching some and try again."
else
for i in $(seq 0 $((${#devs[@]}-1))); do
make_readable ${dev_sizes[$i]}
total_size="$retval"
remaining_size="$retval"
printf "\t╔ ${dev_labels[$i]} [\e[33m${dev_IDs[$i]}\e[0m]\n\t╚ \e[33m/dev/${devs[$i]}\e[0m, \e[32m${total_size}\e[0m\n"
[[ $i -ne $((${#devs[@]}-1)) ]] && printf "\n" || :
done
fi
}
make_readable() {
# Usage: $0 <bytes>[K]
# Legible value returned via $retval
if [[ "$1" == *"K" ]]; then
retval=`echo $1 | numfmt --from=iec --to=iec`
else
retval=`echo $1 | numfmt --from=none --to=iec`
fi
return 0
}
scan_devices() {
potential_devs=()
devs=()
dev_IDs=()
dev_labels=()
dev_sizes=()
set_potential_devs
tmpdir=`mktemp -d`
for device in ${potential_devs[@]}; do
status="" # this used to be a check for whether the drive is already mounted or not, but that is unnecessary so it's skipped now
printf "Scanning /dev/$device...\t"
if [[ "$status" == "" ]]; then
MOUNTED_DEV="/dev/$device"
if [[ !$UNSAFE_SCAN ]]; then
count=`ps aux | grep "mount ${MOUNTED_DEV}" | wc -l`
if [[ $count -ge 2 ]]; then
printf "Failed; it looks like ${MOUNTED_DEV} is being mounted elsewhere.\n\t\t\tTo attempt to mount ${MOUNTED_DEV} regardless, use -u\n"
continue
fi
fi
ret=`mount /dev/$device $tmpdir &> /dev/null`
if [[ $ret -ne 0 ]]; then
echo "Failed, $ret"
umount /dev/$device &> /dev/null
MOUNTED_DEV=""
elif [[ ! -f "$tmpdir/check_stamp.nat" ]]; then
echo "Not properly formatted"
umount /dev/$device &> /dev/null
MOUNTED_DEV=""
else
size=`df $tmpdir | awk ' { print $2 } ' | cut -d$'\n' -f 2 | cut -d '%' -f 1`
no_K_size=`echo ${size}K | numfmt --from=iec --to=none` # df displays disk space in 1K blocks, we want it strictly in bytes
# dev_sizes=(${dev_sizes[@]} $no_K_size)
# devs=(${devs[@]} $device)
dev_ID=`ls -l /dev/disk/by-uuid | grep $device | awk '{print $9}'`
# dev_IDs=(${dev_IDs[@]} $dev_ID)
label=`ls -l /dev/disk/by-label | grep $device | awk '{print $9}'`
if [[ "$label" == "" ]]; then label="No\x20label\x20found"; fi
# dev_labels=(${dev_labels[@]} $label)
grep_res=(`cat $reservedata_loc | grep -n $dev_ID | cut -d':' -f1`)
if [[ "$grep_res" != "" ]]; then
reserved_size=0
for k in $(seq 0 $((${#grep_res[@]} - 1))); do
reserved_size=$((reserved_size + `cat $reservedata_loc | sed -n "$((${grep_res[k]} - 1))p" | cut -d':' -f2 | numfmt --from=iec --to=none`))
done
if [[ $(($no_K_size - $reserved_size)) -lt $REM_MIN ]]; then
umount $tmpdir
MOUNTED_DEV=""
echo -e "\e[33mFull\e[0m"
continue
fi
fi
devs=(${devs[@]} $device)
dev_sizes=(${dev_sizes[@]} $no_K_size)
dev_IDs=(${dev_IDs[@]} $dev_ID)
dev_labels=(${dev_labels[@]} $label)
echo "Formatted"
umount $tmpdir
MOUNTED_DEV=""
fi
else
# echo "Failed because this device is already mounted."
:
fi
done
date +%s > $timestamp_loc
save_data
rmdir $tmpdir
}
sig_close() {
echo
printf "SIGINT, SIGTERM or SIGHUP received, exiting...\n"
exit_fxn
}
fix_space() {
# Usage: $0, with $inval set to the input string
retval=`echo "$inval" | sed 's/ /\\x20/g'`
return 0
}
set_potential_devs() {
potential_devs=(`ls -l /dev/disk/by-uuid | awk '{print $11}' | cut -d'/' -f3 | grep "sd*"`)
return 0
}
exit_fxn() {
rm $tmpdir &> /dev/null
rm $tmpdata &> /dev/null
[[ "$MOUNTED_DEV" != "" ]] && umount $MOUNTED_DEV &> /dev/null || :
for dir in ${temps[@]}; do
umount $dir &> /dev/null
rmdir $dir
done
printf "Goodbye.\n"
exit
}
help_message() {
# -a) Adding directories to the backups
# -r) Removing directories from the backups
# -i) Printing out info about all the backups
# -l) Print when the last backup occurred
# -s) Rescan device data
# -h) Help command
# -q) Quit
# *) Make executable program that gets put in crontab and does the actual backing up (probably same as previous *)
echo -e "\n\e[33m\e[4mCommands\e[0m"
echo -e "\tA) Add a device to the backup system"
echo -e "\tR) Remove a device from the backup system"
echo -e "\tL) List the devices that are currently visible to eBack"
echo -e "\tD) List the devices that are currently registered in the backup system"
echo -e "\ta) Add a directory to the backup system"
echo -e "\tr) Remove a directory from the backup system"
echo -e "\ts) Rescan available external devices"
echo -e "\th) Display this info message"
echo -e "\tl) Print when the last backup occurred"
echo -e "\tq) Quit\n"
}
main "$@"