forked from PierreGode/Ragnar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall_ragnar.sh
More file actions
executable file
·1865 lines (1635 loc) · 70.7 KB
/
install_ragnar.sh
File metadata and controls
executable file
·1865 lines (1635 loc) · 70.7 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
# ragnar Installation Script
# This script handles the complete installation of ragnar
# Author: infinition
# Version: 1.0 - 071124 - 0954
if [ -z "$BASH_VERSION" ]; then
exec /bin/bash "$0" "$@"
fi
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'
# Logging configuration
LOG_DIR="/var/log/ragnar_install"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/ragnar_install_$(date +%Y%m%d_%H%M%S).log"
VERBOSE=false
# Global variables
ragnar_USER="ragnar"
ragnar_PATH="/home/${ragnar_USER}/Ragnar"
CURRENT_STEP=0
TOTAL_STEPS=11
HEADLESS_MODE=false
HEADLESS_VARIANT=""
HEADLESS_VARIANT_LABEL=""
RAGNAR_ENTRYPOINT="Ragnar.py"
SERVER_INSTALL=false
TFT_MODE=false
# Platform detection variables
OS_ID=""
OS_VERSION_ID=""
OS_PRETTY=""
PKG_MGR=""
UPDATE_CMD=""
INSTALL_CMD=""
PKG_PRESENT_CMD=""
ARCH=""
IS_ARM=false
if [[ "$1" == "--help" ]]; then
echo "Usage: sudo ./install_ragnar.sh"
echo "Make sure you have the necessary permissions and that all dependencies are met."
exit 0
fi
# Function to display progress
show_progress() {
echo -e "${BLUE}Step $CURRENT_STEP of $TOTAL_STEPS: $1${NC}"
}
# Logging function
log() {
local level=$1
shift
local message="[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*"
echo -e "$message" >> "$LOG_FILE"
if [ "$VERBOSE" = true ] || [ "$level" != "DEBUG" ]; then
case $level in
"ERROR") echo -e "${RED}$message${NC}" ;;
"SUCCESS") echo -e "${GREEN}$message${NC}" ;;
"WARNING") echo -e "${YELLOW}$message${NC}" ;;
"INFO") echo -e "${BLUE}$message${NC}" ;;
*) echo -e "$message" ;;
esac
fi
}
# Error handling function
handle_error() {
local error_code=$?
local error_message=$1
log "ERROR" "An error occurred during: $error_message (Error code: $error_code)"
log "ERROR" "Check the log file for details: $LOG_FILE"
echo -e "\n${RED}Would you like to:"
echo "1. Retry this step"
echo "2. Skip this step (not recommended)"
echo "3. Exit installation${NC}"
read -r choice
case $choice in
1) return 1 ;; # Retry
2) return 0 ;; # Skip
3) clean_exit 1 ;; # Exit
*) handle_error "$error_message" ;; # Invalid choice
esac
}
# Function to check command success
check_success() {
if [ $? -eq 0 ]; then
log "SUCCESS" "$1"
return 0
else
handle_error "$1"
return $?
fi
}
# Detect OS, package manager, and hardware architecture
detect_platform() {
if [ -f "/etc/os-release" ]; then
# shellcheck source=/dev/null
. /etc/os-release
OS_ID=${ID:-unknown}
OS_VERSION_ID=${VERSION_ID:-unknown}
OS_PRETTY=${PRETTY_NAME:-$OS_ID}
else
OS_ID="unknown"
OS_VERSION_ID="unknown"
OS_PRETTY="unknown"
fi
ARCH=$(uname -m 2>/dev/null || echo "unknown")
case "$ARCH" in
arm*|aarch64) IS_ARM=true ;;
*) IS_ARM=false ;;
esac
case "$OS_ID" in
debian|ubuntu|raspbian)
PKG_MGR="apt"
UPDATE_CMD="apt-get update -y"
INSTALL_CMD="apt-get install -y"
PKG_PRESENT_CMD="dpkg -s"
;;
fedora|rhel|centos|rocky|almalinux)
PKG_MGR="dnf"
UPDATE_CMD="dnf makecache -y"
INSTALL_CMD="dnf install -y"
PKG_PRESENT_CMD="rpm -q"
;;
arch|manjaro|endeavouros)
PKG_MGR="pacman"
UPDATE_CMD="pacman -Sy --noconfirm"
INSTALL_CMD="pacman -S --noconfirm"
PKG_PRESENT_CMD="pacman -Qi"
;;
opensuse*|sles)
PKG_MGR="zypper"
UPDATE_CMD="zypper refresh"
INSTALL_CMD="zypper install -y"
PKG_PRESENT_CMD="rpm -q"
;;
*)
PKG_MGR="apt"
UPDATE_CMD="apt-get update -y"
INSTALL_CMD="apt-get install -y"
PKG_PRESENT_CMD="dpkg -s"
log "WARNING" "Unknown distro; defaulting to apt commands"
;;
esac
log "INFO" "Detected platform: ${OS_PRETTY} (id=${OS_ID}, version=${OS_VERSION_ID}), arch=${ARCH}, pkg_mgr=${PKG_MGR}"
}
# Print a concise system summary for visibility
log_system_summary() {
local cpu_model ram_mb disk_mb
cpu_model=$(grep -m1 "model name" /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')
ram_mb=$(free -m 2>/dev/null | awk '/^Mem:/{print $2}')
disk_mb=$(df -m /home 2>/dev/null | awk 'NR==2 {print $4}')
log "INFO" "System summary:" \
" OS=${OS_PRETTY:-unknown}" \
" Arch=${ARCH:-unknown}" \
" CPU=${cpu_model:-unknown}" \
" RAM=${ram_mb:-?}MB" \
" FreeDisk=${disk_mb:-?}MB (/home)"
}
# Provide package-name fallbacks across distros
package_candidates() {
local pkg=$1
case "$pkg" in
libopenjp2-7) echo "libopenjp2-7 openjpeg2 openjpeg" ;;
libopenblas-dev) echo "libopenblas-dev openblas-devel openblas" ;;
bluez-tools) echo "bluez-tools bluez-utils bluez-utils-compat" ;;
dhcpcd5) echo "dhcpcd5 dhcpcd" ;;
python3-pil) echo "python3-pil python3-pillow python-pillow pillow" ;;
libjpeg-dev) echo "libjpeg-dev libjpeg-turbo-devel libjpeg-turbo" ;;
libpng-dev) echo "libpng-dev libpng-devel" ;;
python3-dev) echo "python3-dev python3-devel" ;;
libffi-dev) echo "libffi-dev libffi-devel" ;;
libssl-dev) echo "libssl-dev openssl-devel" ;;
libgpiod-dev) echo "libgpiod-dev libgpiod-devel libgpiod" ;;
libi2c-dev) echo "libi2c-dev i2c-tools i2c-tools-devel" ;;
build-essential) echo "build-essential base-devel" ;;
python3-sqlalchemy) echo "python3-sqlalchemy python-sqlalchemy sqlalchemy" ;;
python3-pandas) echo "python3-pandas python-pandas pandas" ;;
python3-numpy) echo "python3-numpy python-numpy numpy" ;;
network-manager) echo "network-manager NetworkManager networkmanager" ;;
iproute2) echo "iproute2 iproute" ;;
iputils-ping) echo "iputils-ping iputils" ;;
libatlas-base-dev) echo "libatlas-base-dev atlas-devel" ;;
arp-scan) echo "arp-scan arpscan" ;;
bluez) echo "bluez" ;;
hostapd) echo "hostapd" ;;
dnsmasq) echo "dnsmasq" ;;
wireless-tools) echo "wireless-tools" ;;
bridge-utils) echo "bridge-utils" ;;
*) echo "$pkg" ;;
esac
}
# Install a package using detected package manager with fallbacks
install_package() {
local pkg=$1
local candidates
candidates=$(package_candidates "$pkg")
for candidate in $candidates; do
if [ -n "$PKG_PRESENT_CMD" ] && eval "$PKG_PRESENT_CMD $candidate" >/dev/null 2>&1; then
log "INFO" "${candidate} already present"
return 0
fi
done
for candidate in $candidates; do
if eval "$INSTALL_CMD $candidate" >/dev/null 2>&1; then
log "SUCCESS" "Installed ${candidate}"
return 0
fi
log "WARNING" "Failed to install ${candidate}, trying next fallback"
done
log "WARNING" "Could not install package ${pkg} on ${PKG_MGR}"
return 1
}
# # Check system compatibility
# check_system_compatibility() {
# log "INFO" "Checking system compatibility..."
# # Check if running on Raspberry Pi
# if ! grep -q "Raspberry Pi" /proc/cpuinfo; then
# log "WARNING" "This system might not be a Raspberry Pi. Continue anyway? (y/n)"
# read -r response
# if [[ ! "$response" =~ ^[Yy]$ ]]; then
# clean_exit 1
# fi
# fi
# check_success "System compatibility check completed"
# }
# Check system compatibility
check_system_compatibility() {
log "INFO" "Checking system compatibility..."
local should_ask_confirmation=false
# Skip hardware gating - Ragnar now supports all tested platforms
# Check RAM (Raspberry Pi Zero has 512MB RAM)
total_ram=$(free -m | awk '/^Mem:/{print $2}')
if [ -n "$total_ram" ] && [ "$total_ram" -lt 410 ]; then
log "WARNING" "Low RAM detected. Required: 512MB (410 With OS Running), Found: ${total_ram}MB"
echo -e "${YELLOW}Your system has less RAM than recommended. This might affect performance, but you can continue.${NC}"
should_ask_confirmation=true
elif [ -n "$total_ram" ]; then
log "SUCCESS" "RAM check passed: ${total_ram}MB available"
fi
# Check available disk space
available_space=$(df -m /home | awk 'NR==2 {print $4}')
if [ -n "$available_space" ] && [ "$available_space" -lt 2048 ]; then
log "WARNING" "Low disk space. Recommended: 1GB, Found: ${available_space}MB"
echo -e "${YELLOW}Your system has less free space than recommended. This might affect installation.${NC}"
should_ask_confirmation=true
else
log "SUCCESS" "Disk space check passed: ${available_space}MB available"
fi
# OS/version is now accepted broadly; log for visibility only
if [ -f "/etc/os-release" ]; then
source /etc/os-release
log "INFO" "OS detected: ${PRETTY_NAME} (${VERSION_ID})"
else
log "INFO" "OS detected: unknown (no /etc/os-release)"
fi
# Architecture compatibility: supported across tested platforms, log for visibility only
if command -v dpkg >/dev/null 2>&1; then
architecture=$(dpkg --print-architecture)
else
architecture=${ARCH:-$(uname -m 2>/dev/null)}
fi
log "INFO" "Architecture detected: ${architecture} (proceeding without compatibility warnings)"
if [ "$should_ask_confirmation" = true ]; then
echo -e "\n${YELLOW}Some system compatibility warnings were detected (see above).${NC}"
echo -e "${YELLOW}The installation might not work as expected.${NC}"
echo -e "${YELLOW}Do you want to continue anyway? (y/n)${NC}"
read -r response
if [[ ! "$response" =~ ^[Yy]$ ]]; then
log "INFO" "Installation aborted by user after compatibility warnings"
clean_exit 1
fi
else
log "SUCCESS" "All compatibility checks passed"
fi
log "INFO" "System compatibility check completed"
return 0
}
check_internet() {
log "INFO" "Checking internet connectivity..."
# Try to ping common servers
if ping -c 2 8.8.8.8 > /dev/null 2>&1 || ping -c 2 1.1.1.1 > /dev/null 2>&1; then
log "SUCCESS" "Internet connectivity confirmed"
# Test DNS resolution
if ping -c 1 pypi.org > /dev/null 2>&1; then
log "SUCCESS" "DNS resolution working"
else
log "WARNING" "DNS resolution issues detected. Package installation may be slow."
log "INFO" "Consider checking /etc/resolv.conf or your network settings"
fi
return 0
else
log "WARNING" "No internet connectivity detected!"
echo -e "${YELLOW}Internet connection is required to download Python packages.${NC}"
echo -e "${YELLOW}Please check your network connection and try again.${NC}"
echo -e "\nDo you want to:"
echo "1. Continue anyway (installation may fail)"
echo "2. Exit and fix network issues first (recommended)"
read -r choice
case $choice in
1)
log "WARNING" "Continuing without verified internet connection"
return 0
;;
*)
log "INFO" "Installation aborted - please fix network issues first"
clean_exit 1
;;
esac
fi
}
# Install system dependencies
install_dependencies() {
log "INFO" "Installing system dependencies..."
[ -z "$PKG_MGR" ] && detect_platform
eval "$UPDATE_CMD"
check_success "Package index updated via ${PKG_MGR}"
packages=(
"python3-pip"
"wget"
"lsof"
"git"
"sudo"
"libopenjp2-7"
"nmap"
"libopenblas-dev"
"bluez"
"bluez-tools"
"bridge-utils"
"python3-pil"
"libjpeg-dev"
"zlib1g-dev"
"libpng-dev"
"python3-dev"
"libffi-dev"
"libssl-dev"
"build-essential"
"python3-sqlalchemy"
"python3-pandas"
"python3-numpy"
"python3-flask"
"python3-flask-socketio"
"python3-flask-cors"
"hostapd"
"dnsmasq"
"network-manager"
"wireless-tools"
"iproute2"
"iputils-ping"
"rfkill"
"sqlite3"
"arp-scan"
"tcpdump"
"nikto"
"sqlmap"
"whatweb"
)
if [ "$IS_ARM" = true ]; then
packages+=("libgpiod-dev" "libi2c-dev" "dhcpcd5")
fi
optional_packages=("libatlas-base-dev")
for package in "${packages[@]}"; do
install_package "$package"
done
for package in "${optional_packages[@]}"; do
install_package "$package" || log "WARNING" "Optional package $package unavailable on ${PKG_MGR}"
done
# Ensure vulners.nse script is available for vulnerability scanning
local vulners_path="/usr/share/nmap/scripts/vulners.nse"
if [ ! -f "$vulners_path" ]; then
log "INFO" "Downloading vulners.nse script for nmap..."
mkdir -p "$(dirname "$vulners_path")"
if wget -q -O "$vulners_path" "https://raw.githubusercontent.com/vulnersCom/nmap-vulners/master/vulners.nse"; then
chmod 644 "$vulners_path"
log "SUCCESS" "Installed vulners.nse vulnerability script"
else
log "WARNING" "Failed to download vulners.nse script automatically. Vulnerability scans may be limited."
fi
else
log "INFO" "vulners.nse script already present"
fi
# Update nmap scripts
nmap --script-updatedb
# Configure WiFi interfaces
log "INFO" "Configuring WiFi interfaces..."
# Ensure WiFi is not blocked by rfkill
if command -v rfkill >/dev/null 2>&1; then
rfkill unblock wifi
log "SUCCESS" "WiFi unblocked via rfkill"
else
log "WARNING" "rfkill not available - WiFi blocking status unknown"
fi
# Create basic wpa_supplicant configuration if it doesn't exist
if [ ! -f "/etc/wpa_supplicant/wpa_supplicant.conf" ]; then
log "INFO" "Creating basic wpa_supplicant configuration..."
mkdir -p /etc/wpa_supplicant
cat > /etc/wpa_supplicant/wpa_supplicant.conf << EOF
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
# This file will be managed by NetworkManager and Ragnar WiFi Manager
# Networks will be added dynamically
EOF
chmod 600 /etc/wpa_supplicant/wpa_supplicant.conf
log "SUCCESS" "Created basic wpa_supplicant configuration"
fi
check_success "Dependencies installation completed"
}
# Configure system limits
configure_system_limits() {
log "INFO" "Configuring system limits..."
# Configure /etc/security/limits.conf for file descriptors AND process limits
cat >> /etc/security/limits.conf << EOF
# Ragnar system limits - File descriptors
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
# Ragnar system limits - Process limits (critical for threading and OpenBLAS)
* soft nproc 4096
* hard nproc 8192
root soft nproc 4096
root hard nproc 8192
$ragnar_USER soft nproc 4096
$ragnar_USER hard nproc 8192
EOF
# Configure systemd limits
sed -i '/^#DefaultLimitNOFILE=/d' /etc/systemd/system.conf
echo "DefaultLimitNOFILE=65535" >> /etc/systemd/system.conf
sed -i '/^#DefaultLimitNOFILE=/d' /etc/systemd/user.conf
echo "DefaultLimitNOFILE=65535" >> /etc/systemd/user.conf
# Add process limit to systemd
sed -i '/^#DefaultLimitNPROC=/d' /etc/systemd/system.conf
echo "DefaultLimitNPROC=4096" >> /etc/systemd/system.conf
sed -i '/^#DefaultLimitNPROC=/d' /etc/systemd/user.conf
echo "DefaultLimitNPROC=4096" >> /etc/systemd/user.conf
# Create /etc/security/limits.d/90-ragnar-limits.conf with both file and process limits
cat > /etc/security/limits.d/90-ragnar-limits.conf << EOF
# Ragnar System Limits Configuration
# File descriptor limits
root soft nofile 65535
root hard nofile 65535
$ragnar_USER soft nofile 65535
$ragnar_USER hard nofile 65535
# Process/thread limits (prevents OpenBLAS pthread_create errors)
root soft nproc 4096
root hard nproc 8192
$ragnar_USER soft nproc 4096
$ragnar_USER hard nproc 8192
EOF
# Configure sysctl for file handles and process limits
cat >> /etc/sysctl.conf << EOF
# Ragnar system tuning
fs.file-max = 2097152
kernel.pid_max = 32768
kernel.threads-max = 65536
EOF
sysctl -p
# Ensure PAM limits are applied
if ! grep -q "session required pam_limits.so" /etc/pam.d/common-session; then
echo "session required pam_limits.so" >> /etc/pam.d/common-session
fi
if ! grep -q "session required pam_limits.so" /etc/pam.d/common-session-noninteractive; then
echo "session required pam_limits.so" >> /etc/pam.d/common-session-noninteractive
fi
log "SUCCESS" "System limits configured: nofile=65535, nproc=4096/8192"
check_success "System limits configuration completed"
}
# Configure SPI and I2C
# Install PiSugar power manager server (required for PiSugar UPS battery/button support)
install_pisugar_server() {
# Only relevant on ARM / Raspberry Pi hardware
if [ "$IS_ARM" != true ]; then
log "INFO" "Skipping PiSugar server install (not ARM hardware)"
return 0
fi
# Check if pisugar-server is already installed
if command -v pisugar-server >/dev/null 2>&1 || systemctl list-unit-files pisugar-server.service >/dev/null 2>&1; then
log "INFO" "PiSugar server is already installed"
echo -e "${GREEN}✓ PiSugar server already installed${NC}"
return 0
fi
echo -e "\n${CYAN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${CYAN} PiSugar UPS Support${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}PiSugar provides battery power, battery monitoring, and a${NC}"
echo -e "${BLUE}hardware button for Ragnar. If you have a PiSugar UPS${NC}"
echo -e "${BLUE}attached, the pisugar-server daemon is required.${NC}"
echo ""
read -p "Do you have a PiSugar UPS? Install pisugar-server? (y/n): " install_pisugar
if [ "$install_pisugar" != "y" ] && [ "$install_pisugar" != "Y" ]; then
log "INFO" "User opted out of PiSugar server installation"
echo -e "${YELLOW}Skipping PiSugar server installation${NC}"
return 0
fi
log "INFO" "Installing PiSugar power manager server..."
echo -e "${BLUE}Downloading and installing PiSugar power manager...${NC}"
if curl -sSL http://cdn.pisugar.com/release/pisugar-power-manager.sh | sudo bash; then
log "SUCCESS" "PiSugar server installed successfully"
echo -e "${GREEN}✓ PiSugar server installed${NC}"
# Enable and start the service
if systemctl enable pisugar-server 2>/dev/null; then
log "SUCCESS" "PiSugar server service enabled"
fi
if systemctl start pisugar-server 2>/dev/null; then
log "SUCCESS" "PiSugar server service started"
fi
else
log "WARNING" "PiSugar server installation failed"
echo -e "${YELLOW}⚠ PiSugar server installation failed${NC}"
echo -e "${YELLOW} You can install it manually later:${NC}"
echo -e "${YELLOW} curl http://cdn.pisugar.com/release/pisugar-power-manager.sh | sudo bash${NC}"
fi
}
configure_interfaces() {
log "INFO" "Configuring SPI and I2C interfaces..."
if command -v raspi-config >/dev/null 2>&1; then
raspi-config nonint do_spi 0
raspi-config nonint do_i2c 0
check_success "Interface configuration completed"
else
log "WARNING" "raspi-config not available; skipping SPI/I2C configuration (non-Raspberry Pi hardware)"
fi
}
# Setup ragnar
setup_ragnar() {
log "INFO" "Setting up ragnar..."
# Use PiWheels for faster installs on Raspberry Pi architectures
local machine_arch
machine_arch=$(uname -m 2>/dev/null || echo "")
if [[ "$machine_arch" == "armv7l" || "$machine_arch" == "armv6l" || "$machine_arch" == "aarch64" || "$machine_arch" == "arm64" ]]; then
if [ -z "${PIP_EXTRA_INDEX_URL:-}" ]; then
export PIP_EXTRA_INDEX_URL="https://www.piwheels.org/simple"
else
export PIP_EXTRA_INDEX_URL="$PIP_EXTRA_INDEX_URL https://www.piwheels.org/simple"
fi
log "INFO" "Using PiWheels Python package index for ${machine_arch}"
fi
# Create ragnar user if it doesn't exist
if ! id -u $ragnar_USER >/dev/null 2>&1; then
adduser --disabled-password --gecos "" $ragnar_USER
check_success "Created ragnar user"
fi
# Check for existing ragnar directory with a valid git clone
cd /home/$ragnar_USER
if [ -d "Ragnar/.git" ]; then
log "INFO" "Using existing ragnar directory"
echo -e "${GREEN}Using existing ragnar directory${NC}"
else
# Remove empty/invalid directory if it exists
if [ -d "Ragnar" ]; then
log "WARNING" "Ragnar directory exists but is not a valid git clone, removing..."
rm -rf Ragnar
fi
# Proceed with clone
log "INFO" "Cloning ragnar repository"
git clone https://github.com/PierreGode/Ragnar.git
check_success "Cloned ragnar repository"
fi
cd Ragnar
# Update the default display type in shared.py with the detected/selected version
log "INFO" "Updating display default configuration in shared.py..."
if [ -z "${EPD_VERSION:-}" ]; then
if [ "$HEADLESS_MODE" = true ]; then
log "INFO" "Headless mode selected - skipping shared.py default display configuration"
else
log "WARNING" "Display version not detected - skipping shared.py update"
fi
elif [ -f "$ragnar_PATH/shared.py" ]; then
# Replace whatever epd_type default is currently in shared.py with the user's selection.
# Using a wildcard pattern instead of hardcoding "epd2in13_V4" so this works correctly
# on reinstalls where a previous run already changed the default to a different version.
sed -i "s/\"epd_type\": \"[^\"]*\"/\"epd_type\": \"$EPD_VERSION\"/" "$ragnar_PATH/shared.py"
check_success "Updated shared.py default EPD configuration to $EPD_VERSION"
log "INFO" "Modified: $ragnar_PATH/shared.py"
# Always write the selected epd_type into shared_config.json so the running service
# uses the right driver immediately — even on a fresh install where the file doesn't
# exist yet (previous code skipped this, leaving Ragnar to regenerate config from
# shared.py defaults, which could be stale if sed failed for any reason).
local config_json="$ragnar_PATH/config/shared_config.json"
mkdir -p "$(dirname "$config_json")"
python3 -c "
import json, os
config_path = '$config_json'
cfg = {}
if os.path.exists(config_path):
try:
with open(config_path, 'r') as f:
cfg = json.load(f)
except Exception:
cfg = {}
cfg['epd_type'] = '$EPD_VERSION'
with open(config_path, 'w') as f:
json.dump(cfg, f, indent=4)
print('SUCCESS: Set shared_config.json epd_type to $EPD_VERSION')
" && log "INFO" "Config JSON epd_type set to $EPD_VERSION" \
|| log "WARNING" "Could not write shared_config.json — epd_type will be read from shared.py on first run"
else
log "WARNING" "shared.py not found at $ragnar_PATH/shared.py - skipping E-Paper configuration update"
fi
# Install requirements with --break-system-packages flag
log "INFO" "Installing Python requirements..."
# Install packages that can fail separately to handle errors
log "INFO" "Installing core Python packages..."
# Function to check if a Python package is installed
check_python_package() {
python3 -c "import $1" 2>/dev/null
return $?
}
# Try to install RPi.GPIO and spidev
if ! check_python_package "RPi.GPIO"; then
log "INFO" "Installing RPi.GPIO and spidev..."
pip3 install --break-system-packages RPi.GPIO==0.7.1 spidev==3.5 || {
log "WARNING" "Failed to install RPi.GPIO or spidev, trying without version pinning..."
pip3 install --break-system-packages RPi.GPIO spidev
}
else
log "INFO" "RPi.GPIO already installed, skipping"
fi
# Install Pillow - use system package if pip fails
if ! check_python_package "PIL"; then
log "INFO" "Installing Pillow..."
pip3 install --break-system-packages "Pillow>=10.0.0" || {
log "WARNING" "Pillow pip install failed, using system package python3-pil"
install_package "python3-pil"
}
else
log "INFO" "Pillow already installed, skipping"
fi
# Install numpy and pandas - prefer system packages but fallback to pip
log "INFO" "Checking numpy and pandas..."
if ! check_python_package "numpy" || ! check_python_package "pandas"; then
log "INFO" "Installing numpy and pandas (this may take a while)..."
pip3 install --break-system-packages --retries 5 --timeout 300 "numpy>=1.24.0" "pandas>=2.0.0" || {
log "WARNING" "Pandas/numpy pip install failed, relying on system packages"
}
else
log "INFO" "numpy and pandas already installed, skipping"
fi
# Install remaining packages from requirements.txt with retry logic
# This includes all dependencies for full Ragnar functionality:
# - netifaces: Network interface detection for NetworkScanner
# - smbprotocol/pysmb: SMB protocol support for StealFilesSMB and SMBBruteforce
# - sqlalchemy: SQL database operations for StealDataSQL
# - openai: AI-powered network analysis and vulnerability insights
log "INFO" "Installing remaining Python packages..."
# Array of packages to install with their import names
declare -A packages=(
["rich>=13.0.0"]="rich"
["netifaces==0.11.0"]="netifaces"
["ping3>=4.0.0"]="ping3"
["get-mac>=0.9.0"]="get_mac"
["paramiko>=3.0.0"]="paramiko"
["smbprotocol>=1.10.0"]="smbprotocol"
["pysmb>=1.2.0"]="smb"
["pymysql>=1.0.0"]="pymysql"
["sqlalchemy>=1.4.0"]="sqlalchemy"
["python-nmap>=0.7.0"]="nmap"
["flask>=3.0.0"]="flask"
["flask-socketio>=5.3.0"]="flask_socketio"
["flask-cors>=4.0.0"]="flask_cors"
["psutil>=5.9.0"]="psutil"
["logger>=1.4"]="logger"
)
# Install each package individually with retries if not already installed
for package in "${!packages[@]}"; do
import_name="${packages[$package]}"
if check_python_package "$import_name"; then
log "INFO" "$package already installed, skipping"
else
log "INFO" "Installing $package..."
pip3 install --break-system-packages --retries 3 --timeout 180 "$package" || {
log "WARNING" "Failed to install $package after retries. Continuing..."
}
fi
done
# Install OpenAI package separately for root (since service runs as root)
log "INFO" "Installing OpenAI package for root user..."
sudo pip3 install --break-system-packages --ignore-installed "openai>=2.0.0" || {
log "WARNING" "Failed to install openai package for root. AI features may not work."
log "WARNING" "You can install it manually later with: sudo pip3 install --break-system-packages --ignore-installed openai>=2.0.0"
}
# Install cryptography package for authentication and database encryption
log "INFO" "Installing cryptography package for authentication..."
sudo pip3 install --break-system-packages "cryptography>=41.0.0" || {
log "WARNING" "Failed to install cryptography package. Authentication features may not work."
log "WARNING" "You can install it manually later with: sudo pip3 install --break-system-packages cryptography>=41.0.0"
}
# Verify display driver availability
if [ "$HEADLESS_MODE" = true ] || [ -z "${EPD_VERSION:-}" ]; then
log "INFO" "Headless mode or unknown display version detected - skipping driver verification"
elif [ "$EPD_VERSION" = "gc9a01" ]; then
# TFT drivers ship with Ragnar in resources/waveshare_epd/, verify the file exists
if [ -f "$ragnar_PATH/resources/waveshare_epd/gc9a01.py" ]; then
log "SUCCESS" "GC9A01 TFT driver verified (resources/waveshare_epd/gc9a01.py)"
else
log "ERROR" "GC9A01 TFT driver not found at $ragnar_PATH/resources/waveshare_epd/gc9a01.py"
fi
# Ensure spidev is installed for TFT SPI communication
pip3 install spidev --break-system-packages >/dev/null 2>&1
log "INFO" "SPI dependencies installed for TFT display"
elif [ "$EPD_VERSION" = "ssd1306" ]; then
if [ -f "$ragnar_PATH/resources/waveshare_epd/ssd1306.py" ]; then
log "SUCCESS" "SSD1306 OLED driver verified (resources/waveshare_epd/ssd1306.py)"
else
log "ERROR" "SSD1306 OLED driver not found at $ragnar_PATH/resources/waveshare_epd/ssd1306.py"
fi
# Install smbus2 for I2C communication
pip3 install smbus2 --break-system-packages >/dev/null 2>&1
# Enable I2C interface
raspi-config nonint do_i2c 0 2>/dev/null || true
log "INFO" "I2C interface enabled for SSD1306"
elif [ "$EPD_VERSION" = "lcd1602" ]; then
if [ -f "$ragnar_PATH/resources/waveshare_epd/lcd1602.py" ]; then
log "SUCCESS" "LCD1602 driver verified (resources/waveshare_epd/lcd1602.py)"
else
log "ERROR" "LCD1602 driver not found at $ragnar_PATH/resources/waveshare_epd/lcd1602.py"
fi
# Install smbus2 for I2C communication
pip3 install smbus2 --break-system-packages >/dev/null 2>&1
# Enable I2C interface
raspi-config nonint do_i2c 0 2>/dev/null || true
log "INFO" "I2C interface enabled for LCD1602"
else
log "INFO" "Verifying Waveshare e-Paper library installation for $EPD_VERSION..."
cd /home/$ragnar_USER/e-Paper/RaspberryPi_JetsonNano/python
pip3 install . --break-system-packages
python3 -c "from waveshare_epd import ${EPD_VERSION}; print('EPD module OK')" \
&& log "SUCCESS" "$EPD_VERSION driver verified successfully" \
|| log "ERROR" "EPD driver $EPD_VERSION failed to import"
fi
if [[ "$EPD_VERSION" == max7219* ]]; then
sudo pip3 install --break-system-packages luma.led_matrix luma.core 2>/dev/null || pip3 install --break-system-packages luma.led_matrix luma.core 2>/dev/null || true
fi
check_success "Installed Python requirements"
# Configure Ragnar entrypoint according to the selected mode
log "INFO" "Configuring Ragnar entrypoint ($RAGNAR_ENTRYPOINT)..."
local entrypoint_path="$ragnar_PATH/$RAGNAR_ENTRYPOINT"
if [ -f "$entrypoint_path" ]; then
if [ "$RAGNAR_ENTRYPOINT" = "Ragnar.py" ]; then
if [ -f "$ragnar_PATH/webapp_modern.py" ]; then
# Backup original Ragnar.py if not already backed up
if [ ! -f "${entrypoint_path}.original" ]; then
cp "$entrypoint_path" "${entrypoint_path}.original"
fi
# Update Ragnar.py to use modern webapp
if grep -q "from webapp import web_thread" "$entrypoint_path"; then
sed -i 's/from webapp import web_thread/# Old webapp - replaced with modern\n# from webapp import web_thread\nfrom webapp_modern import run_server as web_thread/' "$entrypoint_path"
log "SUCCESS" "Configured to use modern web interface"
else
log "INFO" "Modern webapp already configured or different setup detected"
fi
else
log "WARNING" "Modern webapp files not found, using default configuration"
fi
else
log "INFO" "Headless variant selected (${HEADLESS_VARIANT_LABEL:-headless}); skipping display configuration"
fi
else
log "WARNING" "Entrypoint $entrypoint_path not found, using default configuration"
fi
# Set correct permissions and ownership
chown -R $ragnar_USER:$ragnar_USER /home/$ragnar_USER/Ragnar
chmod -R 755 /home/$ragnar_USER/Ragnar
# Make utility scripts executable with proper ownership
chmod +x $ragnar_PATH/kill_port_8000.sh 2>/dev/null || true
chmod +x $ragnar_PATH/scripts/update_ragnar.sh 2>/dev/null || true
chmod +x $ragnar_PATH/scripts/quick_update.sh 2>/dev/null || true
chmod +x $ragnar_PATH/scripts/uninstall_ragnar.sh 2>/dev/null || true
chmod +x $ragnar_PATH/scripts/wifi_fix.sh 2>/dev/null || true
chmod +x $ragnar_PATH/scripts/init_data_files.sh 2>/dev/null || true
chmod +x $ragnar_PATH/scripts/preserve_local_data.sh 2>/dev/null || true
chmod +x $ragnar_PATH/wipe_epd.py 2>/dev/null || true
# Ensure ragnar user owns all script files
chown $ragnar_USER:$ragnar_USER $ragnar_PATH/*.sh 2>/dev/null || true
chown $ragnar_USER:$ragnar_USER $ragnar_PATH/scripts/*.sh 2>/dev/null || true
# Initialize data files from templates
log "INFO" "Initializing data files from templates..."
bash $ragnar_PATH/scripts/init_data_files.sh
chown -R $ragnar_USER:$ragnar_USER $ragnar_PATH/data
# Create missing directories and files that are needed for proper operation
log "INFO" "Creating missing directories and files..."
# Create dictionary directory and files
mkdir -p $ragnar_PATH/data/input/dictionary
if [ ! -f "$ragnar_PATH/data/input/dictionary/users.txt" ]; then
cat > $ragnar_PATH/data/input/dictionary/users.txt << EOF
admin
root
user
administrator
test
guest
EOF
log "SUCCESS" "Created users.txt dictionary file"
fi
if [ ! -f "$ragnar_PATH/data/input/dictionary/passwords.txt" ]; then
cat > $ragnar_PATH/data/input/dictionary/passwords.txt << EOF
password
123456
admin
root
password123
123
test
guest
EOF
log "SUCCESS" "Created passwords.txt dictionary file"
fi
# Create comments.json file if missing
if [ ! -f "$ragnar_PATH/resources/comments/comments.json" ]; then
mkdir -p $ragnar_PATH/resources/comments
echo "[]" > $ragnar_PATH/resources/comments/comments.json
log "SUCCESS" "Created comments.json file"
fi
# Create missing ragnar1.bmp placeholder if needed (optional since we handle this gracefully now)
if [ ! -f "$ragnar_PATH/resources/images/static/ragnar1.bmp" ] && [ -f "$ragnar_PATH/resources/images/static/bjorn1.bmp" ]; then
cp "$ragnar_PATH/resources/images/static/bjorn1.bmp" "$ragnar_PATH/resources/images/static/ragnar1.bmp"
log "SUCCESS" "Created ragnar1.bmp from bjorn1.bmp"
fi
# Set proper ownership for all created files
chown -R $ragnar_USER:$ragnar_USER $ragnar_PATH/data/
chown -R $ragnar_USER:$ragnar_USER $ragnar_PATH/resources/
# Validate and fix actions.json file
log "INFO" "Validating actions.json configuration..."
python3 << 'PYTHON_EOF'
import json
import os
actions_file = "/home/ragnar/Ragnar/config/actions.json"
# Check if scanning module exists in actions.json
try:
with open(actions_file, 'r') as f:
actions = json.load(f)
# Check if scanning module is present
has_scanning = any(action.get('b_module') == 'scanning' for action in actions)
if not has_scanning:
print("WARNING: scanning module missing from actions.json, adding it...")
scanning_action = {
"b_module": "scanning",
"b_class": "NetworkScanner",
"b_port": None,
"b_status": "network_scanner",
"b_parent": None
}
actions.insert(0, scanning_action)
with open(actions_file, 'w') as f:
json.dump(actions, f, indent=4)
print("SUCCESS: Added scanning module to actions.json")
else:
print("SUCCESS: scanning module found in actions.json")
except Exception as e:
print(f"ERROR validating actions.json: {e}")
PYTHON_EOF
# Add ragnar user to necessary groups (including sudo for WiFi management)
usermod -a -G spi,gpio,i2c,sudo,netdev $ragnar_USER
# Configure sudo for WiFi management commands without password
log "INFO" "Configuring sudo permissions for WiFi management..."
cat > /etc/sudoers.d/ragnar-wifi << EOF
# Allow ragnar user to run WiFi management commands without password
ragnar ALL=(ALL) NOPASSWD: /usr/bin/nmcli, /sbin/iwlist, /sbin/ip, /bin/systemctl start hostapd, /bin/systemctl stop hostapd, /bin/systemctl start dnsmasq, /bin/systemctl stop dnsmasq, /usr/sbin/hostapd, /usr/sbin/dnsmasq
EOF
chmod 440 /etc/sudoers.d/ragnar-wifi
# Configure sudo for nmap port scanning without password
log "INFO" "Configuring sudo permissions for nmap..."
cat > /etc/sudoers.d/ragnar-nmap << EOF
# Allow ragnar user to run nmap without password for port scanning
ragnar ALL=(ALL) NOPASSWD: /usr/bin/nmap
EOF
chmod 440 /etc/sudoers.d/ragnar-nmap
# Configure sudo for traffic analysis tools without password
log "INFO" "Configuring sudo permissions for traffic analysis..."
cat > /etc/sudoers.d/ragnar-traffic << EOF
# Allow ragnar user to run traffic analysis tools without password
ragnar ALL=(ALL) NOPASSWD: /usr/bin/tcpdump
ragnar ALL=(ALL) NOPASSWD: /usr/bin/tshark
ragnar ALL=(ALL) NOPASSWD: /usr/sbin/iftop
ragnar ALL=(ALL) NOPASSWD: /usr/sbin/nethogs
EOF