-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestic.sh
More file actions
executable file
·2209 lines (1914 loc) · 66.4 KB
/
Copy pathrestic.sh
File metadata and controls
executable file
·2209 lines (1914 loc) · 66.4 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
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
# Restic Backup Manager
# A comprehensive wrapper script for Restic backup management
#
# Features:
# - Easy repository configuration and management
# - Automated backup scheduling with cron
# - Backup retention policy management
# - Progress tracking and colored output
# - Detailed logging and error handling
# - Interactive configuration interface
#
# Dependencies:
# - restic: The backup tool (https://restic.net)
# - jq: JSON processor for configuration management
# - crontab: For backup scheduling (usually pre-installed)
# Configuration
CONFIG_DIR="$HOME/.config"
REPOS_FILE="$CONFIG_DIR/restic.json"
LOG_FILE="/var/log/restic.log"
# Load Telegram configuration from JSON
load_telegram_config() {
if [ -f "$REPOS_FILE" ]; then
TELEGRAM_BOT_TOKEN=$(jq -r '.config.telegram.bot_token // empty' "$REPOS_FILE")
TELEGRAM_CHAT_ID=$(jq -r '.config.telegram.chat_id // empty' "$REPOS_FILE")
fi
}
# Initialize telegram configuration variables
TELEGRAM_BOT_TOKEN=""
TELEGRAM_CHAT_ID=""
load_telegram_config
# ANSI color codes (disabled)
COLOR_RED=''
COLOR_GREEN=''
COLOR_YELLOW=''
COLOR_BLUE=''
COLOR_PURPLE=''
COLOR_CYAN=''
COLOR_RESET=''
# Print messages without colors
log_info() { echo "[INFO] $1"; }
log_success() { echo "[SUCCESS] $1"; }
log_warning() { echo "[WARNING] $1"; }
log_error() { echo "[ERROR] $1"; }
# Check if jq is installed
check_jq_binary()
{
if ! command -v jq &> /dev/null; then
echo "jq is not installed. Installing..."
if command -v apt-get &> /dev/null; then
sudo apt-get update && sudo apt-get install -y jq
elif command -v dnf &> /dev/null; then
sudo dnf install -y jq
elif command -v pacman &> /dev/null; then
sudo pacman -S --noconfirm jq
else
echo "Error: Could not install jq. Please install it manually."
exit 1
fi
fi
}
# Function to check and install restic binary
check_restic_binary()
{
if ! command -v restic &> /dev/null; then
echo "Restic is not installed. Installing..."
# Check the package manager and install accordingly
if command -v apt-get &> /dev/null; then
# Debian/Ubuntu
sudo apt-get update
sudo apt-get install -y restic fuse3 whiptail
elif command -v dnf &> /dev/null; then
# Fedora/RHEL
sudo dnf install -y restic whiptail
elif command -v pacman &> /dev/null; then
# Arch Linux
sudo pacman -S --noconfirm restic libnewt
else
echo "Error: Could not determine package manager. Please install restic manually."
exit 1
fi
# Verify installation
if ! command -v restic &> /dev/null; then
echo "Error: Failed to install restic"
exit 1
fi
echo "Restic installed successfully"
fi
# Check if fuse3 is installed on Debian/Ubuntu systems
if command -v apt-get &> /dev/null && ! dpkg -l | grep -q "fuse3"; then
echo "Installing fuse3 package..."
sudo apt-get update
sudo apt-get install -y fuse3
fi
# Check if whiptail is installed
if ! command -v whiptail &> /dev/null; then
echo "Installing whiptail..."
if command -v apt-get &> /dev/null; then
sudo apt-get update
sudo apt-get install -y whiptail
elif command -v dnf &> /dev/null; then
sudo dnf install -y whiptail
elif command -v pacman &> /dev/null; then
sudo pacman -S --noconfirm libnewt
else
echo "Warning: Could not install whiptail. Graphical file selection will not be available."
fi
fi
}
# Function to read repositories from JSON
read_repos()
{
if [ ! -f "$REPOS_FILE" ]; then
echo "Error: Repositories file not found at $REPOS_FILE"
exit 1
fi
if ! jq empty "$REPOS_FILE" 2> /dev/null; then
echo "Error: Invalid JSON in $REPOS_FILE"
exit 1
fi
}
# Function to backup a specific repository
backup_repo()
{
local repo_name="$1"
local pre_script="$2"
local post_script="$3"
if [ -z "$repo_name" ]; then
log_error "Repository name not provided"
return 1
fi
# Extract repository configuration
local repo_config
repo_config=$(jq -r --arg name "$repo_name" '.repositories[] | select(.name == $name)' "$REPOS_FILE")
if [ -z "$repo_config" ]; then
log_error "Repository '$repo_name' not found"
return 1
fi
# Extract values from repo configuration
local destination password paths excludes
destination=$(echo "$repo_config" | jq -r '.destination')
password=$(echo "$repo_config" | jq -r '.password')
paths=$(echo "$repo_config" | jq -r '.paths[]')
excludes=$(echo "$repo_config" | jq -r '.exclude[]')
# Get pre/post backup scripts from config if not provided as parameters
if [ -z "$pre_script" ]; then
pre_script=$(echo "$repo_config" | jq -r '.pre_backup // empty')
fi
if [ -z "$post_script" ]; then
post_script=$(echo "$repo_config" | jq -r '.post_backup // empty')
fi
# Run pre-backup script if provided
if [ -n "$pre_script" ]; then
if [ -x "$pre_script" ]; then
log_info "Running pre-backup script: $pre_script"
if ! "$pre_script" "$repo_name"; then
log_error "Pre-backup script failed"
return 1
fi
else
log_error "Pre-backup script is not executable: $pre_script"
return 1
fi
fi
# Validate backup paths
local invalid_paths=0
while IFS= read -r path; do
# Expand ~ to $HOME
path="${path/#\~/$HOME}"
if [ ! -e "$path" ]; then
log_warning "Path does not exist: $path"
invalid_paths=1
fi
done < <(echo "$paths")
if [ $invalid_paths -eq 1 ]; then
log_error "Some backup paths are invalid. Please check your configuration."
return 1
fi
# Create exclude parameters
local exclude_params=""
while IFS= read -r exclude; do
exclude_params="$exclude_params --exclude '$exclude'"
done < <(echo "$excludes")
# Set password
export RESTIC_PASSWORD="$password"
# Create backup tag with timestamp
local datetime_tag="backup-$(date +"%Y%m%d-%H%M%S")"
# Create backup command with JSON output
local backup_cmd="restic -r $destination backup --tag $datetime_tag $exclude_params --json"
# Add paths
while IFS= read -r path; do
# Expand ~ to $HOME
path="${path/#\~/$HOME}"
backup_cmd="$backup_cmd '$path'"
done < <(echo "$paths")
# Execute backup with progress spinner
log_info "Starting backup for repository: $repo_name"
log_info "Destination: $destination"
local pid
eval "$backup_cmd" > /tmp/restic-backup-$$.json 2>&1 & pid=$!
local spinner=( '⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏' )
local i=0
while kill -0 $pid 2>/dev/null; do
echo -ne "\r${spinner[i]} Backing up... "
i=$(( (i+1) % ${#spinner[@]} ))
sleep 0.1
done
# Check backup status
wait $pid
local backup_status=$?
echo -ne "\r"
if [ $backup_status -eq 0 ]; then
log_success "Backup completed successfully"
# Parse backup statistics
local stats
stats=$(jq -r '.summary' $( tail -1 /tmp/restic-backup-$$.json ) 2>/dev/null)
if [ -n "$stats" ]; then
echo -e "\nBackup Statistics:"
echo "$stats" | jq -r 'to_entries | .[] | " " + (.key | gsub("_"; " ") | ascii_upcase) + ": " + (.value | tostring)'
fi
else
log_error "Backup failed"
local error_output=$(cat /tmp/restic-backup-$$.json)
rm -f /tmp/restic-backup-$$.json
# Send Telegram notification for backup failure
local telegram_message="❌ <b>Backup Failed</b>\n"
telegram_message+="📦 Repository: <code>${repo_name}</code>\n"
telegram_message+="🔗 Destination: <code>${destination}</code>\n\n"
telegram_message+="⚠️ Error output:\n<pre>${error_output}</pre>"
send_telegram "$telegram_message"
return 1
fi
rm -f /tmp/restic-backup-$$.json
# Apply retention policy if specified
if echo "$repo_config" | jq -e '.retention' > /dev/null; then
local last daily weekly monthly
last=$(echo "$repo_config" | jq -r '.retention.last')
daily=$(echo "$repo_config" | jq -r '.retention.daily')
weekly=$(echo "$repo_config" | jq -r '.retention.weekly')
monthly=$(echo "$repo_config" | jq -r '.retention.monthly')
log_info "Applying retention policy..."
if restic -r "$destination" forget --prune \
--keep-last "$last" \
--keep-daily "$daily" \
--keep-weekly "$weekly" \
--keep-monthly "$monthly"; then
log_success "Retention policy applied successfully"
else
log_error "Failed to apply retention policy"
return 1
fi
fi
# Run post-backup script if provided
if [ -n "$post_script" ]; then
if [ -x "$post_script" ]; then
log_info "Running post-backup script: $post_script"
if ! "$post_script" "$repo_name"; then
log_warning "Post-backup script failed"
fi
else
log_error "Post-backup script is not executable: $post_script"
return 1
fi
fi
}
# Function to backup all repositories
backup_all() {
local pre_script="$1"
local post_script="$2"
log_info "Starting backup of all repositories..."
echo "=========================================="
echo
local total_repos failed_repos=0
total_repos=$(jq -r '.repositories | length' "$REPOS_FILE")
if [ "$total_repos" -eq 0 ]; then
log_warning "No repositories configured. Please add repositories using 'config' command."
return 1
fi
# Get start time for total duration calculation
local start_time=$(date +%s)
local failed_repos_list=()
# Iterate through all repositories
local current=0
while IFS= read -r repo_name; do
current=$((current + 1))
echo "\n[$current/$total_repos] Processing repository: $repo_name"
echo "-------------------------------------------"
if ! backup_repo "$repo_name" "$pre_script" "$post_script"; then
failed_repos=$((failed_repos + 1))
failed_repos_list+=("$repo_name")
fi
# Show progress bar
local progress=$((current * 100 / total_repos))
printf "\nOverall Progress: [%3d%%] " "$progress"
local bar_size=40
local completed=$((progress * bar_size / 100))
local remaining=$((bar_size - completed))
printf "#%.0s" $(seq 1 $completed)
printf "%.0s-" $(seq 1 $remaining)
echo
done < <(jq -r '.repositories[] | .name' "$REPOS_FILE")
# Calculate total duration
local end_time=$(date +%s)
local duration=$((end_time - start_time))
local hours=$((duration / 3600))
local minutes=$(((duration % 3600) / 60))
local seconds=$((duration % 60))
echo -e "\n=========================================="
if [ $failed_repos -eq 0 ]; then
log_success "All repositories backed up successfully!"
else
log_warning "$failed_repos out of $total_repos repositories failed:"
for repo in "${failed_repos_list[@]}"; do
echo " ✗ $repo"
done
fi
echo -e "\nTotal time: "
[ $hours -gt 0 ] && echo -n "$hours hours "
[ $minutes -gt 0 ] && echo -n "$minutes minutes "
echo "$seconds seconds"
return $failed_repos
}
# Function to list all repositories
show_repos()
{
echo
echo "📦 Configured Backup Repositories"
echo "=================================="
# Get total number of repositories
local total_repos=$(jq -r '.repositories | length' "$REPOS_FILE")
if [ "$total_repos" -eq 0 ]; then
echo "\nNo repositories configured"
echo "Use 'config' command to add repositories"
return 0
fi
echo "\nFound $total_repos configured repositories\n"
# Get all repositories and iterate through them
local index=0
jq -r '.repositories[] | @base64' "$REPOS_FILE" | while read -r repo_b64; do
repo=$(echo "$repo_b64" | base64 -d)
# Extract repository details
name=$(echo "$repo" | jq -r '.name')
dest=$(echo "$repo" | jq -r '.destination')
# Print repository header with index
echo "[$index] Repository: $name"
echo " └─ 🔗 Destination: $dest"
# Get and print latest backup info
if [ -n "$RESTIC_PASSWORD" ]; then
unset RESTIC_PASSWORD
fi
export RESTIC_PASSWORD=$(echo "$repo" | jq -r '.password')
latest_snap=$(restic -r "$dest" snapshots --json latest 2>/dev/null | jq -r '.[0].time // "No backups yet"')
if [ "$latest_snap" != "No backups yet" ]; then
echo " └─ 🕒 Latest backup: $latest_snap"
else
echo " └─ 🕒 Latest backup: No backups yet"
fi
# Print paths with status
echo " └─ 📂 Backup paths:"
echo "$repo" | jq -r '.paths[]' | while read -r path; do
path="${path/#\~/$HOME}"
if [ -e "$path" ]; then
echo " └─ ✓ $path"
else
echo " └─ ✗ $path (not found)"
fi
done
# Print excludes if any
if echo "$repo" | jq -e '.exclude' > /dev/null && [ "$(echo "$repo" | jq -r '.exclude | length')" -gt 0 ]; then
echo " └─ 🚫 Excludes:"
echo "$repo" | jq -r '.exclude[]' | while read -r excl; do
echo " └─ $excl"
done
fi
# Print retention policy if exists
if echo "$repo" | jq -e '.retention' > /dev/null; then
echo " └─ ⏱️ Retention policy:"
echo " └─ Last: $(echo "$repo" | jq -r '.retention.last') snapshots"
echo " └─ Daily: $(echo "$repo" | jq -r '.retention.daily') days"
echo " └─ Weekly: $(echo "$repo" | jq -r '.retention.weekly') weeks"
echo " └─ Monthly: $(echo "$repo" | jq -r '.retention.monthly') months"
fi
# Print pre and post backup scripts if configured
local pre_script=$(echo "$repo" | jq -r '.pre_backup // empty')
local post_script=$(echo "$repo" | jq -r '.post_backup // empty')
if [ -n "$pre_script" ] || [ -n "$post_script" ]; then
echo " └─ 📜 Backup scripts:"
[ -n "$pre_script" ] && echo " └─ Pre-backup: $pre_script"
[ -n "$post_script" ] && echo " └─ Post-backup: $post_script"
fi
# Print separator between repositories
if [ $((index + 1)) -lt "$total_repos" ]; then
echo "\n────────────────────────────────────\n"
fi
index=$((index + 1))
done
echo
}
# Install command: copies the script to /usr/local/bin
install_script()
{
# First check if restic and jq are installed
check_restic_binary
check_jq_binary
sudo cp "$0" /usr/local/bin/restic.sh
sudo chmod +x /usr/local/bin/restic.sh
echo "Script installed successfully in /usr/local/bin/restic.sh"
# Create config directory if it doesn't exist
mkdir -p "$CONFIG_DIR"
# Configure Telegram notifications
read -r -p "Enter Telegram Bot Token for notifications (leave empty to skip): " bot_token
if [ -n "$bot_token" ]; then
read -r -p "Enter Telegram Chat ID: " chat_id
if [ -n "$chat_id" ]; then
if ! command -v curl &> /dev/null; then
echo "Installing curl for Telegram notifications..."
if command -v apt-get &> /dev/null; then
sudo apt-get update && sudo apt-get install -y curl
elif command -v dnf &> /dev/null; then
sudo dnf install -y curl
elif command -v pacman &> /dev/null; then
sudo pacman -S --noconfirm curl
else
echo "Warning: Could not install curl. Telegram notifications will not work."
fi
fi
# If repos file doesn't exist, create it with default structure
if [ ! -f "$REPOS_FILE" ]; then
cat > "$REPOS_FILE" << 'EOL'
{
"config": {
"telegram": {
"bot_token": "",
"chat_id": ""
}
},
"repositories": []
}
EOL
fi
# Update Telegram configuration in JSON file
local json_content
json_content=$(jq --arg token "$bot_token" --arg chat "$chat_id" '.config.telegram.bot_token = $token | .config.telegram.chat_id = $chat' "$REPOS_FILE")
echo "$json_content" > "$REPOS_FILE"
# Load the new configuration
load_telegram_config
echo "Telegram notifications configured successfully"
# Test Telegram configuration
local test_message="🔔 <b>Restic Backup Test</b>\n\nNotification system is working correctly!"
if send_telegram "$test_message"; then
echo "✅ Test notification sent successfully"
else
echo "❌ Failed to send test notification. Please check your Telegram configuration."
fi
fi
fi
# If repos file doesn't exist in the destination, create it
if [ ! -f "$REPOS_FILE" ]; then
cat > "$REPOS_FILE" << 'EOL'
{
"repositories": [
{
"name": "example",
"destination": "sftp:user@host:backup",
"password": "your-password-here",
"paths": [
"~/Documents"
],
"exclude": [
"*.tmp"
],
"retention": {
"last": 24,
"daily": 7,
"weekly": 4,
"monthly": 12
},
"pre_backup": "",
"post_backup": ""
}
]
}
EOL
echo "Created default repositories file at $REPOS_FILE"
echo "Please edit the file and set your backup configurations"
fi
}
# Function to initialize a specific repository
init_repo()
{
local repo_name="$1"
if [ -z "$repo_name" ]; then
echo "Error: Repository name not provided"
exit 1
fi
# Extract repository configuration
local repo_config
repo_config=$(jq -r --arg name "$repo_name" '.repositories[] | select(.name == $name)' "$REPOS_FILE")
if [ -z "$repo_config" ]; then
echo "Error: Repository '$repo_name' not found"
exit 1
fi
# Extract values from repo configuration
local destination
local password
destination=$(echo "$repo_config" | jq -r '.destination')
password=$(echo "$repo_config" | jq -r '.password')
# Set password
export RESTIC_PASSWORD="$password"
# Initialize repository
echo "Initializing repository: $repo_name"
if ! restic -r "$destination" init; then
echo "❌ Failed to initialize repository: $repo_name"
return 1
fi
echo "✅ Repository initialized successfully: $repo_name"
return 0
}
# Function to initialize all repositories
init_all()
{
echo "🔄 Initializing all repositories..."
echo "=================================="
echo
local total_repos=$(jq -r '.repositories | length' "$REPOS_FILE")
local current=0
local failed=0
# Iterate through all repositories
jq -r '.repositories[] | .name' "$REPOS_FILE" | while read -r repo_name; do
current=$((current + 1))
echo -e "📦 Processing repository ($current/$total_repos): \033[1;36m$repo_name\033[0m"
echo "-------------------------------------------"
if ! init_repo "$repo_name"; then
failed=$((failed + 1))
fi
echo
done
if [ $failed -eq 0 ]; then
echo "✅ All repositories initialized successfully!"
else
echo "⚠️ Initialization completed with $failed failures."
return 1
fi
}
# Function to list snapshots of a specific repository
list_repo_snapshots()
{
local repo_name="$1"
local verbose="$2"
if [ -z "$repo_name" ]; then
echo "Error: Repository name not provided"
exit 1
fi
# Extract repository configuration
local repo_config
repo_config=$(jq -r --arg name "$repo_name" '.repositories[] | select(.name == $name)' "$REPOS_FILE")
if [ -z "$repo_config" ]; then
echo "Error: Repository '$repo_name' not found"
exit 1
fi
# Extract values from repo configuration
local destination
local password
destination=$(echo "$repo_config" | jq -r '.destination')
password=$(echo "$repo_config" | jq -r '.password')
# Set password
export RESTIC_PASSWORD="$password"
# Print repository header
echo -e "📦 Repository: \033[1;36m$repo_name\033[0m"
echo " └─ 🔗 Destination: $destination"
echo " └─ 📊 Snapshots:"
echo
# List snapshots with different detail levels
if [ "$verbose" = "true" ]; then
echo "🔍 Detailed snapshot list:"
if ! restic -r "$destination" snapshots --verbose; then
echo "❌ Failed to list snapshots for repository: $repo_name"
return 1
fi
echo -e "\n📋 Latest snapshot contents:"
if ! restic -r "$destination" ls latest; then
echo "❌ Failed to list contents for repository: $repo_name"
return 1
fi
echo -e "\n📊 Repository statistics:"
if ! restic -r "$destination" stats; then
echo "❌ Failed to get statistics for repository: $repo_name"
return 1
fi
else
if ! restic -r "$destination" snapshots; then
echo "❌ Failed to list snapshots for repository: $repo_name"
return 1
fi
fi
echo
return 0
}
# Function to list snapshots of all repositories
list_all_snapshots()
{
local verbose="$1"
echo "🔄 Listing snapshots from all repositories..."
echo "==========================================="
echo
local total_repos=$(jq -r '.repositories | length' "$REPOS_FILE")
local current=0
local failed=0
# Iterate through all repositories
jq -r '.repositories[] | .name' "$REPOS_FILE" | while read -r repo_name; do
current=$((current + 1))
if ! list_repo_snapshots "$repo_name" "$verbose"; then
failed=$((failed + 1))
fi
done
if [ $failed -eq 0 ]; then
echo "✅ Successfully listed all snapshots!"
else
echo "⚠️ Listing completed with $failed failures."
return 1
fi
}
# Function to restore a specific repository
restore_repo()
{
local repo_name="$1"
local snapshot_id="$2"
local restore_path="$3"
local files=("${@:4}") # Get all remaining arguments as files array
if [ -z "$repo_name" ]; then
echo "Error: Repository name not provided"
exit 1
fi
if [ -z "$snapshot_id" ]; then
echo "Error: Snapshot ID not provided"
exit 1
fi
# Extract repository configuration
local repo_config
repo_config=$(jq -r --arg name "$repo_name" '.repositories[] | select(.name == $name)' "$REPOS_FILE")
if [ -z "$repo_config" ]; then
echo "Error: Repository '$repo_name' not found"
exit 1
fi
# Extract values from repo configuration
local destination
local password
destination=$(echo "$repo_config" | jq -r '.destination')
password=$(echo "$repo_config" | jq -r '.password')
# Set password
export RESTIC_PASSWORD="$password"
# Create restore command
local restore_cmd="restic -r $destination restore $snapshot_id"
# If files are specified, add them to the command
if [ ${#files[@]} -gt 0 ]; then
echo "🔄 Restoring specific files from repository: \033[1;36m$repo_name\033[0m"
echo " └─ 🔗 Destination: $destination"
echo " └─ 📊 Snapshot ID: $snapshot_id"
echo " └─ 📂 Files to restore:"
for file in "${files[@]}"; do
echo " └─ $file"
restore_cmd="$restore_cmd --include '$file'"
done
else
echo "🔄 Restoring entire snapshot from repository: \033[1;36m$repo_name\033[0m"
echo " └─ 🔗 Destination: $destination"
echo " └─ 📊 Snapshot ID: $snapshot_id"
fi
# Add target directory
echo " └─ 🎯 Target path: $restore_path"
restore_cmd="$restore_cmd --target '$restore_path'"
echo
echo "Starting restore operation..."
if ! eval "$restore_cmd"; then
echo "❌ Failed to restore from repository: $repo_name"
return 1
fi
echo "✅ Restore completed successfully"
return 0
}
# Function to handle restore command
handle_restore_command() {
local repo_name=""
local snapshot_id=""
local files=()
local use_gui=false
local restore_path="." # Default to current directory
# Parse arguments
shift # skip the 'restore' command
while [[ $# -gt 0 ]]; do
case "$1" in
-f | --file)
shift
while [[ $# -gt 0 ]] && [[ $1 != -* ]]; do
files+=("$1")
shift
done
;;
-g | --gui)
use_gui=true
shift
;;
-p | --path)
shift
if [[ $# -gt 0 ]]; then
restore_path="$1"
shift
else
echo "Error: -p option requires a path argument"
return 1
fi
;;
*)
if [ -z "$repo_name" ]; then
repo_name="$1"
elif [ -z "$snapshot_id" ]; then
snapshot_id="$1"
fi
shift
;;
esac
done
if [ -z "$repo_name" ] || [ -z "$snapshot_id" ]; then
echo "Error: Repository name and snapshot ID are required"
echo "Usage: $0 restore <repo-name> <snapshot-id> [-f file1 file2 ...] [-g] [-p path]"
echo "Options:"
echo " -f, --file Specify files to restore"
echo " -g, --gui Use graphical interface to select files"
echo " -p, --path Target path for restoring files (default: current directory)"
return 1
fi
# Extract repository configuration for graphical selection
if [ "$use_gui" = true ]; then
if ! command -v whiptail &> /dev/null; then
log_error "whiptail is not installed. Cannot use graphical file selection."
return 1
fi
# Get repository configuration
repo_config=$(jq -r --arg name "$repo_name" '.repositories[] | select(.name == $name)' "$REPOS_FILE")
if [ -z "$repo_config" ]; then
log_error "Repository '$repo_name' not found"
return 1
fi
destination=$(echo "$repo_config" | jq -r '.destination')
password=$(echo "$repo_config" | jq -r '.password')
# Get files through graphical selection
if selected_files=($(select_files_graphically "$repo_name" "$snapshot_id" "$destination" "$password")); then
if [ ${#selected_files[@]} -gt 0 ]; then
files=("${selected_files[@]}")
else
log_error "No files selected"
return 1
fi
else
return 1
fi
fi
restore_repo "$repo_name" "$snapshot_id" "$restore_path" "${files[@]}"
}
# Function to select files graphically using whiptail
select_files_graphically() {
local repo_name="$1"
local snapshot_id="$2"
local destination="$3"
local temp_file="/tmp/restic-files-$$.txt"
local selected_files=()
# List all files in the snapshot and save to temporary file
if ! RESTIC_PASSWORD="$4" restic -r "$destination" ls "$snapshot_id" > "$temp_file"; then
log_error "Failed to list files in snapshot"
rm -f "$temp_file"
return 1
fi
# Create array of files with their selection status (initially OFF)
local file_list=()
while IFS= read -r file; do
# Skip empty lines and directory entries
[[ -z "$file" || "$file" =~ /$ ]] && continue
file_list+=("$file" "" "OFF")
done < "$temp_file"
if [ ${#file_list[@]} -eq 0 ]; then
log_error "No files found in snapshot"
rm -f "$temp_file"
return 1
fi
# Show checklist dialog
if selected=$(whiptail --title "Select Files to Restore" \
--checklist "Use space to select/deselect files" \
$((LINES-8)) $((COLUMNS-10)) $((LINES-15)) \
"${file_list[@]}" \
3>&1 1>&2 2>&3); then
# Convert selected files string to array
eval "selected_files=($selected)"
else
log_info "File selection cancelled"
rm -f "$temp_file"
return 1
fi
rm -f "$temp_file"
# Print selected files to stdout (one per line)
printf "%s\n" "${selected_files[@]}"
return 0
}
# Function to manage crontab scheduling
manage_crontab()
{
local script_path="/usr/local/bin/restic.sh"
local schedule
local mode="$1"
echo "🕒 Configurazione Backup Automatico"
echo "=================================="
echo
if [ "$mode" = "-s" ]; then
echo "📋 Schedulazioni di backup attuali:"
echo
# Leggi il crontab attuale
local current_crontab
current_crontab=$(crontab -l 2> /dev/null || echo "")
# Filtra e mostra solo le righe relative a restic.sh
local restic_schedules
restic_schedules=$(echo "$current_crontab" | grep "restic\.sh backup" || echo "")
if [ -z "$restic_schedules" ]; then
echo "Nessuna schedulazione di backup configurata."
else
echo "$restic_schedules" | while IFS= read -r line; do
local schedule_part=${line%restic.sh*}
echo "🔄 $schedule_part"
echo " └─ Comando: $line"
echo
done
fi
return 0
elif [ "$mode" = "-d" ]; then
echo "⚠️ Rimozione delle schedulazioni di backup"
echo
echo "Vuoi rimuovere tutte le schedulazioni di backup? [s/N]"
read -r remove_cron
if [[ "$remove_cron" =~ ^[Ss]$ ]]; then
# Leggi il crontab attuale
local current_crontab
current_crontab=$(crontab -l 2> /dev/null || echo "")
# Rimuovi tutte le pianificazioni di restic.sh
local new_crontab
new_crontab=$(echo "$current_crontab" | grep -v "restic\.sh backup")
# Installa il nuovo crontab
echo "$new_crontab" | crontab -
if [ $? -eq 0 ]; then
echo "✅ Schedulazioni rimosse con successo!"
else
echo "❌ Errore durante la rimozione delle schedulazioni"
return 1
fi
else
echo "Rimozione annullata"
fi
return 0
fi
# Seleziona la schedulazione
select_schedule() {
echo "Seleziona la frequenza di backup:"