-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruleset-fetcher.sh
More file actions
1733 lines (1504 loc) · 51.6 KB
/
ruleset-fetcher.sh
File metadata and controls
1733 lines (1504 loc) · 51.6 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
VERSION="1.1.0"
GITHUB_REPO="prettyleaf/ruleset-fetcher"
GITHUB_RAW_URL="https://raw.githubusercontent.com/${GITHUB_REPO}/main/ruleset-fetcher.sh"
CONFIG_DIR="/opt/ruleset-fetcher"
CONFIG_FILE="${CONFIG_DIR}/config.conf"
URLS_FILE="${CONFIG_DIR}/urls.txt"
LOG_FILE="${CONFIG_DIR}/ruleset-fetcher.log"
SCRIPT_PATH="/usr/local/bin/ruleset-fetcher"
SYMLINK_PATH="/usr/local/bin/rfetcher"
DOWNLOAD_DIR=""
UPDATE_INTERVAL="6"
TELEGRAM_BOT_TOKEN=""
TELEGRAM_CHAT_ID=""
TELEGRAM_THREAD_ID="0"
TELEGRAM_ENABLED="false"
GITHUB_ACCESS_TOKEN=""
# Colors with terminal detection (stdout or stderr)
if [[ -t 1 || -t 2 ]]; then
RED=$'\033[31m'
GREEN=$'\033[32m'
YELLOW=$'\033[33m'
BLUE=$'\033[34m'
CYAN=$'\033[36m'
GRAY=$'\033[37m'
LIGHT_GRAY=$'\033[90m'
NC=$'\033[0m'
BOLD=$'\033[1m'
else
RED=""
GREEN=""
YELLOW=""
BLUE=""
CYAN=""
GRAY=""
LIGHT_GRAY=""
NC=""
BOLD=""
fi
print_banner() {
echo -e "${CYAN}"
echo ' _ _ __ _ _ '
echo ' _ __ _ _| | ___ ___ ___| |_ / _| ___| |_ ___| |__ ___ _ __ '
echo '| '\''__| | | | |/ _ \/ __|/ _ \ __| | |_ / _ \ __/ __| '\''_ \ / _ \ '\''__|'
echo '| | | |_| | | __/\__ \ __/ |_ | _| __/ || (__| | | | __/ | '
echo '|_| \__,_|_|\___||___/\___|\__| |_| \___|\__\___|_| |_|\___|_| '
echo -e "${NC}"
echo -e " ${BLUE}v${VERSION}${NC}"
echo ""
}
setup_symlink() {
if [[ "$EUID" -ne 0 ]]; then
return 1
fi
# Setup main symlink (ruleset-fetcher)
if [[ -L "$SCRIPT_PATH" && "$(readlink -f "$SCRIPT_PATH")" == "$(readlink -f "$0")" ]]; then
: # Already configured
elif [[ -d "$(dirname "$SCRIPT_PATH")" ]]; then
rm -f "$SCRIPT_PATH"
if [[ "$(readlink -f "$0")" != "${SCRIPT_PATH}" ]]; then
cp "$(readlink -f "$0")" "${SCRIPT_PATH}"
chmod +x "${SCRIPT_PATH}"
fi
fi
# Setup short alias symlink (rfetcher)
if [[ -L "$SYMLINK_PATH" && "$(readlink -f "$SYMLINK_PATH")" == "$SCRIPT_PATH" ]]; then
: # Already configured
elif [[ -d "$(dirname "$SYMLINK_PATH")" ]]; then
rm -f "$SYMLINK_PATH"
if ln -s "$SCRIPT_PATH" "$SYMLINK_PATH" 2>/dev/null; then
: # Symlink created
fi
fi
return 0
}
log_message() {
local level="$1"
local message="$2"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[${timestamp}] [${level}] ${message}" >> "${LOG_FILE}"
}
print_success() {
echo -e "${GREEN}✓ $1${NC}"
}
print_error() {
echo -e "${RED}✗ $1${NC}"
}
print_warning() {
echo -e "${YELLOW}⚠ $1${NC}"
}
print_info() {
echo -e "${BLUE}ℹ $1${NC}"
}
check_root() {
if [[ $EUID -ne 0 ]]; then
print_error "This script must be run as root (use sudo)"
exit 1
fi
}
check_dependencies() {
local deps=("curl" "wget" "jq" "cron")
local missing=()
for dep in "${deps[@]}"; do
if ! command -v "$dep" &> /dev/null; then
missing+=("$dep")
fi
done
if [[ ${#missing[@]} -gt 0 ]]; then
print_warning "Missing dependencies: ${missing[*]}"
print_info "Installing dependencies..."
apt-get update -qq
apt-get install -y -qq curl wget jq cron
print_success "Dependencies installed"
else
print_success "All dependencies are installed"
fi
}
send_telegram_notification() {
local message="$1"
if [[ -f "${CONFIG_FILE}" ]]; then
source "${CONFIG_FILE}"
fi
if [[ -z "${TELEGRAM_BOT_TOKEN}" ]] || [[ -z "${TELEGRAM_CHAT_ID}" ]]; then
return 0
fi
local api_url="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage"
local data="chat_id=${TELEGRAM_CHAT_ID}&text=${message}&parse_mode=HTML"
if [[ -n "${TELEGRAM_THREAD_ID}" ]] && [[ "${TELEGRAM_THREAD_ID}" != "0" ]]; then
data="${data}&message_thread_id=${TELEGRAM_THREAD_ID}"
fi
local response=$(curl -s -X POST "${api_url}" -d "${data}" 2>/dev/null)
if echo "$response" | jq -e '.ok == true' > /dev/null 2>&1; then
log_message "INFO" "Telegram notification sent successfully"
return 0
else
log_message "ERROR" "Failed to send Telegram notification: ${response}"
return 1
fi
}
test_telegram() {
local test_message="🔔 <b>Ruleset Fetcher</b>%0A%0A✅ Test notification successful!%0A%0A📅 $(date '+%Y-%m-%d %H:%M:%S')"
if send_telegram_notification "${test_message}"; then
print_success "Telegram test message sent successfully!"
else
print_error "Failed to send Telegram test message"
fi
}
create_config_dir() {
if [[ ! -d "${CONFIG_DIR}" ]]; then
mkdir -p "${CONFIG_DIR}"
chmod 755 "${CONFIG_DIR}"
print_success "Created config directory: ${CONFIG_DIR}"
fi
}
load_config() {
if [[ -f "${CONFIG_FILE}" ]]; then
source "${CONFIG_FILE}"
return 0
fi
return 1
}
save_config() {
cat > "${CONFIG_FILE}" << EOF
# Ruleset Fetcher Configuration
# Generated on $(date '+%Y-%m-%d %H:%M:%S')
# Download directory for rule-set files
DOWNLOAD_DIR="${DOWNLOAD_DIR}"
# Update interval in hours
UPDATE_INTERVAL="${UPDATE_INTERVAL}"
# Telegram Bot Token (from @BotFather)
TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN}"
# Telegram Chat ID (user ID, group ID, or channel ID)
TELEGRAM_CHAT_ID="${TELEGRAM_CHAT_ID}"
# Telegram Thread/Topic ID (optional, for forum groups)
# Set to 0 or leave empty for direct messages
TELEGRAM_THREAD_ID="${TELEGRAM_THREAD_ID}"
# Enable Telegram notifications (true/false)
TELEGRAM_ENABLED="${TELEGRAM_ENABLED}"
# GitHub token for private repositories and release assets
GITHUB_ACCESS_TOKEN="${GITHUB_ACCESS_TOKEN}"
EOF
chmod 600 "${CONFIG_FILE}"
print_success "Configuration saved to ${CONFIG_FILE}"
}
save_urls() {
printf '%s\n' "${URLS[@]}" > "${URLS_FILE}"
chmod 644 "${URLS_FILE}"
print_success "URLs saved to ${URLS_FILE}"
}
load_urls() {
URLS=()
if [[ -f "${URLS_FILE}" ]]; then
while IFS= read -r line || [[ -n "$line" ]]; do
[[ -n "$line" ]] && URLS+=("$line")
done < "${URLS_FILE}"
fi
}
get_url_basename() {
local url="${1%%\?*}"
basename "${url}"
}
is_github_url() {
local url="$1"
[[ "${url}" =~ ^https://(api\.github\.com|github\.com|raw\.githubusercontent\.com)/ ]]
}
is_github_release_asset_url() {
local url="$1"
[[ "${url}" =~ ^https://api\.github\.com/repos/[^/]+/[^/]+/releases/assets/[0-9]+([/?].*)?$ ]]
}
get_github_token() {
if [[ -n "${RULESET_FETCHER_GITHUB_TOKEN:-}" ]]; then
echo "${RULESET_FETCHER_GITHUB_TOKEN}"
elif [[ -n "${RF_GITHUB_TOKEN:-}" ]]; then
echo "${RF_GITHUB_TOKEN}"
elif [[ -n "${GITHUB_TOKEN:-}" ]]; then
echo "${GITHUB_TOKEN}"
else
echo "${GITHUB_ACCESS_TOKEN:-}"
fi
}
download_github_release_asset() {
local url="$1"
local dest_dir="$2"
local github_token
github_token="$(get_github_token)"
local metadata_headers=(-H "Accept: application/vnd.github+json")
local download_headers=(-H "Accept: application/octet-stream")
if [[ -n "${github_token}" ]]; then
metadata_headers+=(-H "Authorization: Bearer ${github_token}")
download_headers+=(-H "Authorization: Bearer ${github_token}")
fi
local metadata
metadata=$(curl -fsSL --connect-timeout 30 --max-time 120 \
"${metadata_headers[@]}" \
"${url}" 2>/dev/null) || {
if [[ -z "${github_token}" ]]; then
log_message "ERROR" "GitHub release asset metadata request failed. Configure a GitHub token if the repository is private: ${url}"
fi
return 1
}
local filename
filename=$(printf '%s' "${metadata}" | jq -r '.name // empty' 2>/dev/null)
filename="${filename##*/}"
if [[ -z "${filename}" ]]; then
log_message "ERROR" "Failed to resolve GitHub asset filename for ${url}"
return 1
fi
local dest_path="${dest_dir}/${filename}"
local temp_path="${dest_path}.tmp"
mkdir -p "${dest_dir}"
if curl -fsSL --connect-timeout 30 --max-time 300 \
"${download_headers[@]}" \
-o "${temp_path}" "${url}" 2>/dev/null; then
mv "${temp_path}" "${dest_path}"
chmod 644 "${dest_path}"
echo "${filename}"
return 0
fi
if [[ -z "${github_token}" ]]; then
log_message "ERROR" "GitHub release asset download failed. Configure a GitHub token if the repository is private: ${url}"
fi
rm -f "${temp_path}" 2>/dev/null
return 1
}
download_file() {
local url="$1"
local dest_dir="$2"
local filename
filename="$(get_url_basename "${url}")"
local dest_path="${dest_dir}/${filename}"
local temp_path="${dest_path}.tmp"
local github_token
github_token="$(get_github_token)"
local curl_args=(
-fsSL
--connect-timeout 30
--max-time 120
-o "${temp_path}"
)
if is_github_release_asset_url "${url}"; then
download_github_release_asset "${url}" "${dest_dir}"
return $?
fi
if is_github_url "${url}" && [[ -n "${github_token}" ]]; then
curl_args+=(-H "Authorization: Bearer ${github_token}")
fi
mkdir -p "${dest_dir}"
if curl "${curl_args[@]}" "${url}" 2>/dev/null; then
mv "${temp_path}" "${dest_path}"
chmod 644 "${dest_path}"
echo "${filename}"
return 0
else
rm -f "${temp_path}" 2>/dev/null
return 1
fi
}
download_all_files() {
local silent_mode="${1:-false}"
if [[ ! -f "${CONFIG_FILE}" ]]; then
print_error "Configuration not found. Please run setup first."
return 1
fi
load_config
load_urls
if [[ ${#URLS[@]} -eq 0 ]]; then
print_error "No URLs configured. Please add URLs first."
return 1
fi
local success_count=0
local fail_count=0
local success_files=()
local failed_files=()
local start_time=$(date +%s)
[[ "$silent_mode" != "true" ]] && print_info "Starting download of ${#URLS[@]} file(s)..."
[[ "$silent_mode" != "true" ]] && echo ""
for url in "${URLS[@]}"; do
local filename
filename="$(get_url_basename "${url}")"
[[ "$silent_mode" != "true" ]] && echo -n " Downloading ${filename}... "
if result=$(download_file "$url" "$DOWNLOAD_DIR"); then
local downloaded_name="${result:-${filename}}"
((success_count++))
success_files+=("${downloaded_name}")
[[ "$silent_mode" != "true" ]] && print_success "OK"
log_message "INFO" "Downloaded: ${downloaded_name}"
else
((fail_count++))
failed_files+=("$filename")
[[ "$silent_mode" != "true" ]] && print_error "FAILED"
log_message "ERROR" "Failed to download: ${filename} from ${url}"
fi
done
local end_time=$(date +%s)
local duration=$((end_time - start_time))
[[ "$silent_mode" != "true" ]] && echo ""
[[ "$silent_mode" != "true" ]] && print_info "Download complete: ${success_count} succeeded, ${fail_count} failed (${duration}s)"
log_message "INFO" "Download batch complete: ${success_count} succeeded, ${fail_count} failed"
if [[ "${TELEGRAM_ENABLED}" == "true" ]]; then
local status_emoji="✅"
local status_text="successful"
if [[ $fail_count -gt 0 ]]; then
if [[ $success_count -eq 0 ]]; then
status_emoji="❌"
status_text="failed"
else
status_emoji="⚠️"
status_text="partial"
fi
fi
local message="🔄 <b>Ruleset Fetcher Update</b>%0A%0A"
message+="${status_emoji} Status: ${status_text}%0A"
message+="📊 Results: ${success_count}/${#URLS[@]} files%0A"
message+="⏱ Duration: ${duration}s%0A"
message+="📅 $(date '+%Y-%m-%d %H:%M:%S')%0A"
if [[ ${#success_files[@]} -gt 0 ]]; then
message+="%0A✅ <b>Downloaded:</b>%0A"
for f in "${success_files[@]}"; do
message+=" • ${f}%0A"
done
fi
if [[ ${#failed_files[@]} -gt 0 ]]; then
message+="%0A❌ <b>Failed:</b>%0A"
for f in "${failed_files[@]}"; do
message+=" • ${f}%0A"
done
fi
send_telegram_notification "${message}"
fi
return $fail_count
}
# Cron job marker to identify our entries
CRON_MARKER="# ruleset-fetcher-auto-update"
install_cron_job() {
local interval_hours="$1"
# Remove existing cron job if any
remove_cron_job 2>/dev/null || true
# Create cron expression based on interval
local cron_expr
case "$interval_hours" in
1) cron_expr="0 * * * *" ;; # Every hour
3) cron_expr="0 */3 * * *" ;; # Every 3 hours
6) cron_expr="0 */6 * * *" ;; # Every 6 hours
12) cron_expr="0 */12 * * *" ;; # Every 12 hours
24) cron_expr="0 0 * * *" ;; # Daily at midnight
*) cron_expr="0 */${interval_hours} * * *" ;; # Custom interval
esac
# Get existing crontab or start with empty
local existing_cron
existing_cron=$(crontab -l 2>/dev/null) || existing_cron=""
# Add new cron job with marker
local new_cron_line="${cron_expr} ${SCRIPT_PATH} --update >/dev/null 2>&1 ${CRON_MARKER}"
if [[ -z "$existing_cron" ]]; then
echo "$new_cron_line" | crontab -
else
printf '%s\n%s\n' "$existing_cron" "$new_cron_line" | crontab -
fi
print_success "Cron job installed"
print_info "Files will be updated every ${interval_hours} hour(s)"
}
remove_cron_job() {
local existing_cron
existing_cron=$(crontab -l 2>/dev/null) || existing_cron=""
if [[ -z "$existing_cron" ]]; then
print_info "No crontab exists"
return 0
fi
# Only remove lines with our specific marker
local new_cron
new_cron=$(echo "$existing_cron" | grep -v "$CRON_MARKER" || true)
if [[ -z "$new_cron" ]]; then
crontab -r 2>/dev/null || true
else
echo "$new_cron" | crontab -
fi
print_success "Cron job removed"
}
show_cron_status() {
local cron_line
cron_line=$(crontab -l 2>/dev/null | grep "$CRON_MARKER" || true)
if [[ -n "$cron_line" ]]; then
print_success "Auto-update cron job is ACTIVE"
echo ""
# Show without the marker for cleaner display
echo " Schedule: ${cron_line% $CRON_MARKER}"
else
print_warning "Auto-update cron job is NOT active"
fi
}
setup_download_directory() {
echo ""
print_info "Step 1: Configure Download Directory"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
local default_dir="${CONFIG_DIR}"
echo -e "Download directory for rule-set files."
echo -e "Default: ${BOLD}${default_dir}${NC}"
echo ""
read -p "Enter download directory [press Enter for default]: " input_dir
DOWNLOAD_DIR="${input_dir:-$default_dir}"
if [[ ! -d "${DOWNLOAD_DIR}" ]]; then
mkdir -p "${DOWNLOAD_DIR}"
chmod 755 "${DOWNLOAD_DIR}"
print_success "Created directory: ${DOWNLOAD_DIR}"
else
print_success "Using existing directory: ${DOWNLOAD_DIR}"
fi
}
setup_urls() {
echo ""
print_info "Step 2: Configure Download URLs"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Enter the URLs of files to download (one per line)."
echo "Example: https://github.com/MetaCubeX/meta-rules-dat/raw/meta/geo/geosite/discord.mrs"
echo ""
echo "Press Enter when done."
echo ""
URLS=()
while true; do
read -r -p "URL: " url || true
if [[ -z "$url" ]]; then
break
fi
if [[ "$url" =~ ^https?:// ]]; then
URLS+=("$url")
print_success "Added: $(get_url_basename "$url")"
else
print_warning "Invalid URL format, skipping: $url"
fi
done
if [[ ${#URLS[@]} -eq 0 ]]; then
print_warning "No URLs added. You can add them later."
else
print_success "Added ${#URLS[@]} URL(s)"
fi
}
setup_update_interval() {
echo ""
print_info "Step 6: Configure Auto-Update Interval"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "How often should files be updated?"
echo " 1) Every 1 hour"
echo " 2) Every 3 hours"
echo " 3) Every 6 hours"
echo " 4) Every 12 hours"
echo " 5) Every 24 hours (daily)"
echo " 6) Custom interval"
echo ""
read -p "Select option [3]: " interval_option
interval_option="${interval_option:-3}"
case "$interval_option" in
1) UPDATE_INTERVAL=1 ;;
2) UPDATE_INTERVAL=3 ;;
3) UPDATE_INTERVAL=6 ;;
4) UPDATE_INTERVAL=12 ;;
5) UPDATE_INTERVAL=24 ;;
6)
read -p "Enter custom interval in hours: " custom_interval
UPDATE_INTERVAL="${custom_interval:-6}"
;;
*) UPDATE_INTERVAL=6 ;;
esac
print_success "Update interval set to ${UPDATE_INTERVAL} hour(s)"
}
setup_github_access() {
echo ""
print_info "Step 3: Configure GitHub Access"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Optional: add a GitHub token to download from private repositories."
echo "Also supports GitHub release asset API URLs like:"
echo " https://api.github.com/repos/<OWNER>/<REPO>/releases/assets/<ASSET_ID>"
echo ""
if [[ -n "$(get_github_token)" ]]; then
print_success "A GitHub token is already configured"
else
print_info "No GitHub token configured. Public URLs will still work."
fi
read -p "Set or update GitHub token now? (y/n) [n]: " configure_github
configure_github="${configure_github:-n}"
if [[ "${configure_github}" =~ ^[Yy]$ ]]; then
read -rsp "Enter GitHub token: " GITHUB_ACCESS_TOKEN
echo ""
if [[ -n "${GITHUB_ACCESS_TOKEN}" ]]; then
print_success "GitHub token saved"
else
print_warning "Empty token entered. Saved token cleared."
fi
fi
}
setup_telegram() {
echo ""
print_info "Step 5: Configure Telegram Notifications"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
read -p "Enable Telegram notifications? (y/n) [y]: " enable_tg
enable_tg="${enable_tg:-y}"
if [[ "$enable_tg" =~ ^[Yy]$ ]]; then
TELEGRAM_ENABLED="true"
echo ""
echo "To set up Telegram notifications:"
echo " 1. Create a bot with @BotFather and get the bot token"
echo " 2. Get your chat ID from @userinfobot or @getidsbot"
echo " 3. For groups/channels, add the bot and get the group ID"
echo " 4. For forum groups with topics, get the thread ID"
echo ""
read -p "Enter Bot Token: " TELEGRAM_BOT_TOKEN
read -p "Enter Chat ID: " TELEGRAM_CHAT_ID
echo ""
echo "For forum groups with topics/threads:"
read -p "Enter Thread ID (press Enter for direct messages): " TELEGRAM_THREAD_ID
TELEGRAM_THREAD_ID="${TELEGRAM_THREAD_ID:-0}"
if [[ -n "$TELEGRAM_BOT_TOKEN" ]] && [[ -n "$TELEGRAM_CHAT_ID" ]]; then
echo ""
read -p "Send test notification? (y/n) [y]: " send_test
send_test="${send_test:-y}"
if [[ "$send_test" =~ ^[Yy]$ ]]; then
save_config
test_telegram
fi
fi
else
TELEGRAM_ENABLED="false"
TELEGRAM_BOT_TOKEN=""
TELEGRAM_CHAT_ID=""
TELEGRAM_THREAD_ID="0"
print_info "Telegram notifications disabled"
fi
}
run_setup() {
# Respect RF_NO_CLEAR environment variable: if set, skip clearing the terminal before setup.
if [[ -t 0 && -z "${RF_NO_CLEAR:-}" ]]; then
clear
fi
print_banner
check_root
check_dependencies
create_config_dir
echo ""
print_info "Starting Setup Wizard..."
echo ""
# Step 1: Download Directory
setup_download_directory
# Step 2: URLs
setup_urls
# Step 3: GitHub access
setup_github_access
# Step 4: Review URLs and download
if [[ ${#URLS[@]} -gt 0 ]]; then
echo ""
print_info "Step 4: Review URLs"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "You have added ${#URLS[@]} URL(s):"
echo ""
local i=1
for url in "${URLS[@]}"; do
echo " ${i}) $(get_url_basename "$url")"
((i++))
done
echo ""
while true; do
read -p "Do you want to modify the list? (y/n) [n]: " modify_urls
modify_urls="${modify_urls:-n}"
if [[ "$modify_urls" =~ ^[Yy]$ ]]; then
echo ""
echo " 1) Add more URLs"
echo " 2) Remove a URL"
echo " 3) Clear all and re-enter"
echo " 0) Done editing"
echo ""
read -p "Select option: " edit_option
case "$edit_option" in
1)
echo ""
echo "Enter additional URLs (press Enter twice when done):"
while true; do
read -p "URL: " url
if [[ -z "$url" ]]; then
break
fi
if [[ "$url" =~ ^https?:// ]]; then
URLS+=("$url")
print_success "Added: $(get_url_basename "$url")"
else
print_warning "Invalid URL format, skipping"
fi
done
;;
2)
if [[ ${#URLS[@]} -eq 0 ]]; then
print_warning "No URLs to remove"
else
echo ""
local j=1
for url in "${URLS[@]}"; do
echo " ${j}) $(get_url_basename "$url")"
((j++))
done
echo ""
read -p "Enter number to remove: " remove_num
if [[ "$remove_num" =~ ^[0-9]+$ ]] && [[ $remove_num -ge 1 ]] && [[ $remove_num -le ${#URLS[@]} ]]; then
unset 'URLS[$((remove_num-1))]'
URLS=("${URLS[@]}")
print_success "URL removed"
else
print_error "Invalid selection"
fi
fi
;;
3)
URLS=()
print_info "All URLs cleared. Enter new URLs:"
setup_urls
;;
0|"")
break
;;
esac
# Show updated list
if [[ ${#URLS[@]} -gt 0 ]]; then
echo ""
echo "Current URLs (${#URLS[@]} total):"
local k=1
for url in "${URLS[@]}"; do
echo " ${k}) $(get_url_basename "$url")"
((k++))
done
fi
else
break
fi
done
# Ask to download now
echo ""
read -p "Download files now? (y/n) [y]: " download_now
download_now="${download_now:-y}"
if [[ "$download_now" =~ ^[Yy]$ ]]; then
save_config
save_urls
echo ""
download_all_files
fi
fi
# Step 5: Telegram
echo ""
read -p "Do you want to configure Telegram notifications now? (y/n) [n]: " setup_tg_now
setup_tg_now="${setup_tg_now:-n}"
if [[ "$setup_tg_now" =~ ^[Yy]$ ]]; then
setup_telegram
else
TELEGRAM_ENABLED="false"
TELEGRAM_BOT_TOKEN=""
TELEGRAM_CHAT_ID=""
TELEGRAM_THREAD_ID="0"
print_info "Telegram notifications skipped. You can configure later from the menu."
fi
# Step 6: Update interval
setup_update_interval
save_config
save_urls
if [[ "$(readlink -f "$0")" != "${SCRIPT_PATH}" ]]; then
cp "$(readlink -f "$0")" "${SCRIPT_PATH}"
chmod +x "${SCRIPT_PATH}"
print_success "Script installed to ${SCRIPT_PATH}"
fi
setup_symlink
install_cron_job "${UPDATE_INTERVAL}"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
print_success "Setup complete!"
echo ""
echo "Quick access commands:"
echo " ${BOLD}ruleset-fetcher${NC} - Full command"
echo " ${BOLD}rfetcher${NC} - Short alias"
echo ""
echo "Files are saved to: ${DOWNLOAD_DIR}"
echo "Auto-update every: ${UPDATE_INTERVAL} hour(s)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
read -p "Press Enter to continue..."
}
add_url() {
load_urls
echo ""
read -p "Enter URL to add: " new_url
if [[ -z "$new_url" ]]; then
print_error "No URL provided"
return 1
fi
if [[ ! "$new_url" =~ ^https?:// ]]; then
print_error "Invalid URL format"
return 1
fi
for url in "${URLS[@]}"; do
if [[ "$url" == "$new_url" ]]; then
print_warning "URL already exists"
return 1
fi
done
URLS+=("$new_url")
save_urls
print_success "Added: $(get_url_basename "$new_url")"
}
remove_url() {
load_urls
if [[ ${#URLS[@]} -eq 0 ]]; then
print_error "No URLs configured"
return 1
fi
echo ""
echo "Current URLs:"
local i=1
for url in "${URLS[@]}"; do
echo " ${i}) $(get_url_basename "$url")"
((i++))
done
echo ""
read -p "Enter number to remove (or 'all' to remove all): " selection
if [[ "$selection" == "all" ]]; then
URLS=()
save_urls
print_success "All URLs removed"
elif [[ "$selection" =~ ^[0-9]+$ ]] && [[ $selection -ge 1 ]] && [[ $selection -le ${#URLS[@]} ]]; then
local removed="${URLS[$((selection-1))]}"
unset 'URLS[$((selection-1))]'
URLS=("${URLS[@]}")
save_urls
print_success "Removed: $(get_url_basename "$removed")"
else
print_error "Invalid selection"
return 1
fi
}
list_urls() {
load_urls
if [[ ${#URLS[@]} -eq 0 ]]; then
print_warning "No URLs configured"
return 0
fi
echo ""
print_info "Configured URLs (${#URLS[@]} total):"
echo ""
local i=1
for url in "${URLS[@]}"; do
echo " ${i}) $(get_url_basename "$url")"
echo " ${url}"
((i++))
done
echo ""
}
show_status() {
print_banner
echo "Configuration"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if load_config; then
echo " Download Directory: ${DOWNLOAD_DIR}"
echo " Update Interval: ${UPDATE_INTERVAL} hour(s)"
if [[ -n "$(get_github_token)" ]]; then
echo " GitHub Token: configured"
else
echo " GitHub Token: not configured"
fi
echo " Telegram Enabled: ${TELEGRAM_ENABLED}"
load_urls
echo " Configured URLs: ${#URLS[@]}"
# Show files in directory (exclude config files)
if [[ -d "${DOWNLOAD_DIR}" ]]; then
local file_count=$(find "${DOWNLOAD_DIR}" -maxdepth 1 -type f \
! -name "$(basename "${CONFIG_FILE}")" \
! -name "$(basename "${URLS_FILE}")" \
! -name "$(basename "${LOG_FILE}")" 2>/dev/null | wc -l)
echo " Downloaded Files: ${file_count}"
fi
else
print_warning "Not configured. Run with --setup to configure."
fi
echo ""
echo "Cron Status"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
show_cron_status
echo ""
echo "Recent Logs"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [[ -f "${LOG_FILE}" ]]; then
tail -10 "${LOG_FILE}"
else
echo " No logs yet"
fi
}
get_remote_version() {
local remote_script
remote_script=$(curl -fsSL --connect-timeout 10 --max-time 30 "${GITHUB_RAW_URL}" 2>/dev/null) || return 1
# Extract VERSION= line robustly, allowing spaces and single/double quotes.
# Examples handled:
# VERSION="1.2.3"
# VERSION = '1.2.3'
# VERSION=1.2.3
local version
version=$(printf '%s\n' "$remote_script" \
| sed -nE "s/^[[:space:]]*VERSION[[:space:]]*=[[:space:]]*['\"]?([^[:space:]'\"]+)['\"]?.*/\1/p" \
| head -n1)
# Validate that a version was found