-
Notifications
You must be signed in to change notification settings - Fork 16
/
ishare2
executable file
·2672 lines (2349 loc) · 93.6 KB
/
ishare2
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
# Initial release date: October 2022
# Authors: @mativ00 & @sudoalx on Telegram
# Description: This bash script was created to automate the installation of images hosted on labhub.eu.org
# Version: 3.5.8-main
# Last Updated: 2024-08-08 yyyy-mm-dd
# Default ishare2 configuration: this configuration will be overwritten when defined in the configuration file.
USE_ARIA2C=false # Set to true to use aria2c for faster downloads. Set to false to use wget instead.
SSL_CHECK="true" # Set to true to check SSL certificate. Set to false to disable SSL certificate check.
CHANNEL="main" # Set to main to use the main channel. Set to main to use the main channel.
MIRRORS=("https://raw.githubusercontent.com/ishare2-org/mirrors/main/index.gd.json" "https://raw.githubusercontent.com/ishare2-org/mirrors/main/index.od.json") # List of mirrors
JSON_URL=${MIRRORS[0]} # Set to the default mirror
# End of ishare2 configuration
# Initialize variables
ISHARE2_DIR="/opt/ishare2/cli" # ishare2 directory
LOG_FILE="$ISHARE2_DIR/ishare2.log" # Log file
TEMP_JSON="$ISHARE2_DIR/index.json" # Temporary JSON file
VERSION="3.5.8-main" # Current version of ishare2
SOURCES_URL="https://raw.githubusercontent.com/ishare2-org/ishare2-cli/$CHANNEL/sources.list" # Sources.list URL
MOTD_FILE="$ISHARE2_DIR/motd.json" # MOTD file
REMOTE_MOTD_URL="https://raw.githubusercontent.com/ishare2-org/ishare2-cli/$CHANNEL/motd.json" # Remote MOTD URL
# Colors
RED='\033[31m'
YELLOW='\033[1;33m'
GREEN='\033[32m'
BLUE='\033[34m'
NO_COLOR='\033[0m'
# Script name
SCR_NAME_EXEC=$0
SCR_NAME_EXEC_FP=$(realpath "$0")
SCR_NAME=$(basename "$SCR_NAME_EXEC")
SCR_NAME=${SCR_NAME%.*}
# Configuration file
ISHARE2_CONF_FILE=$ISHARE2_DIR/ishare2.conf
logger() {
local log_level=${1^^} # Convert log level to uppercase
shift # Remove log level from arguments
# Create LOG_FILE if it does not exist
if [[ ! -f "$LOG_FILE" ]]; then
touch "$LOG_FILE"
fi
# Ensure LOG_FILE is set and writable
if [[ -z "$LOG_FILE" ]]; then
echo "LOG_FILE is not set" >&2
return 1
elif [[ ! -w "$LOG_FILE" && ! -e "$LOG_FILE" ]]; then
echo "Cannot write to LOG_FILE: $LOG_FILE" >&2
# Attempt to create the log file
touch "$LOG_FILE" || return 1
# Attempt to fix the permissions
chmod 644 "$LOG_FILE" || return 1
return 1
fi
# Ensure SCR_NAME is set
if [[ -z "$SCR_NAME" ]]; then
SCR_NAME="UNKNOWN_SCRIPT"
fi
# Log the output to the log file
echo -e "[$log_level][$SCR_NAME] $(date '+%Y-%m-%d %H:%M:%S'): $*" >>"$LOG_FILE"
}
# Function to fetch the latest list of sources needed for ishare2
ishare2_sources() {
check_installed "curl"
# Check if the sources.list file exists in the ishare2 directory
if [ ! -f "$ISHARE2_DIR/sources.list" ]; then
# If the sources.list file is older than 1 day, backup the file and download the latest sources.list
if [ ! -f "$ISHARE2_DIR/sources.list" ] || [ $(find "$ISHARE2_DIR/sources.list" -mtime +1 -print) ]; then
# Backup the sources.list file
cp $ISHARE2_DIR/sources.list "$ISHARE2_DIR/sources.list.bak"
# Download the latest sources.list
curl -sL "$SOURCES_URL" >"$ISHARE2_DIR/sources.list"
# Check if the sources.list file was downloaded successfully
if [ $? -eq 0 ]; then
logger info "The sources.list file has been downloaded successfully."
else
logger error "Failed to download the sources.list file."
logger info "Restoring the backup sources.list file..."
# Restore the backup sources.list file
if [ -f "$ISHARE2_DIR/sources.list.bak" ]; then
cp "$ISHARE2_DIR/sources.list.bak" $ISHARE2_DIR/sources.list
logger info "The backup sources.list file has been restored."
echo -e "${RED}[-] Failed to download the sources.list file.${NO_COLOR}"
echo -e "${YELLOW}[!] Using the old sources.list file.${NO_COLOR}"
echo -e "${YELLOW}[!] Please check your internet connection and try again.${NO_COLOR}"
else
logger info "The backup sources.list file does not exist."
echo -e "${RED}[-] Failed to download the sources.list file.${NO_COLOR}"
echo -e "${YELLOW}[!] Please check your internet connection and try again.${NO_COLOR}"
exit 1
fi
fi
fi
fi
# Source the sources.list file
source $ISHARE2_DIR/sources.list
}
# Function to initialize motd checks
check_motd() {
# Fetch the latest MOTD from the remote source
fetch_latest_motd
# Check if the fetched MOTD is different from the current one
if motds_are_different; then
# Display the updated MOTD
show_motd
# Update the MOTD information
update_motd_info
else
logger info "MOTD is up to date. No changes were made."
if should_show_motd; then
# Display the current MOTD
show_motd
# Update the MOTD information
update_motd_info
fi
fi
}
# Function to check if the MOTD should be shown
should_show_motd() {
current_date=$(date +"%Y-%m-%d")
last_shown_date=$(jq -r '.last_shown_date' "$MOTD_FILE")
show_count=$(jq -r '.show_count' "$MOTD_FILE")
# Check if MOTD has not been shown today or shown less than 3 times
if [ "$current_date" != "$last_shown_date" ] || [ "$show_count" -lt 3 ]; then
return 0 # Show MOTD
else
return 1 # Do not show MOTD
fi
}
# Function to display the MOTD
show_motd() {
message=$(jq -r '.message' "$MOTD_FILE")
messages=(
"MOTD from the ishare2 team:"
"$message"
""
"Telegram: https://t.me/NetLabHub"
"Donate: https://buymeacoffee.com/sudoalex"
"GitHub: https://github.com/ishare2-org/ishare2-cli"
)
print_box "${messages[@]}"
}
# Function to update the MOTD information
update_motd_info() {
current_date=$(date +"%Y-%m-%d")
jq '.last_shown_date = $date | .show_count += 1' --arg date "$current_date" "$MOTD_FILE" >$ISHARE2_DIR/motd.tmp.json
times_shown=$(jq -r '.show_count' "$ISHARE2_DIR/motd.tmp.json")
logger info "MOTD has been shown $times_shown out of 3 times today."
mv $ISHARE2_DIR/motd.tmp.json "$MOTD_FILE"
}
# Function to fetch the latest MOTD from a remote source
fetch_latest_motd() {
if [ ! -f "$MOTD_FILE" ]; then
logger info "MOTD file does not exist. Fetching the latest MOTD from the remote source."
curl -s "$REMOTE_MOTD_URL" >$ISHARE2_DIR/motd.json
return
fi
curl -s "$REMOTE_MOTD_URL" >$ISHARE2_DIR/motd.tmp.json
# if curl failed then write custom message to motd file
if [ $? -ne 0 ]; then
echo -e "{\"message\":\"Failed to fetch the latest MOTD. Please check your internet connection.\"}" >$ISHARE2_DIR/motd.tmp.json
fi
}
# Function to compare the current MOTD with the fetched MOTD
motds_are_different() {
if [ ! -f "$MOTD_FILE" ] || [ ! -f "$ISHARE2_DIR/motd.tmp.json" ]; then
return 0
fi
local current_motd=$(jq -r '.message' "$MOTD_FILE")
local fetched_motd=$(jq -r '.message' "$ISHARE2_DIR/motd.tmp.json")
# Compare the current MOTD with the fetched MOTD
if [ "$current_motd" != "$fetched_motd" ]; then
mv $ISHARE2_DIR/motd.tmp.json "$MOTD_FILE"
fi
[ "$current_motd" != "$fetched_motd" ]
}
# Function to check if there is a new version of ishare2 available
check_updates() {
LATEST_VERSION=$(curl -sL https://raw.githubusercontent.com/ishare2-org/ishare2-cli/$CHANNEL/version)
# Check if the version file could be fetched successfully
if [ -z "$LATEST_VERSION" ]; then
echo -e "${RED}[-] Failed to fetch the latest version information. Please check your internet connection.${NO_COLOR}"
logger error "Failed to fetch the latest version information from: $LATEST_VERSION"
return
fi
if [[ $LATEST_VERSION != $VERSION ]]; then
# Make an array of messages
messages=(
"A newer version of ishare2 is available."
"Current version: $VERSION"
"Latest version: $LATEST_VERSION"
"Run: ishare2 upgrade to update to the latest version."
"See more methods to update on GitHub:"
"https://github.com/ishare2-org/ishare2-cli"
)
print_box "${messages[@]}"
fi
}
# Function to print a box-like component with adjusted width
print_box() {
messages=("$@")
# Split messages on line breaks and find the length of the longest line
max_length=0
IFS=$'\n' # Internal Field Separator set to newline for splitting
all_lines=() # Array to hold all lines of all messages
for message in "${messages[@]}"; do
# Split message into lines
readarray -t lines <<<"$message"
for line in "${lines[@]}"; do
all_lines+=("$line")
length=${#line}
if ((length > max_length)); then
max_length=$length
fi
done
done
IFS=$' \t\n' # Reset IFS to default
# Display information in a box-like component with adjusted width
echo -e "${YELLOW}┌$(printf '─%.0s' $(seq 1 $((max_length + 4))))┐${NO_COLOR}"
for line in "${all_lines[@]}"; do
printf "${YELLOW}│${NO_COLOR} %-$(($max_length + 2))s ${YELLOW}│${NO_COLOR}\n" "$line"
done
echo -e "${YELLOW}└$(printf '─%.0s' $(seq 1 $((max_length + 4))))┘${NO_COLOR}"
}
# Function to rotate among the available mirrors
rotate_mirrors() {
# Rotate mirrors
source $ISHARE2_CONF_FILE
# Create unset JSON_URL if it does not exist
if ! grep -q "JSON_URL" "$ISHARE2_CONF_FILE"; then
echo "JSON_URL=" >>"$ISHARE2_CONF_FILE"
fi
if [[ $ROTATE == true ]]; then
logger info "Rotating mirrors..."
if [[ $JSON_URL == ${MIRRORS[0]} ]]; then
logger info "Setting JSON_URL to ${MIRRORS[1]}"
JSON_URL=${MIRRORS[1]}
sed -i "s|JSON_URL=.*|JSON_URL=${MIRRORS[1]}|" "$ISHARE2_CONF_FILE"
elif [[ $JSON_URL == ${MIRRORS[1]} ]]; then
logger info "Setting JSON_URL to ${MIRRORS[0]}"
JSON_URL=${MIRRORS[0]}
sed -i "s|JSON_URL=.*|JSON_URL=${MIRRORS[0]}|" "$ISHARE2_CONF_FILE"
elif [[ -z $JSON_URL ]]; then # If JSON_URL is empty, set it to the first mirror
logger info "Setting JSON_URL to ${MIRRORS[0]}"
JSON_URL=${MIRRORS[0]}
sed -i "s|JSON_URL=.*|JSON_URL=${MIRRORS[0]}|" "$ISHARE2_CONF_FILE"
fi
fi
}
# Function to print a separator with a title
print_separator() {
local TITLE=$1
local WIDTH=${#TITLE}
local SEPARATOR=""
# Calculate the required number of '=' characters to create the separator
for ((i = 0; i < WIDTH + 8; i++)); do
SEPARATOR+="="
done
echo -e "${BLUE}$SEPARATOR${NO_COLOR}"
echo -e "\033[1;33m ${TITLE} \033[0m"
echo -e "${BLUE}$SEPARATOR${NO_COLOR}"
}
# Function to check if PNetLab is installed
is_pnetlab_installed() {
# Check if pnetlab is installed
data=$(mysql -uroot -ppnetlab -D pnetlab_db -e "SELECT control_value FROM control WHERE control_value>1;" 2>/dev/null)
data_array=("$data")
pnetlab_version=${data_array[1]}
if [[ -z $pnetlab_version ]]; then
echo -e "${YELLOW}[!] WARN: PNetLab was not found.${NO_COLOR}"
echo -e "${YELLOW}[!]${NO_COLOR} This script has only been tested on PNetLab. If you are not using PNetLab, you may encounter issues."
logger warn "PNetLab is not installed."
return 1
fi
return 0
}
# Function to initialize the ishare2 directory checks
check_ishare2_dir() {
# check if ishare2 directory exists otherwise create it
if [[ ! -d $ISHARE2_DIR ]]; then
create_ishare2_dir
fi
}
# Set max log file lines to 1000
set_max_log_lines() {
if [[ -f $LOG_FILE ]]; then
if [[ $(wc -l <"$LOG_FILE") -gt 1000 ]]; then
tail -n 1000 $LOG_FILE >$ISHARE2_DIR/tmp.txt
mv $ISHARE2_DIR/tmp.txt $LOG_FILE
fi
fi
}
create_default_conf() {
install_dependencies
# If the --init argument is passed, display a message to the user
messages=(
"The default configuration will be used. Feel free to modify it later"
"by running: ishare2 config"
"Press Enter to continue."
)
print_box "${messages[@]}"
read -n 1
# Write the default configuration to the configuration file
echo "USE_ARIA2C=false" >$ISHARE2_CONF_FILE
echo "SSL_CHECK=true" >>$ISHARE2_CONF_FILE
echo "CHANNEL=$CHANNEL" >>$ISHARE2_CONF_FILE
echo "ROTATE=true" >>$ISHARE2_CONF_FILE
echo "JSON_URL=${MIRRORS[0]}" >>$ISHARE2_CONF_FILE
# Display values used
messages=(
"Configuration values:"
"USE_ARIA2C: false"
"SSL_CHECK: true"
"CHANNEL: $CHANNEL"
"ROTATE: true"
)
print_box "${messages[@]}"
}
# Function to check if the configuration file exists, and validate it
check_config() {
# get first argument
local first_arg=$1
if [[ $first_arg == "--init" ]]; then
# check if ishare2 directory exists otherwise create it
check_ishare2_dir
# create default configuration
create_default_conf
return
fi
# check if config file exists
if [[ ! -f $ISHARE2_CONF_FILE ]]; then
create_config
fi
# check if config file is empty
if [[ ! -s $ISHARE2_CONF_FILE ]]; then
echo -e "${RED}[!] Configuration file is empty. Please configure ishare2.${NO_COLOR}"
create_config
fi
# check if config file is valid
validate_conf_file
}
# Function to create the configuration file
create_config() {
fix_repositories
clear
messages=(
"Welcome to the ishare2!"
"This script will guide you through the initial configuration process."
"But first, let's check if the required dependencies are installed."
)
print_box "${messages[@]}"
sleep 3
is_pnetlab_installed
# check if pnetlab is installed
if [[ -z $pnetlab_version ]]; then
logger warn "PNetLab is not installed."
else
echo -e "${GREEN}[+] PNetLab version: $pnetlab_version found.${NO_COLOR}"
check_pnetlab_sources
fi
echo -e "${BLUE}[*] Installing ishare2 dependencies...${NO_COLOR}"
MAX_RETRIES=3
retry_counter=0
while [[ $retry_counter -lt $MAX_RETRIES ]]; do
if install_dependencies; then
break
fi
echo -e "${RED}[-] Failed to install dependencies. Retrying...${NO_COLOR}"
logger error "Failed to install dependencies. Retrying..."
retry_counter=$((retry_counter + 1))
sleep 10
done
if [[ $retry_counter -eq $MAX_RETRIES ]]; then
MAX_RETRIES=3
retry_counter=0
while [[ $retry_counter -lt $MAX_RETRIES ]]; do
if check_pnetlab_sources; then
break
fi
echo -e "${RED}[-] Failed to replace pnetlab sources. Retrying...${NO_COLOR}"
logger error "Failed to replace PNetLab sources. Retrying..."
retry_counter=$((retry_counter + 1))
sleep 10
done
fi
logger info "Starting configuration wizard..."
# Create the configuration file
clear
messages=(
"Welcome to the ishare2 configuration wizard."
"- This wizard will guide you through the configuration process."
"- Press Enter to accept the default value."
"- You can modify the configuration later by running: ishare2 config."
"- Press Ctrl+C to cancel."
)
print_box "${messages[@]}"
sleep 3
# Ask whether to use aria2c or not
echo -e "${YELLOW}[+] Use aria2c for faster downloads? (default: no)${NO_COLOR}"
read -p "[+] (y/n): " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo -e "${YELLOW}[!] Using aria2c allows you to download files faster, however, many users reported having issues with it.\nTo disable it, run: ishare2 config and answer no to this question.${NO_COLOR}"
echo "USE_ARIA2C=true" >$ISHARE2_CONF_FILE
install_package "aria2"
read -n 1
else
echo "USE_ARIA2C=false" >$ISHARE2_CONF_FILE
fi
# Ask if SSL certificate should be checked
echo -e "${YELLOW}[+] Check SSL certificate? (default: yes)${NO_COLOR}"
read -p "[+] (y/n): " -r
case $REPLY in
[Nn])
SSL_CHECK=false
;;
*)
SSL_CHECK=true
;;
esac
echo "SSL_CHECK=\"$SSL_CHECK\"" >>$ISHARE2_CONF_FILE
echo -e "${YELLOW}[+] Choose the update channel.${NO_COLOR}"
# Get branches as an array instead of a single string with spaces
mapfile -t branches < <(curl -sL https://api.github.com/repos/ishare2-org/ishare2-cli/branches | jq -r '.[].name')
# Display branches with correct indexing
for ((i = 0; i < ${#branches[@]}; i++)); do
echo " $((i + 1))) ${branches[i]}"
done
# Ask the user to select a branch
local current_channel=$CHANNEL
read -p "[*] Enter the number of the branch you want to use (default: $CHANNEL): " -r
if [[ -z $REPLY ]]; then
echo -e "${YELLOW}[!] Using the default branch.${NO_COLOR}"
elif ! [[ $REPLY =~ ^[0-9]+$ ]] || ((REPLY < 1 || REPLY > ${#branches[@]})); then
echo -e "${RED}[!] Invalid input. Using the default branch.${NO_COLOR}"
else
CHANNEL=${branches[REPLY - 1]}
echo -e "${YELLOW}[!] Using the $CHANNEL branch.${NO_COLOR}"
echo -e "${YELLOW}[!] Running: ishare2 upgrade, will update ishare2 to the $CHANNEL branch.${NO_COLOR}"
fi
echo "CHANNEL=\"$CHANNEL\"" >>$ISHARE2_CONF_FILE
# Provisional mirror selection feature. Will be replaced with a better solution in the future.
# Ask if the user wants to use the default mirror, another mirror or a custom mirror
echo -e "${YELLOW}[+] Choose a mirror. (default: Rotate mirrors)${NO_COLOR}"
# Show list of mirrors
echo " 1) Rotate mirrors (recommended)"
echo " 2) Google Drive mirror"
echo " 3) Onedrive mirror"
echo " 4) Custom mirror"
# Ask the user to select a mirror
read -p "[*] Enter the number of the mirror you want to use (default: 1): " -r
case $REPLY in
2)
JSON_URL=${MIRRORS[0]}
echo -e "${YELLOW}[!] Using Google Drive mirror.${NO_COLOR}"
;;
3)
JSON_URL=${MIRRORS[1]}
echo -e "${YELLOW}[!] Using Onedrive mirror.${NO_COLOR}"
;;
4)
echo -e "${YELLOW}[+] Enter the URL of the mirror.${NO_COLOR}"
read -p "[*] Enter the URL of the mirror you want to use: " -r
JSON_URL="$REPLY"
echo -e "${YELLOW}[!] Using custom mirror: $JSON_URL.${NO_COLOR}"
;;
*)
echo -e "${YELLOW}[!] ishare2 will rotate among the available mirrors.${NO_COLOR}"
echo "ROTATE=true" >>$ISHARE2_CONF_FILE
;;
esac
echo "JSON_URL=\"$JSON_URL\"" >>$ISHARE2_CONF_FILE
# Validate the configuration file
if [ ! -f "$ISHARE2_CONF_FILE" ]; then
echo -e "${RED}[!] Failed to create configuration file. Please try again.${NO_COLOR}"
logger error "Failed to create configuration file."
exit 1
fi
remove_duplicates
validate_conf_file
sleep 1
clear
messages=(
"Configuration completed successfully."
"You can start using ishare2!"
"[!] IMPORTANT NOTICES:"
"- ishare2 is a free and open-source project. If you paid"
" for it, you have been scammed."
"- Do not download ishare2 from unofficial sources as they"
" may contain arbitrary code."
)
print_box "${messages[@]}"
# Update to the latest version on the selected channel
if [[ $current_channel != $CHANNEL ]]; then
echo -e "${YELLOW}[!] Installing the latest version of ishare2 on the $CHANNEL channel...${NO_COLOR}"
curl -sL https://raw.githubusercontent.com/ishare2-org/ishare2-cli/$CHANNEL/ishare2 >/usr/sbin/ishare2
chmod +x /usr/sbin/ishare2
echo -e "${GREEN}[+] ishare2 has been updated to the latest version on the $CHANNEL channel.${NO_COLOR}"
fi
}
# Function to remove duplicate lines from the configuration file
remove_duplicates() {
local config_file="$ISHARE2_CONF_FILE"
# Check if the configuration file exists
if [ ! -f "$config_file" ]; then
echo -e "${RED}[!] Configuration file does not exist.${NO_COLOR}"
logger error "Configuration file does not exist."
return
fi
# Remove duplicate lines from the configuration file
awk '!seen[$0]++' "$config_file" >"$config_file.tmp" && mv "$config_file.tmp" "$config_file"
logger info "Removed duplicate lines from the configuration file."
}
# Function to validate the configuration file
validate_conf_file() {
# Check if the configuration file exists
if [ ! -f "$ISHARE2_CONF_FILE" ]; then
echo -e "${RED}[!] Configuration file does not exist.${NO_COLOR}"
logger error "Configuration file does not exist."
return 1
fi
# Array of allowed variables
local allowed_vars=("USE_ARIA2C" "CHANNEL" "SSL_CHECK" "JSON_URL" "ROTATE" "MOTD")
# Read the configuration file line by line and filter out invalid variables
local filtered_content=""
while IFS= read -r line; do
# Skip empty lines and comments
if [[ -z "$line" || "$line" == \#* ]]; then
continue
fi
# Extract variable name by trimming leading and trailing whitespaces
local var_name="$(echo "$line" | awk -F '=' '{gsub(/^[ \t]+|[ \t]+$/, "", $1); print $1}')"
# Check if the variable is allowed
is_allowed=false
for allowed_var in "${allowed_vars[@]}"; do
if [[ "$allowed_var" == "$var_name" ]]; then
is_allowed=true
break
fi
done
if $is_allowed || [[ "$line" != *=* ]]; then
filtered_content+="$line"$'\n'
else
logger warn "Removed invalid variable \"$var_name\" from the configuration file."
fi
done <"$ISHARE2_CONF_FILE"
# Write the filtered content back to the configuration file
echo "$filtered_content" >"$ISHARE2_CONF_FILE"
logger info "Validated the configuration file."
# shellcheck source=/opt/ishare2/cli/ishare2.conf
source "$ISHARE2_CONF_FILE"
return 0
}
# Function to remove i-share.top apt sources.list
remove_ishare_sources() {
# Remove i-share.top line from sources.list
sed -i '/i-share.top/d' /etc/apt/sources.list
}
# Function to install dependencies required for ishare2
install_dependencies() {
remove_ishare_sources
echo -e "${YELLOW}[+] ishare2 needs to install some dependencies to work properly.${NO_COLOR}"
local packages=("curl" "wget" "jq" "unrar" "tree" "unzip")
echo -e "${YELLOW}[+] List of packages to be installed: ${NO_COLOR}"
for package in "${packages[@]}"; do
echo -e "${YELLOW} -${NO_COLOR} $package"
done
echo -e "${YELLOW}[+] Starting to install dependencies in 5 seconds... This may take a while. Press Ctrl+C to cancel.${NO_COLOR}"
sleep 5
for package in "${packages[@]}"; do
install_package "$package"
done
}
# Function to check if a package is installed and install it if it's not
check_installed() {
PACKAGE=$1
# Check if package is installed
if ! command -v "$PACKAGE" &>/dev/null; then
echo -e "${YELLOW}[!] WARN: $PACKAGE is not installed.${NO_COLOR}"
install_package "$PACKAGE"
# Check success of package installation
if ! command -v "$PACKAGE" &>/dev/null; then
echo -e "${RED}[-] Error: Failed to install $PACKAGE.${NO_COLOR}"
logger error "Failed to install $PACKAGE."
exit 1
else # package is installed
echo -e "${GREEN}[+] $PACKAGE has been installed successfully.${NO_COLOR}"
fi
fi
}
# Function to check if a site is accessible
is_site_accessible() {
local url=$1
if ! curl -s --head --request GET "$url" | grep "200 OK\|301 Moved Permanently" >/dev/null; then
return 1 # Site is not accessible
else
return 0 # Site is accessible
fi
}
# Function to check if the sources.list file is using the correct sources
fix_repositories() {
# Immediately check for http://repo.pnetlab.com and replace it with https if found
if grep -q "deb \[trusted=yes\] http://repo.pnetlab.com ./" /etc/apt/sources.list; then
echo -e "${YELLOW}[+] Found http://repo.pnetlab.com in sources.list, replacing with https...${NO_COLOR}"
sed -i 's|deb \[trusted=yes\] http://repo.pnetlab.com ./|deb [trusted=yes] https://repo.pnetlab.com ./|g' /etc/apt/sources.list
fi
# Check if https://repo.pnetlab.com is accessible
if ! is_site_accessible "https://repo.pnetlab.com"; then
echo -e "${YELLOW}[!] repo.pnetlab.com is not accessible.${NO_COLOR}"
echo -e "${YELLOW}[!] Checking alternative...${NO_COLOR}"
# The script previously modified any http to https if necessary, so just check for https existence now
if grep -q "deb \[trusted=yes\] https://repo.pnetlab.com ./" /etc/apt/sources.list; then
echo -e "${YELLOW}[!] Your sources.list is already using https for repo.pnetlab.com.${NO_COLOR}"
fi
# Check if https://pnetlab.labhub.eu.org is accessible
if ! is_site_accessible "https://pnetlab.labhub.eu.org"; then
echo -e "${RED}[-] Both repo.pnetlab.com and the alternative pnetlab.labhub.eu.org are inaccessible.${NO_COLOR}"
echo -e "${YELLOW}[!] Please check your internet connection and try again.${NO_COLOR}"
# Ask the user if they want to continue anyway
echo -e "${YELLOW}[?] Do you want to continue anyway?${NO_COLOR}"
read -p "[?] (y/n): " -r
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
fi
# Ask the user if they want to replace the sources
echo -e "${YELLOW}[!] The official pnetlab.com repository is not accessible.${NO_COLOR}"
echo -e "${YELLOW}[?] Do you want to replace the pnetlab sources with the LabHub mirror?${NO_COLOR}"
read -p "[?] (y/n): " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
# Comment out "deb [trusted=yes] https://repo.pnetlab.com ./" and add "deb [trusted=yes] https://pnetlab.labhub.eu.org ./"
echo -e "${YELLOW}[+] Replacing pnetlab sources with labhub mirror...${NO_COLOR}"
sed -i 's|deb \[trusted=yes\] https://repo.pnetlab.com ./|#deb \[trusted=yes\] https://repo.pnetlab.com ./|g' /etc/apt/sources.list
echo "deb [trusted=yes] https://pnetlab.labhub.eu.org ./" >>/etc/apt/sources.list
fi
else
echo -e "${GREEN}[+] repo.pnetlab.com is accessible.${NO_COLOR}"
# No further action needed if the site is accessible, assuming the earlier check already ensured https is used
fi
}
# Function to run apt-get update
apt_get_update() {
echo -e "${YELLOW}[+] Updating package lists...${NO_COLOR}"
if ! apt-get update -y -qq; then
return 1
fi
}
# Function to install a package
install_package() {
local package_name=$1
# check if $package_name is installed otherwise install it
if ! command -v "$package_name" &>/dev/null; then
echo -e "${YELLOW}[+] $package_name is not installed.${NO_COLOR}"
if ! apt_get_update; then
echo -e "${RED}[-] Failed to update package lists.${NO_COLOR}"
echo -e "${YELLOW}[!] Attempting to fix APT sources...${NO_COLOR}"
fix_repositories
if ! apt_get_update; then
echo -e "${RED}[-] Failed to fix APT sources.${NO_COLOR}"
logger error "Failed to fix APT sources."
exit 1
fi
fi
echo -e "${YELLOW}[+] Installing $package_name...${NO_COLOR}"
if ! apt-get install -qq -y "$package_name"; then
echo -e "${RED}[-] Failed to install $package_name. Please install it manually or you will likely encounter issues in the future.${NO_COLOR}"
echo -e "${YELLOW}[!] Run: apt-get install -y $package_name${NO_COLOR}"
logger error "Failed to install $package_name."
exit 1
fi
else
echo -e "${GREEN}[+] $package_name is already installed.${NO_COLOR}"
logger info "Package $package_name is already installed."
logger info "Updating $package_name..."
if ! apt-get install --only-upgrade -qq "$package_name"; then
logger error "Failed to update $package_name."
exit 1
fi
fi
}
# Function to check if APT or dpkg is running and unlock dpkg
unlock_dpkg() {
# Check if APT or dpkg is running
if pgrep -f '^[/]usr[/]bin[/](apt|dpkg)' >/dev/null 2>&1; then
echo "APT or dpkg seems to be running in the background."
echo -e "${YELLOW}[?] Do you want to unlock dpkg?${NO_COLOR}"
# Confirm with the user
echo -e "${YELLOW}[!] Warning: Unlocking dpkg while APT or dpkg processes are active can lead to a broken system.${NO_COLOR}"
echo "Proceed with caution. It's recommended to try this only if you're sure that no APT or dpkg processes are running."
echo "Proceed? (y/n)"
read -r answer
if [[ $answer != "y" && $answer != "Y" ]]; then
echo "Operation cancelled by the user."
fi
# Attempt to remove lock files
echo "Attempting to remove lock files..."
local lock_files=(
"/var/lib/dpkg/lock"
"/var/cache/apt/archives/lock"
"/var/lib/apt/lists/lock"
"/var/lib/dpkg/lock-frontend"
)
for file in "${lock_files[@]}"; do
if [ -f "$file" ]; then
sudo rm "$file" >/dev/null 2>&1
echo "Removed $file"
else
echo "$file does not exist or has already been removed."
fi
done
# Attempt to reconfigure dpkg
echo "Reconfiguring dpkg..."
sudo dpkg --configure -a
echo "Operation completed. Please try running your APT or dpkg command again."
fi
}
# Function to create the ishare2 directory
create_ishare2_dir() {
echo -e "${YELLOW}[!] Creating ishare2 directory...${NO_COLOR}"
if ! mkdir -p $ISHARE2_DIR 2>/dev/null; then
error_message=$(mkdir -p $ISHARE2_DIR 2>&1 >/dev/null)
if [[ $error_message == *"Permission denied"* ]]; then
echo -e "${RED}[-] Failed to create ishare2 directory: Permission denied.${NO_COLOR}"
else
echo -e "${RED}[-] Failed to create ishare2 directory. Error: $error_message${NO_COLOR}"
fi
exit 1
fi
logger info "ishare2 directory created successfully."
}
# Function to check image size against the downloaded image
check_image_size() {
local image_path=$1
local image_name=$2
local image_size_from_json=$3
# Check if the image file exists
if [ ! -f "$image_path$image_name" ]; then
echo -e "${RED}[-] Error: The image file does not exist.${NO_COLOR}"
logger error "The image file does not exist: $image_path$image_name"
exit 1
fi
# Get the size of the downloaded image
local image_size=$(stat -c%s "$image_path$image_name")
# Check if the image size is less than 20KB
if [ $image_size -lt 20000 ]; then
echo -e "${RED}[-] Error: The image file size is too small. The file may be corrupted.${NO_COLOR}"
logger error "The image file size is too small: $image_path$image_name. Expected size: $image_size_from_json. Actual size: $image_size"
exit 1
fi
# Check if the image size matches the size from the JSON file
if [ $image_size -ne $image_size_from_json ]; then
echo -e "${RED}[-] Error: The image file size does not match the size expected by the index.${NO_COLOR}"
echo -e "${RED}[!] Debug information:${NO_COLOR}"
echo -e "${YELLOW} Expected size: $image_size_from_json${NO_COLOR}"
echo -e "${YELLOW} Actual size: $image_size${NO_COLOR}"
echo -e "${YELLOW} JSON file URL: $JSON_URL${NO_COLOR}"
logger error "The image file size does not match the size from the JSON index: $image_path$image_name. Expected size: $image_size_from_json. Actual size: $image_size"
exit 1
fi
echo -e "${GREEN}[+] Basic integrity checks passed. The downloaded image is the expected size.${NO_COLOR}"
}
# Function to fetch JSON file with the list of files to download
fetch_json() {
check_installed "jq"
# Create a temporary directory
logger info "Downloading JSON file from $JSON_URL..."
curl -sL "$JSON_URL" -o "$TEMP_JSON"
# Check if the curl command failed
if [ $? -ne 0 ]; then
logger error "Failed to download the JSON file. From: $JSON_URL"
echo -e "${RED}[-] Failed to download the JSON index file. Check your internet connection.${NO_COLOR}"
echo -e "${YELLOW}[!] Running connection test to check your internet connection.${NO_COLOR}"
connection_tests
exit 1
fi
# Check if the JSON file is valid
if ! jq -e . >/dev/null 2>&1 <"$TEMP_JSON"; then
logger error "Error: Invalid JSON index file."
echo -e "${RED}[-] Error: Invalid JSON index file.${NO_COLOR}"
echo -e "${RED}[!] Debug information:${NO_COLOR}"
echo -e "${YELLOW} - JSON file URL: $JSON_URL${NO_COLOR}"
echo -e "${YELLOW} - JSON file location: $TEMP_JSON${NO_COLOR}"
echo -e "${RED}[!] Troubleshooting:${NO_COLOR}"
echo -e "${YELLOW} 1) Check if the JSON file is accessible through your web browser.${NO_COLOR}"
echo -e "${YELLOW} 2) If the issue persists, report the issue to the ishare2 team on Telegram: https://t.me/NetLabHub${NO_COLOR}"
exit 1
else
logger info "JSON file downloaded successfully."
fi
}
# Function to download a file using wget or aria2c
download_file() {
local url="$1"
local output="$2"
local options="$3"
USE_ARIA2C=$(grep "USE_ARIA2C" $ISHARE2_CONF_FILE | cut -d "=" -f2)
if [[ $USE_ARIA2C == "true" ]]; then
# Check if aria2c is installed
if ! command -v aria2c &>/dev/null; then
echo -e "${RED}[-] Error: aria2c is not installed. Attempting to install it...${NO_COLOR}"
install_package "aria2" >/dev/null
# Check if aria2c is installed
if ! command -v aria2c &>/dev/null; then
echo -e "${RED}[-] Error: aria2c is not installed. Please install it manually and try again.${NO_COLOR}"
exit 1
else # aria2c is installed
echo -e "${GREEN}[+] aria2c has been installed successfully.${NO_COLOR}"
fi
fi
fi
if command -v aria2c &>/dev/null && [[ $USE_ARIA2C == "true" ]]; then
download_file_aria2 "$url" "$output" "$options"
else
download_file_wget "$url" "$output" "$options"
fi
}
# Function to download a file using aria2c
download_file_aria2() {
local url="$1"
local output_dir="$2"
local output_name="$3"
logger info "Downloading file from $url..."
rm -f error.log
if [ "$SSL_CHECK" = true ]; then
aria2c --console-log-level=warn -j 2 -c --split=4 --min-split-size=20M --max-connection-per-server=4 --download-result=hide --allow-overwrite=true --dir="$output_dir" --out="$output_name" --log="error.log" "$url"
else
aria2c --console-log-level=warn -j 2 -c --split=4 --min-split-size=20M --max-connection-per-server=4 --download-result=hide --check-certificate=false --allow-overwrite=true --dir="$output_dir" --out="$output_name" --log="error.log" "$url"
fi
if [ $? -eq 0 ]; then
# line break
echo
echo -e "${YELLOW}[+] ${GREEN}The file has been downloaded successfully to $output_dir$output_name ${NO_COLOR}"
rm -f error.log
else
echo -e "${RED}[-] Error: Unable to download the file. Check the error.log file for more information.${NO_COLOR}"
exit 1
fi
# Check if file size is less than 20KB and its extension is not excluded
local excluded_extensions=("html" "txt" "php" "yml" "md" "json" "sh" "yaml" "txt")
if [ -f "$output_dir$output_name" ] && [ $(stat -c%s "$output_dir$output_name") -lt 20000 ]; then
is_excluded=false
for ext in "${excluded_extensions[@]}"; do
if [ "${output_name##*.}" = "$ext" ]; then
is_excluded=true
break
fi
done
if [ "$is_excluded" = false ]; then
echo -e "${RED}[-] The file size is too small. The file may be corrupted.${NO_COLOR}"
# Check if html file is downloaded instead of the actual file, key words: "DOCTYPE", "<html>", Bhadoo
if grep -q "DOCTYPE" "$output_dir$output_name" || grep -q "<html>" "$output_dir$output_name" || grep -q "Bhadoo" "$output_dir$output_name"; then
echo -e "${RED}[-] The file may be corrupted. The file may be an HTML file instead of the actual file.${NO_COLOR}"
fi
# Show troubleshooting steps
echo -e "${YELLOW}[!] Troubleshooting:${NO_COLOR}"
echo -e "${YELLOW}[!] 1) Switch mirrors, if you have mirrors rotation enabled then run the command again using the --overwrite flag.${NO_COLOR}"
echo -e "${YELLOW}[!] 2) If the issue persists, visit the live repository through your web browser and download the file manually.${NO_COLOR}"
echo -e "${YELLOW}[!] 3) If the issue persists, report the issue to the ishare2 team on Telegram.${NO_COLOR}"
fi
fi
}
# Function to download a file using curl
download_file_curl() { # $1 = url, $2 = output
# Create the directory if it does not exist
mkdir -p $ISHARE2_DIR/tmp
# Create the file if it does not exist
touch $ISHARE2_DIR/tmp/curl_error
local url="$1"
local output="$2"
logger info "Downloading file from $url..."
if [ "$SSL_CHECK" = true ]; then
curl -s -o "$output" "$url" 2>$ISHARE2_DIR/tmp/curl_error
else
curl -s --insecure -o "$output" "$url" 2>$ISHARE2_DIR/tmp/curl_error
fi
if [ $? -eq 0 ]; then
logger info "The file has been downloaded successfully to $output."
rm -f $ISHARE2_DIR/tmp/curl_error
else
echo -e "${RED}[-] Error: Unable to download the file. ${NO_COLOR}"
# Read the error message from the curl_error file
ERROR_MESSAGE=$(cat $ISHARE2_DIR/tmp/curl_error)
# Print the error message
echo -e "${RED}[-] Logs:\n $ERROR_MESSAGE ${NO_COLOR}"
exit 1
fi
}
# Function to download a file using wget
download_file_wget() {
# Create the directory if it does not exist
mkdir -p $ISHARE2_DIR/tmp
# Create the file if it does not exist
touch $ISHARE2_DIR/tmp/wget_error