-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathinstall.sh
executable file
·2170 lines (1890 loc) · 82.5 KB
/
install.sh
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
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Function to print colored messages
print_message() {
# Check if $3 exists, otherwise set to empty string
local nonewline=${3:-""}
if [ "$nonewline" = "nonewline" ]; then
echo -en "${2}${1}${NC}"
else
echo -e "${2}${1}${NC}"
fi
}
# ASCII Art Banner
cat << "EOF"
____ _ _ _ _ _____ _____ ____
| __ )(_)_ __ __| | \ | | ____|_ _| / ___| ___
| _ \| | '__/ _` | \| | _| | | | | _ / _ \
| |_) | | | | (_| | |\ | |___ | | | |_| | (_) |
|____/|_|_| \__,_|_| \_|_____| |_| \____|\___/
EOF
print_message "\n🐦 BirdNET-Go Installation Script" "$GREEN"
print_message "This script will install BirdNET-Go and its dependencies." "$YELLOW"
BIRDNET_GO_VERSION="nightly"
BIRDNET_GO_IMAGE="ghcr.io/tphakala/birdnet-go:${BIRDNET_GO_VERSION}"
# Function to get IP address
get_ip_address() {
# Get primary IP address, excluding docker and localhost interfaces
local ip=""
# Method 1: Try using ip command with POSIX-compatible regex
if command_exists ip; then
ip=$(ip -4 addr show scope global \
| grep -vE 'docker|br-|veth' \
| grep -oE 'inet ([0-9]+\.){3}[0-9]+' \
| awk '{print $2}' \
| head -n1)
fi
# Method 2: Try hostname command for fallback if ip command didn't work
if [ -z "$ip" ] && command_exists hostname; then
ip=$(hostname -I 2>/dev/null | awk '{print $1}')
fi
# Method 3: Try ifconfig as last resort
if [ -z "$ip" ] && command_exists ifconfig; then
ip=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | head -n1 | awk '{print $2}' | sed 's/addr://')
fi
# Return the IP address or empty string
echo "$ip"
}
# Function to check if mDNS is available
check_mdns() {
# First check if avahi-daemon is installed
if ! command_exists avahi-daemon && ! command_exists systemctl; then
return 1
fi
# Then check if it's running
if command_exists systemctl && systemctl is-active --quiet avahi-daemon; then
hostname -f | grep -q ".local"
return $?
fi
return 1
}
# Function to check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Function to check if curl is available and install it if needed
ensure_curl() {
if ! command_exists curl; then
print_message "📦 curl not found. Installing curl..." "$YELLOW"
if sudo apt -qq update && sudo apt install -qq -y curl; then
print_message "✅ curl installed successfully" "$GREEN"
else
print_message "❌ Failed to install curl" "$RED"
print_message "Please install curl manually and try again" "$YELLOW"
exit 1
fi
fi
}
# Function to check network connectivity
check_network() {
print_message "🌐 Checking network connectivity..." "$YELLOW"
local success=true
# First do a basic ping test to check general connectivity
if ! ping -c 1 8.8.8.8 >/dev/null 2>&1; then
print_message "❌ No network connectivity (ping test failed)" "$RED"
print_message "Please check your internet connection and try again" "$YELLOW"
exit 1
fi
# Now ensure curl is available for further tests
ensure_curl
# HTTP/HTTPS Check
print_message "\n📡 Testing HTTP/HTTPS connectivity..." "$YELLOW"
local urls=(
"https://github.com"
"https://raw.githubusercontent.com"
"https://ghcr.io"
)
for url in "${urls[@]}"; do
local http_code
http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url")
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 400 ]; then
print_message "✅ HTTPS connection successful to $url (HTTP $http_code)" "$GREEN"
else
print_message "❌ HTTPS connection failed to $url (HTTP $http_code)" "$RED"
success=false
fi
done
# Docker Registry Check
print_message "\n📡 Testing GitHub registry connectivity..." "$YELLOW"
if curl -s "https://ghcr.io/v2/" >/dev/null 2>&1; then
print_message "✅ GitHub registry is accessible" "$GREEN"
else
print_message "❌ Cannot access Docker registry" "$RED"
success=false
fi
if [ "$success" = false ]; then
print_message "\n❌ Network connectivity check failed" "$RED"
print_message "Please check:" "$YELLOW"
print_message " • Internet connection" "$YELLOW"
print_message " • DNS settings (/etc/resolv.conf)" "$YELLOW"
print_message " • Firewall rules" "$YELLOW"
print_message " • Proxy settings (if applicable)" "$YELLOW"
return 1
fi
print_message "\n✅ Network connectivity check passed\n" "$GREEN"
return 0
}
# Function to check system prerequisites
check_prerequisites() {
print_message "🔧 Checking system prerequisites..." "$YELLOW"
# Check CPU architecture and generation
case "$(uname -m)" in
"x86_64")
# Check CPU flags for AVX2 (Haswell and newer)
if ! grep -q "avx2" /proc/cpuinfo; then
print_message "❌ Your Intel CPU is too old. BirdNET-Go requires Intel Haswell (2013) or newer CPU with AVX2 support" "$RED"
exit 1
else
print_message "✅ Intel CPU architecture and generation check passed" "$GREEN"
fi
;;
"aarch64"|"arm64")
print_message "✅ ARM 64-bit architecture detected, continuing with installation" "$GREEN"
;;
"armv7l"|"armv6l"|"arm")
print_message "❌ 32-bit ARM architecture detected. BirdNET-Go requires 64-bit ARM processor and OS" "$RED"
exit 1
;;
*)
print_message "❌ Unsupported CPU architecture: $(uname -m)" "$RED"
exit 1
;;
esac
# shellcheck source=/etc/os-release
if [ -f /etc/os-release ]; then
. /etc/os-release
else
print_message "❌ Cannot determine OS version" "$RED"
exit 1
fi
# Check for supported distributions
case "$ID" in
debian)
# Debian 11 (Bullseye) has VERSION_ID="11"
if [ -n "$VERSION_ID" ] && [ "$VERSION_ID" -lt 11 ]; then
print_message "❌ Debian $VERSION_ID too old. Version 11 (Bullseye) or newer required" "$RED"
exit 1
else
print_message "✅ Debian $VERSION_ID found" "$GREEN"
fi
;;
raspbian)
print_message "❌ You are running 32-bit version of Raspberry Pi OS. BirdNET-Go requires 64-bit version" "$RED"
exit 1
;;
ubuntu)
# Ubuntu 20.04 has VERSION_ID="20.04"
ubuntu_version=$(echo "$VERSION_ID" | awk -F. '{print $1$2}')
if [ "$ubuntu_version" -lt 2004 ]; then
print_message "❌ Ubuntu $VERSION_ID too old. Version 20.04 or newer required" "$RED"
exit 1
else
print_message "✅ Ubuntu $VERSION_ID found" "$GREEN"
fi
;;
*)
print_message "❌ Unsupported Linux distribution for install.sh. Please use Debian 11+, Ubuntu 20.04+, or Raspberry Pi OS (Bullseye+)" "$RED"
exit 1
;;
esac
# Function to add user to required groups
add_user_to_groups() {
print_message "🔧 Adding user $USER to required groups..." "$YELLOW"
local groups_added=false
if ! groups "$USER" | grep &>/dev/null "\bdocker\b"; then
if sudo usermod -aG docker "$USER"; then
print_message "✅ Added user $USER to docker group" "$GREEN"
groups_added=true
else
print_message "❌ Failed to add user $USER to docker group" "$RED"
exit 1
fi
fi
if ! groups "$USER" | grep &>/dev/null "\baudio\b"; then
if sudo usermod -aG audio "$USER"; then
print_message "✅ Added user $USER to audio group" "$GREEN"
groups_added=true
else
print_message "❌ Failed to add user $USER to audio group" "$RED"
exit 1
fi
fi
# Add user to adm group for journalctl access
if ! groups "$USER" | grep &>/dev/null "\badm\b"; then
if sudo usermod -aG adm "$USER"; then
print_message "✅ Added user $USER to adm group" "$GREEN"
groups_added=true
else
print_message "❌ Failed to add user $USER to adm group" "$RED"
exit 1
fi
fi
if [ "$groups_added" = true ]; then
print_message "Please log out and log back in for group changes to take effect, and rerun install.sh to continue with install" "$YELLOW"
exit 0
fi
}
# Check and install Docker
if ! command_exists docker; then
print_message "🐳 Docker not found. Installing Docker..." "$YELLOW"
# Install Docker from apt repository
sudo apt -qq update
sudo apt -qq install -y docker.io
# Add current user to required groups
add_user_to_groups
# Start Docker service
if sudo systemctl start docker; then
print_message "✅ Docker service started successfully" "$GREEN"
else
print_message "❌ Failed to start Docker service" "$RED"
exit 1
fi
# Enable Docker service on boot
if sudo systemctl enable docker; then
print_message "✅ Docker service start on boot enabled successfully" "$GREEN"
else
print_message "❌ Failed to enable Docker service on boot" "$RED"
exit 1
fi
print_message "⚠️ Docker installed successfully. To make group member changes take effect, please log out and log back in and rerun install.sh to continue with install" "$YELLOW"
# exit install script
exit 0
else
print_message "✅ Docker found" "$GREEN"
# Check if user is in required groups
add_user_to_groups
# Check if Docker can be used by the user
if ! docker info &>/dev/null; then
print_message "❌ Docker cannot be accessed by user $USER. Please ensure you have the necessary permissions." "$RED"
exit 1
else
print_message "✅ Docker is accessible by user $USER" "$GREEN"
fi
fi
print_message "🥳 System prerequisites checks passed" "$GREEN"
print_message ""
}
# Function to check if directories can be created
check_directory() {
local dir="$1"
if [ ! -d "$dir" ]; then
if ! mkdir -p "$dir" 2>/dev/null; then
print_message "❌ Cannot create directory $dir" "$RED"
print_message "Please check permissions" "$YELLOW"
exit 1
fi
elif [ ! -w "$dir" ]; then
print_message "❌ Cannot write to directory $dir" "$RED"
print_message "Please check permissions" "$YELLOW"
exit 1
fi
}
# Function to check if there is enough disk space for Docker image
check_docker_space() {
local required_space=2000000 # 2GB in KB
local available_space
available_space=$(df -k /var/lib/docker | awk 'NR==2 {print $4}')
if [ "$available_space" -lt "$required_space" ]; then
print_message "❌ Insufficient disk space for Docker image" "$RED"
print_message "Required: 2GB, Available: $((available_space/1024))MB" "$YELLOW"
exit 1
fi
}
# Function to pull Docker image
pull_docker_image() {
print_message "\n🐳 Pulling BirdNET-Go Docker image from GitHub Container Registry..." "$YELLOW"
# Check if Docker can be used by the user
if ! docker info &>/dev/null; then
print_message "❌ Docker cannot be accessed by user $USER. Please ensure you have the necessary permissions." "$RED"
print_message "This could be due to:" "$YELLOW"
print_message "- User $USER is not in the docker group" "$YELLOW"
print_message "- Docker service is not running" "$YELLOW"
print_message "- Insufficient privileges to access Docker socket" "$YELLOW"
exit 1
fi
if docker pull "${BIRDNET_GO_IMAGE}"; then
print_message "✅ Docker image pulled successfully" "$GREEN"
else
print_message "❌ Failed to pull Docker image" "$RED"
print_message "This could be due to:" "$YELLOW"
print_message "- No internet connection" "$YELLOW"
print_message "- GitHub container registry being unreachable" "$YELLOW"
print_message "- Invalid image name or tag" "$YELLOW"
print_message "- Insufficient privileges to access Docker socket on local system" "$YELLOW"
exit 1
fi
}
# Helper function to check if BirdNET-Go systemd service exists
detect_birdnet_service() {
# Check for service unit files on disk
if [ -f "/etc/systemd/system/birdnet-go.service" ] || [ -f "/lib/systemd/system/birdnet-go.service" ]; then
return 0
fi
return 1
}
# Function to check if BirdNET service exists
check_service_exists() {
detect_birdnet_service
return $?
}
# Function to safely execute docker commands, suppressing errors if Docker isn't installed
safe_docker() {
if command_exists docker; then
docker "$@" 2>/dev/null
return $?
fi
return 1
}
# Function to check if BirdNET-Go is fully installed (service + container)
check_birdnet_installation() {
local service_exists=false
local image_exists=false
local container_exists=false
local container_running=false
local debug_output=""
# Check for systemd service
if detect_birdnet_service; then
service_exists=true
debug_output="${debug_output}Systemd service detected. "
fi
# Only check Docker components if Docker is installed
if command_exists docker; then
# Streamlined Docker checks
# Check for BirdNET-Go images
if safe_docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "birdnet-go"; then
image_exists=true
debug_output="${debug_output}Docker image exists. "
fi
# Check for any BirdNET-Go containers (running or stopped)
container_count=$(safe_docker ps -a --filter "ancestor=${BIRDNET_GO_IMAGE}" --format "{{.ID}}" | wc -l)
if [ "$container_count" -gt 0 ]; then
container_exists=true
debug_output="${debug_output}Container exists. "
# Check if any of these containers are running
running_count=$(safe_docker ps --filter "ancestor=${BIRDNET_GO_IMAGE}" --format "{{.ID}}" | wc -l)
if [ "$running_count" -gt 0 ]; then
container_running=true
debug_output="${debug_output}Container running. "
fi
fi
# Fallback check for containers with birdnet-go in the name
if [ "$container_exists" = false ]; then
if safe_docker ps -a | grep -q "birdnet-go"; then
container_exists=true
debug_output="${debug_output}Container with birdnet name exists. "
# Check if any of these containers are running
if safe_docker ps | grep -q "birdnet-go"; then
container_running=true
debug_output="${debug_output}Container with birdnet name running. "
fi
fi
fi
fi
# Debug output - uncomment to debug installation check
# print_message "DEBUG: $debug_output Service: $service_exists, Image: $image_exists, Container: $container_exists, Running: $container_running" "$YELLOW"
# Check if Docker components exist (image or containers)
local docker_components_exist
if [ "$image_exists" = true ] || [ "$container_exists" = true ] || [ "$container_running" = true ]; then
docker_components_exist=true
else
docker_components_exist=false
fi
# Full installation: service AND Docker components
if [ "$service_exists" = true ] && [ "$docker_components_exist" = true ]; then
echo "full" # Full installation with systemd
return 0
fi
# Docker-only installation: Docker components but no service
if [ "$service_exists" = false ] && [ "$docker_components_exist" = true ]; then
echo "docker" # Docker-only installation
return 0
fi
echo "none" # No installation
return 1 # No installation
}
# Function to check if we have preserved data from previous installation
check_preserved_data() {
if [ -f "$CONFIG_FILE" ] || [ -d "$DATA_DIR" ]; then
return 0 # Preserved data exists
fi
return 1 # No preserved data
}
# Function to convert only relative paths to absolute paths
convert_relative_to_absolute_path() {
local config_file=$1
local abs_path=$2
# Look specifically for the audio export path in the export section
local export_section_line=$(grep -n "export:" "$config_file" | cut -d: -f1)
if [ -z "$export_section_line" ]; then
print_message "⚠️ Export section not found in config file" "$YELLOW"
return 1
fi
# Find the path line within the export section (looking only at the next few lines after export:)
local clip_path_line=$(tail -n +$export_section_line "$config_file" | grep -n "path:" | head -1 | cut -d: -f1)
if [ -z "$clip_path_line" ]; then
print_message "⚠️ Clip path setting not found in export section" "$YELLOW"
return 1
fi
# Calculate the actual line number in the file
clip_path_line=$((export_section_line + clip_path_line - 1))
# Extract the current path value
local current_path=$(sed -n "${clip_path_line}p" "$config_file" | sed -E 's/^[[:space:]]*path:[[:space:]]*([^#]*).*/\1/' | xargs)
# Remove quotes if present
current_path=${current_path#\"}
current_path=${current_path%\"}
# Only convert if path is relative (doesn't start with /)
if [[ ! "$current_path" =~ ^/ ]]; then
print_message "Converting relative path '${current_path}' to absolute path '${abs_path}'" "$YELLOW"
# Use line-specific sed to replace just the clips path line
sed -i "${clip_path_line}s|path: .*|path: ${abs_path} # path to audio clip export directory|" "$config_file"
return 0
else
print_message "Path '${current_path}' is already absolute, skipping conversion" "$GREEN"
return 1
fi
}
# Function to handle all path migrations
update_paths_in_config() {
if [ -f "$CONFIG_FILE" ]; then
print_message "🔧 Updating paths in configuration file..." "$YELLOW"
if convert_relative_to_absolute_path "$CONFIG_FILE" "/data/clips/"; then
print_message "✅ Audio export path updated to absolute path" "$GREEN"
else
print_message "ℹ️ Audio export path already absolute; no changes made" "$YELLOW"
fi
fi
}
# Helper function to clean up HLS tmpfs mount
cleanup_hls_mount() {
local hls_mount="${CONFIG_DIR}/hls"
local mount_unit=$(systemctl list-units --type=mount | grep -i "$hls_mount" | awk '{print $1}')
print_message "🧹 Cleaning up tmpfs mounts..." "$YELLOW"
# First check if the mount exists
if mount | grep -q "$hls_mount" || [ -n "$mount_unit" ]; then
if [ -n "$mount_unit" ]; then
print_message "Found systemd mount unit: $mount_unit" "$YELLOW"
# Try to stop the mount unit using systemctl
print_message "Stopping systemd mount unit..." "$YELLOW"
sudo systemctl stop "$mount_unit" 2>/dev/null
# Check if it's still active
if systemctl is-active --quiet "$mount_unit"; then
print_message "⚠️ Failed to stop mount unit, trying manual unmount..." "$YELLOW"
else
print_message "✅ Successfully stopped systemd mount unit" "$GREEN"
return 0
fi
else
print_message "Found tmpfs mount at $hls_mount, attempting to unmount..." "$YELLOW"
fi
# Try regular unmount approaches as fallback
# Try regular unmount first
umount "$hls_mount" 2>/dev/null
# If still mounted, try with force flag
if mount | grep -q "$hls_mount"; then
umount -f "$hls_mount" 2>/dev/null
fi
# If still mounted, try with sudo
if mount | grep -q "$hls_mount"; then
sudo umount "$hls_mount" 2>/dev/null
fi
# If still mounted, try sudo with force flag
if mount | grep -q "$hls_mount"; then
sudo umount -f "$hls_mount" 2>/dev/null
fi
# If still mounted, try with lazy unmount as last resort
if mount | grep -q "$hls_mount"; then
print_message "⚠️ Regular unmount failed, trying lazy unmount..." "$YELLOW"
sudo umount -l "$hls_mount" 2>/dev/null
fi
# Final check
if mount | grep -q "$hls_mount"; then
print_message "❌ Failed to unmount $hls_mount" "$RED"
print_message "You may need to reboot the system to fully remove it" "$YELLOW"
else
print_message "✅ Successfully unmounted $hls_mount" "$GREEN"
fi
else
print_message "No tmpfs mount found at $hls_mount" "$GREEN"
fi
}
# Function to download base config file
download_base_config() {
# If config file already exists and we're not doing a fresh install, just use the existing config
if [ -f "$CONFIG_FILE" ] && [ "$FRESH_INSTALL" != "true" ]; then
print_message "✅ Using existing configuration file: " "$GREEN" "nonewline"
print_message "$CONFIG_FILE" "$NC"
return 0
fi
print_message "\n📥 Downloading base configuration file from GitHub to: " "$YELLOW" "nonewline"
print_message "$CONFIG_FILE" "$NC"
# Download new config to temporary file first
local temp_config="/tmp/config.yaml.new"
if ! curl -s --fail https://raw.githubusercontent.com/tphakala/birdnet-go/main/internal/conf/config.yaml > "$temp_config"; then
print_message "❌ Failed to download configuration template" "$RED"
print_message "This could be due to:" "$YELLOW"
print_message "- No internet connection or DNS resolution failed" "$YELLOW"
print_message "- Firewall blocking outgoing connections" "$YELLOW"
print_message "- GitHub being unreachable" "$YELLOW"
print_message "\nPlease check your internet connection and try again." "$YELLOW"
rm -f "$temp_config"
exit 1
fi
local config_updated=false
if [ -f "$CONFIG_FILE" ]; then
if cmp -s "$CONFIG_FILE" "$temp_config"; then
print_message "✅ Base configuration already exists" "$GREEN"
rm -f "$temp_config"
else
print_message "⚠️ Existing configuration file found." "$YELLOW"
print_message "❓ Do you want to overwrite it? Backup of current configuration will be created (y/n): " "$YELLOW" "nonewline"
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
# Create backup with timestamp
local backup_file
backup_file="${CONFIG_FILE}.$(date '+%Y%m%d_%H%M%S').backup"
cp "$CONFIG_FILE" "$backup_file"
print_message "✅ Backup created: " "$GREEN" "nonewline"
print_message "$backup_file" "$NC"
mv "$temp_config" "$CONFIG_FILE"
print_message "✅ Configuration updated successfully" "$GREEN"
config_updated=true
else
print_message "✅ Keeping existing configuration file" "$YELLOW"
rm -f "$temp_config"
fi
fi
else
mv "$temp_config" "$CONFIG_FILE"
print_message "✅ Base configuration downloaded successfully" "$GREEN"
config_updated=true
fi
# Always ensure clips path is absolute, regardless of whether config was updated or existing
print_message "\n🔧 Checking audio export path configuration..." "$YELLOW"
if convert_relative_to_absolute_path "$CONFIG_FILE" "/data/clips/"; then
print_message "✅ Audio export path updated to absolute path" "$GREEN"
else
print_message "ℹ️ Audio export path already absolute; no changes made" "$YELLOW"
fi
}
# Function to test RTSP URL
test_rtsp_url() {
local url=$1
# Parse URL to get host and port
if [[ $url =~ rtsp://([^@]+@)?([^:/]+)(:([0-9]+))? ]]; then
local host="${BASH_REMATCH[2]}"
local port="${BASH_REMATCH[4]:-554}" # Default RTSP port is 554
print_message "🧪 Testing connection to $host:$port..." "$YELLOW"
# Test port using timeout and nc, redirect all output to /dev/null
if ! timeout 5 nc -zv "$host" "$port" &>/dev/null; then
print_message "❌ Could not connect to $host:$port" "$RED"
print_message "❓ Do you want to use this URL anyway? (y/n): " "$YELLOW" "nonewline"
read -r force_continue
if [[ $force_continue == "y" ]]; then
print_message "⚠️ Continuing with untested RTSP URL" "$YELLOW"
return 0
fi
return 1
fi
# Skip RTSP stream test, assume connection is good if port is open
print_message "✅ Port is accessible, continuing with RTSP URL" "$GREEN"
return 0
else
print_message "❌ Invalid RTSP URL format" "$RED"
fi
return 1
}
# Function to configure audio input
configure_audio_input() {
while true; do
print_message "\n🎤 Audio Capture Configuration" "$GREEN"
print_message "1) Use sound card"
print_message "2) Use RTSP stream"
print_message "3) Configure later in BirdNET-Go web interface"
print_message "❓ Select audio input method (1/2/3): " "$YELLOW" "nonewline"
read -r audio_choice
case $audio_choice in
1)
if configure_sound_card; then
break
fi
;;
2)
if configure_rtsp_stream; then
break
fi
;;
3)
print_message "⚠️ Skipping audio input configuration" "$YELLOW"
print_message "⚠️ You can configure audio input later in BirdNET-Go web interface at Audio Capture Settings" "$YELLOW"
# MODIFIED: Always include device mapping even when skipping configuration
AUDIO_ENV="--device /dev/snd"
break
;;
*)
print_message "❌ Invalid selection. Please try again." "$RED"
;;
esac
done
}
# Function to validate audio device
validate_audio_device() {
local device="$1"
# Check if user is in audio group
if ! groups "$USER" | grep &>/dev/null "\baudio\b"; then
print_message "⚠️ User $USER is not in the audio group" "$YELLOW"
if sudo usermod -aG audio "$USER"; then
print_message "✅ Added user $USER to audio group" "$GREEN"
print_message "⚠️ Please log out and log back in for group changes to take effect" "$YELLOW"
exit 0
else
print_message "❌ Failed to add user to audio group" "$RED"
return 1
fi
fi
# Test audio device access - using LC_ALL=C to force English output
if ! LC_ALL=C arecord -c 1 -f S16_LE -r 48000 -d 1 -D "$device" /dev/null 2>/dev/null; then
print_message "❌ Failed to access audio device" "$RED"
print_message "This could be due to:" "$YELLOW"
print_message " • Device is busy" "$YELLOW"
print_message " • Insufficient permissions" "$YELLOW"
print_message " • Device is not properly connected" "$YELLOW"
return 1
else
print_message "✅ Audio device validated successfully, tested 48kHz 16-bit mono capture" "$GREEN"
fi
return 0
}
# Function to configure sound card
configure_sound_card() {
while true; do
print_message "\n🎤 Detected audio devices:" "$GREEN"
# Create arrays to store device information
declare -a devices
local default_selection=0
# Capture arecord output to a variable first, forcing English locale
local arecord_output
arecord_output=$(LC_ALL=C arecord -l 2>/dev/null)
if [ -z "$arecord_output" ]; then
print_message "❌ No audio capture devices found!" "$RED"
return 1
fi
# Parse arecord output and create a numbered list
while IFS= read -r line; do
if [[ $line =~ ^card[[:space:]]+([0-9]+)[[:space:]]*:[[:space:]]*([^,]+),[[:space:]]*device[[:space:]]+([0-9]+)[[:space:]]*:[[:space:]]*([^[]+)[[:space:]]*\[(.*)\] ]]; then
card_num="${BASH_REMATCH[1]}"
card_name="${BASH_REMATCH[2]}"
device_num="${BASH_REMATCH[3]}"
device_name="${BASH_REMATCH[4]}"
device_desc="${BASH_REMATCH[5]}"
# Clean up names
card_name=$(echo "$card_name" | sed 's/\[//g' | sed 's/\]//g' | xargs)
device_name=$(echo "$device_name" | xargs)
device_desc=$(echo "$device_desc" | xargs)
devices+=("$device_desc")
# Set first USB device as default
if [[ "$card_name" =~ USB && $default_selection -eq 0 ]]; then
default_selection=${#devices[@]}
fi
echo "[$((${#devices[@]}))] Card $card_num: $card_name"
echo " Device $device_num: $device_name [$device_desc]"
fi
done <<< "$arecord_output"
if [ ${#devices[@]} -eq 0 ]; then
print_message "❌ No audio capture devices found!" "$RED"
return 1
fi
# If no USB device was found, use first device as default
if [ "$default_selection" -eq 0 ]; then
default_selection=1
fi
print_message "\nPlease select a device number from the list above (1-${#devices[@]}) [${default_selection}] or 'b' to go back: " "$YELLOW" "nonewline"
read -r selection
if [ "$selection" = "b" ]; then
return 1
fi
# If empty, use default selection
if [ -z "$selection" ]; then
selection=$default_selection
fi
if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le "${#devices[@]}" ]; then
local friendly_name="${devices[$((selection-1))]}"
# Parse the original arecord output to get the correct card and device numbers
local card_num
local device_num
local index=1
while IFS= read -r line; do
if [[ "$line" =~ ^card[[:space:]]+([0-9]+)[[:space:]]*:[[:space:]]*([^,]+),[[:space:]]*device[[:space:]]+([0-9]+) ]]; then
if [ "$index" -eq "$selection" ]; then
card_num="${BASH_REMATCH[1]}"
device_num="${BASH_REMATCH[3]}"
break
fi
((index++))
fi
done <<< "$(LC_ALL=C arecord -l)"
ALSA_CARD="$friendly_name"
print_message "✅ Selected capture device: " "$GREEN" "nonewline"
print_message "$ALSA_CARD"
# Update config file with the friendly name
sed -i "s/source: \"sysdefault\"/source: \"${ALSA_CARD}\"/" "$CONFIG_FILE"
# Comment out RTSP section
sed -i '/rtsp:/,/ # - rtsp/s/^/#/' "$CONFIG_FILE"
AUDIO_ENV="--device /dev/snd"
return 0
else
print_message "❌ Invalid selection. Please try again." "$RED"
fi
done
}
# Function to configure RTSP stream
configure_rtsp_stream() {
while true; do
print_message "\n🎥 RTSP Stream Configuration" "$GREEN"
print_message "Configure primary RTSP stream. Additional streams can be added later via web interface at Audio Capture Settings." "$YELLOW"
print_message "Enter RTSP URL (format: rtsp://user:password@address:port/path) or 'b' to go back: " "$YELLOW" "nonewline"
read -r RTSP_URL
if [ "$RTSP_URL" = "b" ]; then
return 1
fi
if [[ ! $RTSP_URL =~ ^rtsp:// ]]; then
print_message "❌ Invalid RTSP URL format. Please try again." "$RED"
continue
fi
if test_rtsp_url "$RTSP_URL"; then
print_message "✅ RTSP connection successful!" "$GREEN"
# Update config file
sed -i "s|# - rtsp://user:password@example.com/stream1| - ${RTSP_URL}|" "$CONFIG_FILE"
# Comment out audio source section
sed -i '/source: "sysdefault"/s/^/#/' "$CONFIG_FILE"
# MODIFIED: Always include device mapping even with RTSP
AUDIO_ENV="--device /dev/snd"
return 0
else
print_message "❌ Could not connect to RTSP stream. Do you want to:" "$RED"
print_message "1) Try again"
print_message "2) Go back to audio input selection"
print_message "❓ Select option (1/2): " "$YELLOW" "nonewline"
read -r retry
if [ "$retry" = "2" ]; then
return 1
fi
fi
done
}
# Function to configure audio export format
configure_audio_format() {
print_message "\n🔊 Audio Export Configuration" "$GREEN"
print_message "Select audio format for captured sounds:"
print_message "1) WAV (Uncompressed, largest files)"
print_message "2) FLAC (Lossless compression)"
print_message "3) AAC (High quality, smaller files) - default"
print_message "4) MP3 (For legacy use only)"
print_message "5) Opus (Best compression)"
while true; do
print_message "❓ Select format (1-5) [3]: " "$YELLOW" "nonewline"
read -r format_choice
# If empty, use default (AAC)
if [ -z "$format_choice" ]; then
format_choice="3"
fi
case $format_choice in
1) format="wav"; break;;
2) format="flac"; break;;
3) format="aac"; break;;
4) format="mp3"; break;;
5) format="opus"; break;;
*) print_message "❌ Invalid selection. Please try again." "$RED";;
esac
done
print_message "✅ Selected audio format: " "$GREEN" "nonewline"
print_message "$format"
# Update config file
sed -i "s/type: wav/type: $format/" "$CONFIG_FILE"
}
# Function to configure locale
configure_locale() {
print_message "\n🌐 Locale Configuration for bird species names" "$GREEN"
print_message "Available languages:" "$YELLOW"
# Create arrays for locales
declare -a locale_codes=("en-uk" "en-us" "af" "ar" "bg" "ca" "cs" "zh" "hr" "da" "nl" "et" "fi" "fr" "de" "el" "he" "hi-in" "hu" "is" "id" "it" "ja" "ko" "lv" "lt" "ml" "no" "pl" "pt" "pt-br" "pt-pt" "ro" "ru" "sr" "sk" "sl" "es" "sv" "th" "tr" "uk" "vi-vn")
declare -a locale_names=("English (UK)" "English (US)" "Afrikaans" "Arabic" "Bulgarian" "Catalan" "Czech" "Chinese" "Croatian" "Danish" "Dutch" "Estonian" "Finnish" "French" "German" "Greek" "Hebrew" "Hindi" "Hungarian" "Icelandic" "Indonesian" "Italian" "Japanese" "Korean" "Latvian" "Lithuanian" "Malayalam" "Norwegian" "Polish" "Portuguese" "Brazilian Portuguese" "Portuguese (Portugal)" "Romanian" "Russian" "Serbian" "Slovak" "Slovenian" "Spanish" "Swedish" "Thai" "Turkish" "Ukrainian" "Vietnamese")
# Display available locales
for i in "${!locale_codes[@]}"; do
printf "%2d) %-30s" "$((i+1))" "${locale_names[i]}"
if [ $((i % 2)) -eq 1 ]; then
echo
fi
done
echo
# Add a final newline if the last row is incomplete
if [ $((${#locale_codes[@]} % 2)) -eq 1 ]; then
echo
fi
while true; do
print_message "❓ Select your language (1-${#locale_codes[@]}): " "$YELLOW" "nonewline"
read -r selection
if [[ "$selection" =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le "${#locale_codes[@]}" ]; then
LOCALE_CODE="${locale_codes[$((selection-1))]}"
print_message "✅ Selected language: " "$GREEN" "nonewline"
print_message "${locale_names[$((selection-1))]}"
# Update config file - fixed to replace the entire locale value
sed -i "s/locale: [a-zA-Z0-9_-]*/locale: ${LOCALE_CODE}/" "$CONFIG_FILE"
break
else
print_message "❌ Invalid selection. Please try again." "$RED"
fi
done
}
# Function to get location from NordVPN and OpenStreetMap
get_ip_location() {
# First try NordVPN's service for city/country
local nordvpn_info
if nordvpn_info=$(curl -s "https://nordvpn.com/wp-admin/admin-ajax.php" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "action=get_user_info_data" 2>/dev/null) && [ -n "$nordvpn_info" ]; then
# Check if the response is valid JSON and contains the required fields
if echo "$nordvpn_info" | jq -e '.city and .country' >/dev/null 2>&1; then
local city
local country
city=$(echo "$nordvpn_info" | jq -r '.city')
country=$(echo "$nordvpn_info" | jq -r '.country')
if [ "$city" != "null" ] && [ "$country" != "null" ] && [ -n "$city" ] && [ -n "$country" ]; then
# Use OpenStreetMap to get precise coordinates
local coordinates
coordinates=$(curl -s "https://nominatim.openstreetmap.org/search?city=${city}&country=${country}&format=json" | jq -r '.[0] | "\(.lat) \(.lon)"')
if [ -n "$coordinates" ] && [ "$coordinates" != "null null" ]; then
local lat
local lon
lat=$(echo "$coordinates" | cut -d' ' -f1)
lon=$(echo "$coordinates" | cut -d' ' -f2)
echo "$lat|$lon|$city|$country"