-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
1030 lines (875 loc) · 31 KB
/
Copy pathinstall.sh
File metadata and controls
1030 lines (875 loc) · 31 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
#
# Portable AirPlay Receiver - Installation Script
# Run as: sudo ./install.sh
#
# Robust installer with error handling and recovery
#
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Get the directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="/tmp/airplay_install.log"
# Detect the actual user (not root)
# Priority: SUDO_USER > user who owns the script directory > first user in /home
if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ]; then
USER_NAME="$SUDO_USER"
elif [ -n "$(stat -c '%U' "$SCRIPT_DIR" 2>/dev/null)" ] && [ "$(stat -c '%U' "$SCRIPT_DIR")" != "root" ]; then
USER_NAME="$(stat -c '%U' "$SCRIPT_DIR")"
else
USER_NAME=$(ls /home | grep -v lost+found | head -1)
fi
# Set install directory based on detected user
INSTALL_DIR="/home/${USER_NAME}/airplay"
# Initialize log
echo "Installation started: $(date)" > "$LOG_FILE"
#######################################
# Logging and output functions
#######################################
log() {
echo "[$(date '+%H:%M:%S')] $1" >> "$LOG_FILE"
}
print_status() {
echo -e "${GREEN}[✓]${NC} $1"
log "SUCCESS: $1"
}
print_warning() {
echo -e "${YELLOW}[!]${NC} $1"
log "WARNING: $1"
}
print_error() {
echo -e "${RED}[✗]${NC} $1"
log "ERROR: $1"
}
print_info() {
echo -e "${BLUE}[i]${NC} $1"
log "INFO: $1"
}
print_step() {
echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN} $1${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "STEP: $1"
}
#######################################
# Helper functions
#######################################
command_exists() {
command -v "$1" >/dev/null 2>&1
}
service_exists() {
systemctl list-unit-files | grep -q "$1"
}
retry_command() {
local max_attempts=$1
local delay=$2
shift 2
local cmd="$@"
for ((i=1; i<=max_attempts; i++)); do
if eval "$cmd" >> "$LOG_FILE" 2>&1; then
return 0
fi
if [ $i -lt $max_attempts ]; then
print_warning "Attempt $i failed, retrying in ${delay}s..."
sleep $delay
fi
done
return 1
}
check_internet() {
if ping -c 1 google.com >/dev/null 2>&1 || ping -c 1 8.8.8.8 >/dev/null 2>&1; then
return 0
fi
return 1
}
#######################################
# Main installation
#######################################
echo ""
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Portable AirPlay Receiver Installer ║${NC}"
echo -e "${GREEN}║ v1.0 - Robust Edition ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
echo ""
# Check if running as root
if [ "$EUID" -ne 0 ]; then
print_error "Please run as root: sudo ./install.sh"
exit 1
fi
# Validate detected user
if [ -z "$USER_NAME" ] || [ ! -d "/home/${USER_NAME}" ]; then
print_error "Could not detect user. Please run as: sudo -E ./install.sh"
print_error "Or set USER_NAME manually in the script."
exit 1
fi
print_info "Detected user: ${USER_NAME}"
print_info "Installation directory: ${INSTALL_DIR}"
print_info "Log file: ${LOG_FILE}"
echo ""
# Check internet connectivity
print_info "Checking internet connectivity..."
if ! check_internet; then
print_error "No internet connection. Please connect to the internet first."
exit 1
fi
print_status "Internet connection OK"
#######################################
# Hardware Pre-requisite Check
#######################################
echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW} IMPORTANT: Hardware Check${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "Before continuing, please ensure:"
echo -e " ${GREEN}1.${NC} I2S DAC (PCM5102/HiFiBerry) is connected"
echo -e " ${GREEN}2.${NC} OLED display is connected (I2C)"
echo -e " ${GREEN}3.${NC} Rotary encoder is connected (GPIO)"
echo -e " ${GREEN}4.${NC} RGB LED is connected (optional)"
echo ""
read -p "Is all hardware connected? (y/n): " hw_confirm
if [[ ! "$hw_confirm" =~ ^[Yy]$ ]]; then
echo ""
print_error "Please connect all hardware and run the installer again."
print_info "The I2S DAC must be connected for audio configuration."
exit 1
fi
print_status "Hardware confirmation received"
#######################################
# Step 1: System Update
#######################################
print_step "[1/10] Updating System"
if retry_command 3 5 "apt update"; then
print_status "Package lists updated"
else
print_warning "Failed to update package lists, continuing anyway..."
fi
# Upgrade is optional, don't fail on it
apt upgrade -y >> "$LOG_FILE" 2>&1 || print_warning "System upgrade had warnings (non-critical)"
print_status "System update complete"
#######################################
# Step 2: Install Dependencies
#######################################
print_step "[2/10] Installing Dependencies"
PACKAGES=(
build-essential git autoconf automake libtool
libpopt-dev libconfig-dev libasound2-dev libavahi-client-dev
libssl-dev libsoxr-dev libplist-dev libsodium-dev
libavutil-dev libavcodec-dev libavformat-dev
libgcrypt20-dev libxxhash-dev uuid-dev xmltoman xxd
python3-pip python3-venv python3-dev python3-smbus python3-pil
i2c-tools hostapd dnsmasq avahi-daemon
libswresample-dev # Additional dependency that might be needed
)
# Install packages with retry
FAILED_PACKAGES=()
for pkg in "${PACKAGES[@]}"; do
if dpkg -s "$pkg" >/dev/null 2>&1; then
echo -n "." # Already installed
else
if apt install -y "$pkg" >> "$LOG_FILE" 2>&1; then
echo -n "+"
else
FAILED_PACKAGES+=("$pkg")
echo -n "x"
fi
fi
done
echo ""
if [ ${#FAILED_PACKAGES[@]} -gt 0 ]; then
print_warning "Some packages failed to install: ${FAILED_PACKAGES[*]}"
print_info "Attempting to fix..."
apt --fix-broken install -y >> "$LOG_FILE" 2>&1
fi
print_status "Dependencies installed"
#######################################
# Step 3: Enable Interfaces
#######################################
print_step "[3/10] Enabling I2C and SPI"
# Enable I2C
if raspi-config nonint do_i2c 0 >> "$LOG_FILE" 2>&1; then
print_status "I2C enabled"
else
print_warning "Could not enable I2C via raspi-config, trying manual method..."
if ! grep -q "^dtparam=i2c_arm=on" /boot/firmware/config.txt 2>/dev/null && \
! grep -q "^dtparam=i2c_arm=on" /boot/config.txt 2>/dev/null; then
echo "dtparam=i2c_arm=on" >> /boot/firmware/config.txt 2>/dev/null || \
echo "dtparam=i2c_arm=on" >> /boot/config.txt 2>/dev/null
fi
fi
# Enable SPI
if raspi-config nonint do_spi 0 >> "$LOG_FILE" 2>&1; then
print_status "SPI enabled"
else
print_warning "Could not enable SPI via raspi-config"
fi
#######################################
# Step 4: Configure I2S DAC
#######################################
print_step "[4/10] Configuring I2S DAC"
# Determine boot config location
if [ -f "/boot/firmware/config.txt" ]; then
BOOT_CONFIG="/boot/firmware/config.txt"
elif [ -f "/boot/config.txt" ]; then
BOOT_CONFIG="/boot/config.txt"
else
print_error "Could not find boot config file!"
exit 1
fi
print_info "Using boot config: ${BOOT_CONFIG}"
# Backup original config
if [ ! -f "${BOOT_CONFIG}.backup.original" ]; then
cp "$BOOT_CONFIG" "${BOOT_CONFIG}.backup.original"
print_status "Boot config backed up"
fi
# Disable onboard audio
sed -i 's/^dtparam=audio=on/#dtparam=audio=on/' "$BOOT_CONFIG"
# Add I2S DAC config if not present
if ! grep -q "dtoverlay=hifiberry-dac" "$BOOT_CONFIG"; then
cat >> "$BOOT_CONFIG" << 'EOF'
# I2S DAC Configuration (AirPlay Receiver)
dtparam=i2s=on
dtoverlay=hifiberry-dac
EOF
print_status "I2S DAC configuration added"
else
print_info "I2S DAC already configured"
fi
# Enable hardware watchdog
if ! grep -q "dtparam=watchdog=on" "$BOOT_CONFIG"; then
echo "" >> "$BOOT_CONFIG"
echo "# Hardware watchdog for auto-recovery" >> "$BOOT_CONFIG"
echo "dtparam=watchdog=on" >> "$BOOT_CONFIG"
print_status "Hardware watchdog enabled"
else
print_info "Hardware watchdog already enabled"
fi
#######################################
# Step 5: Install NQPTP
#######################################
print_step "[5/10] Installing NQPTP (AirPlay 2 Timing)"
cd /tmp
# Clean up any previous attempts
rm -rf nqptp 2>/dev/null
if git clone https://github.com/mikebrady/nqptp.git >> "$LOG_FILE" 2>&1; then
cd nqptp
if autoreconf -fi >> "$LOG_FILE" 2>&1 && \
./configure --with-systemd-startup >> "$LOG_FILE" 2>&1 && \
make -j$(nproc) >> "$LOG_FILE" 2>&1; then
# Try make install, handle errors
if ! make install >> "$LOG_FILE" 2>&1; then
print_warning "make install had issues, trying manual installation..."
# Manual installation
cp nqptp /usr/local/bin/ 2>/dev/null || true
# Create systemd service manually
mkdir -p /lib/systemd/system
if [ -f "nqptp.service" ]; then
cp nqptp.service /lib/systemd/system/
else
cat > /lib/systemd/system/nqptp.service << 'EOF'
[Unit]
Description=NQPTP AirPlay 2 Timing Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/nqptp
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
fi
fi
# Create nqptp user if needed
getent group nqptp &>/dev/null || groupadd -r nqptp 2>/dev/null || true
getent passwd nqptp &>/dev/null || useradd -r -M -g nqptp -s /usr/sbin/nologin nqptp 2>/dev/null || true
systemctl daemon-reload
systemctl enable nqptp >> "$LOG_FILE" 2>&1 || true
systemctl start nqptp >> "$LOG_FILE" 2>&1 || true
if systemctl is-active --quiet nqptp; then
print_status "NQPTP installed and running"
else
print_warning "NQPTP installed but not running (may work after reboot)"
fi
else
print_error "Failed to build NQPTP"
exit 1
fi
else
print_error "Failed to clone NQPTP repository"
exit 1
fi
#######################################
# Step 6: Install Shairport Sync
#######################################
print_step "[6/10] Installing Shairport Sync"
cd /tmp
# Clean up any previous attempts
rm -rf shairport-sync 2>/dev/null
if git clone https://github.com/mikebrady/shairport-sync.git >> "$LOG_FILE" 2>&1; then
cd shairport-sync
print_info "Configuring Shairport Sync (with metadata support)..."
if autoreconf -fi >> "$LOG_FILE" 2>&1 && \
./configure --sysconfdir=/etc --with-alsa \
--with-soxr --with-avahi --with-ssl=openssl \
--with-systemd --with-airplay-2 \
--with-metadata >> "$LOG_FILE" 2>&1; then
print_info "Building Shairport Sync (this may take a few minutes)..."
if make -j$(nproc) >> "$LOG_FILE" 2>&1; then
# Try make install - this often fails on systemd service part
print_info "Installing Shairport Sync..."
make install >> "$LOG_FILE" 2>&1
INSTALL_RESULT=$?
# Verify the binary was installed
if [ ! -f "/usr/local/bin/shairport-sync" ]; then
print_warning "Binary not in expected location, copying manually..."
cp shairport-sync /usr/local/bin/
chmod +x /usr/local/bin/shairport-sync
fi
# Verify binary works
if /usr/local/bin/shairport-sync --version >> "$LOG_FILE" 2>&1; then
print_status "Shairport Sync binary installed successfully"
else
print_error "Shairport Sync binary not working!"
exit 1
fi
# Handle systemd service manually (common failure point)
print_info "Setting up systemd service..."
mkdir -p /lib/systemd/system
# Try to use the generated service file, or create one
if [ -f "scripts/shairport-sync.service-avahi" ]; then
cp scripts/shairport-sync.service-avahi /lib/systemd/system/shairport-sync.service
elif [ -f "scripts/shairport-sync.service" ]; then
cp scripts/shairport-sync.service /lib/systemd/system/shairport-sync.service
else
# Create service file manually
cat > /lib/systemd/system/shairport-sync.service << 'EOF'
[Unit]
Description=Shairport Sync - AirPlay Audio Receiver
After=sound.target network-online.target avahi-daemon.service nqptp.service
Wants=avahi-daemon.service
Requires=nqptp.service
[Service]
Type=simple
ExecStart=/usr/local/bin/shairport-sync
Restart=always
RestartSec=5
User=shairport-sync
Group=shairport-sync
[Install]
WantedBy=multi-user.target
EOF
fi
# Create shairport-sync user if needed
getent group shairport-sync &>/dev/null || groupadd -r shairport-sync 2>/dev/null || true
getent passwd shairport-sync &>/dev/null || useradd -r -M -g shairport-sync -s /usr/sbin/nologin -G audio shairport-sync 2>/dev/null || true
# Copy default config if not exists
if [ ! -f "/etc/shairport-sync.conf" ]; then
if [ -f "scripts/shairport-sync.conf" ]; then
cp scripts/shairport-sync.conf /etc/shairport-sync.conf
fi
fi
systemctl daemon-reload
systemctl enable shairport-sync >> "$LOG_FILE" 2>&1
print_status "Shairport Sync installed successfully"
else
print_error "Failed to build Shairport Sync"
exit 1
fi
else
print_error "Failed to configure Shairport Sync"
print_info "Check log file for details: $LOG_FILE"
exit 1
fi
else
print_error "Failed to clone Shairport Sync repository"
exit 1
fi
#######################################
# Step 7: Configure System Files
#######################################
print_step "[7/10] Configuring System Files"
#---------------------------------------
# Helper function: Update or add config value in shairport-sync.conf
# Usage: update_shairport_config "section" "key" "value"
#---------------------------------------
update_shairport_config() {
local file="/etc/shairport-sync.conf"
local section="$1"
local key="$2"
local value="$3"
# Check if section exists
if grep -q "^${section}\s*=" "$file" 2>/dev/null; then
# Section exists - check if key exists in section
if grep -A 20 "^${section}\s*=" "$file" | grep -q "^\s*${key}\s*="; then
# Key exists - update it
sed -i "/^${section}\s*=/,/^};/s|^\(\s*\)${key}\s*=.*|\1${key} = ${value};|" "$file"
else
# Key doesn't exist - add it before closing brace
sed -i "/^${section}\s*=/,/^};/s|^\(};.*\)|\t${key} = ${value};\n\1|" "$file"
fi
fi
}
#---------------------------------------
# Shairport Sync config - PATCH instead of replace
#---------------------------------------
SHAIRPORT_CONF="/etc/shairport-sync.conf"
if [ -f "$SHAIRPORT_CONF" ]; then
print_info "Existing shairport-sync.conf found, patching..."
# Backup original
[ ! -f "${SHAIRPORT_CONF}.backup" ] && cp "$SHAIRPORT_CONF" "${SHAIRPORT_CONF}.backup"
# Update specific values we need
update_shairport_config "general" "name" '"Portable AirPlay"'
update_shairport_config "general" "interpolation" '"soxr"'
update_shairport_config "general" "output_backend" '"alsa"'
update_shairport_config "general" "volume_range_db" "60"
# Update ALSA settings - use default which routes through softvol in asound.conf
update_shairport_config "alsa" "output_device" '"default"'
# Add session control hooks if not present
if ! grep -q "run_this_before_entering_active_state" "$SHAIRPORT_CONF"; then
# Check if sessioncontrol section exists
if grep -q "^sessioncontrol\s*=" "$SHAIRPORT_CONF"; then
# Add hooks to existing section
sed -i "/^sessioncontrol\s*=/,/^};/s|^\(};.*\)|\trun_this_before_entering_active_state = \"/usr/local/bin/airplay_on_start.sh\";\n\trun_this_after_exiting_active_state = \"/usr/local/bin/airplay_on_stop.sh\";\n\1|" "$SHAIRPORT_CONF"
else
# Add new sessioncontrol section at end
cat >> "$SHAIRPORT_CONF" << EOF
sessioncontrol = {
run_this_before_entering_active_state = "/usr/local/bin/airplay_on_start.sh";
run_this_after_exiting_active_state = "/usr/local/bin/airplay_on_stop.sh";
active_state_timeout = 10.0;
};
EOF
fi
else
# Update existing hooks path
sed -i "s|run_this_before_entering_active_state = \".*\"|run_this_before_entering_active_state = \"/usr/local/bin/airplay_on_start.sh\"|g" "$SHAIRPORT_CONF"
sed -i "s|run_this_after_exiting_active_state = \".*\"|run_this_after_exiting_active_state = \"/usr/local/bin/airplay_on_stop.sh\"|g" "$SHAIRPORT_CONF"
fi
print_status "Shairport Sync config patched"
else
# No existing config - create new one
print_info "Creating new shairport-sync.conf..."
cat > "$SHAIRPORT_CONF" << EOF
// Shairport Sync Configuration
// Portable AirPlay Receiver
//
// Uses "default" output which routes through softvol in asound.conf
// PCM5102 DAC has no hardware mixer, so softvol provides software volume
general = {
name = "Portable AirPlay";
output_backend = "alsa";
interpolation = "soxr";
volume_range_db = 60;
};
alsa = {
output_device = "default";
};
sessioncontrol = {
run_this_before_entering_active_state = "/usr/local/bin/airplay_on_start.sh";
run_this_after_exiting_active_state = "/usr/local/bin/airplay_on_stop.sh";
active_state_timeout = 10.0;
};
// Metadata settings for track info display on OLED
metadata = {
enabled = "yes";
include_cover_art = "no";
pipe_name = "/tmp/shairport-sync-metadata";
pipe_timeout = 5000;
};
EOF
print_status "Shairport Sync config created"
fi
# Add metadata section if not present (for patched configs)
if ! grep -q "^metadata\s*=" "$SHAIRPORT_CONF"; then
print_info "Adding metadata section to config..."
cat >> "$SHAIRPORT_CONF" << 'EOF'
// Metadata settings for track info display on OLED
metadata = {
enabled = "yes";
include_cover_art = "no";
pipe_name = "/tmp/shairport-sync-metadata";
pipe_timeout = 5000;
};
EOF
print_status "Metadata section added"
fi
#---------------------------------------
# ALSA config - Use card NAME for reliability
#---------------------------------------
ALSA_CONF="/etc/asound.conf"
# Backup existing config
if [ -f "$ALSA_CONF" ] && [ ! -f "${ALSA_CONF}.backup" ]; then
cp "$ALSA_CONF" "${ALSA_CONF}.backup"
fi
print_info "Creating ALSA config with softvol (PCM5102 has no hardware mixer)..."
cat > "$ALSA_CONF" << 'EOF'
# ALSA configuration for I2S DAC (HiFiBerry/PCM5102)
# PCM5102 has NO hardware volume control, so we use softvol plugin
# The softvol creates a software mixer called "SoftVol" on card 1
pcm.!default {
type plug
slave.pcm "softvol"
}
pcm.softvol {
type softvol
slave.pcm "hw:1,0"
control {
name "SoftVol"
card 1
}
min_dB -51.0
max_dB 0.0
}
ctl.!default {
type hw
card 1
}
EOF
print_status "ALSA config created with softvol (card 1, mixer: SoftVol)"
#---------------------------------------
# Hostapd config - Create/update for AP mode
#---------------------------------------
mkdir -p /etc/hostapd
HOSTAPD_CONF="/etc/hostapd/hostapd.conf"
if [ -f "$HOSTAPD_CONF" ]; then
print_info "Existing hostapd.conf found, checking settings..."
[ ! -f "${HOSTAPD_CONF}.backup" ] && cp "$HOSTAPD_CONF" "${HOSTAPD_CONF}.backup"
# Update SSID if different
if ! grep -q "ssid=AirPlay-Setup" "$HOSTAPD_CONF"; then
sed -i 's/^ssid=.*/ssid=AirPlay-Setup/' "$HOSTAPD_CONF" 2>/dev/null || \
echo "ssid=AirPlay-Setup" >> "$HOSTAPD_CONF"
fi
# Ensure interface is wlan0
if ! grep -q "^interface=wlan0" "$HOSTAPD_CONF"; then
sed -i 's/^interface=.*/interface=wlan0/' "$HOSTAPD_CONF" 2>/dev/null || \
echo "interface=wlan0" >> "$HOSTAPD_CONF"
fi
print_status "Hostapd config verified"
else
cat > "$HOSTAPD_CONF" << 'EOF'
# Hostapd configuration for AirPlay Setup AP mode
interface=wlan0
driver=nl80211
ssid=AirPlay-Setup
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=0
EOF
print_status "Hostapd config created"
fi
# Point hostapd to its config if default file exists
if [ -f "/etc/default/hostapd" ]; then
if ! grep -q '^DAEMON_CONF="/etc/hostapd/hostapd.conf"' /etc/default/hostapd; then
sed -i 's|^#\?DAEMON_CONF=.*|DAEMON_CONF="/etc/hostapd/hostapd.conf"|' /etc/default/hostapd
fi
fi
#---------------------------------------
# dnsmasq config - Append if not present
#---------------------------------------
DNSMASQ_CONF="/etc/dnsmasq.conf"
if [ -f "$DNSMASQ_CONF" ]; then
[ ! -f "${DNSMASQ_CONF}.backup" ] && cp "$DNSMASQ_CONF" "${DNSMASQ_CONF}.backup"
# Only add our config if not already present
if ! grep -q "# AirPlay Setup AP mode" "$DNSMASQ_CONF"; then
print_info "Adding AP mode config to dnsmasq..."
cat >> "$DNSMASQ_CONF" << 'EOF'
# AirPlay Setup AP mode
# Only active when AP mode is enabled
interface=wlan0
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
address=/#/192.168.4.1
EOF
print_status "dnsmasq config updated"
else
print_info "dnsmasq already configured for AP mode"
fi
else
cat > "$DNSMASQ_CONF" << 'EOF'
# dnsmasq configuration
# AirPlay Setup AP mode
# Only active when AP mode is enabled
interface=wlan0
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
address=/#/192.168.4.1
EOF
print_status "dnsmasq config created"
fi
#---------------------------------------
# Disable AP services by default (controlled by Python app)
#---------------------------------------
systemctl disable hostapd >> "$LOG_FILE" 2>&1 || true
systemctl disable dnsmasq >> "$LOG_FILE" 2>&1 || true
systemctl stop hostapd 2>/dev/null || true
systemctl stop dnsmasq 2>/dev/null || true
#---------------------------------------
# WiFi Power Management - Disable for reliable connections
#---------------------------------------
print_info "Configuring WiFi power management..."
# Disable roaming on Broadcom WiFi driver (Pi 3/Zero W)
mkdir -p /etc/modprobe.d
cat > /etc/modprobe.d/brcmfmac.conf << 'EOF'
# Disable roaming for more stable WiFi connections
options brcmfmac roamoff=1
EOF
# Disable WiFi power save in NetworkManager
mkdir -p /etc/NetworkManager/conf.d
cat > /etc/NetworkManager/conf.d/wifi-powersave.conf << 'EOF'
[connection]
# Disable WiFi power save (2 = disable, 3 = enable)
wifi.powersave = 2
EOF
print_status "WiFi power management configured"
print_status "Configuration files ready"
#######################################
# Step 8: Set up Python Environment
#######################################
print_step "[8/10] Setting up Python Environment"
# Create install directory
mkdir -p "${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}/scripts"
# Copy project files
if [ -d "${SCRIPT_DIR}/src" ]; then
cp -r "${SCRIPT_DIR}/src" "${INSTALL_DIR}/"
print_status "Source files copied"
else
print_error "Source directory not found: ${SCRIPT_DIR}/src"
exit 1
fi
if [ -d "${SCRIPT_DIR}/templates" ]; then
cp -r "${SCRIPT_DIR}/templates" "${INSTALL_DIR}/"
print_status "Templates copied"
fi
# Create virtual environment
print_info "Creating Python virtual environment..."
cd "${INSTALL_DIR}"
if python3 -m venv venv >> "$LOG_FILE" 2>&1; then
print_status "Virtual environment created"
else
print_error "Failed to create virtual environment"
exit 1
fi
# Activate and install packages
source venv/bin/activate
print_info "Installing Python packages..."
pip install --upgrade pip >> "$LOG_FILE" 2>&1
PYTHON_PACKAGES=(
"RPi.GPIO"
"adafruit-circuitpython-ssd1306"
"adafruit-blinka"
"Pillow"
"rpi_ws281x"
"adafruit-circuitpython-neopixel"
"flask"
"pyalsaaudio"
"paho-mqtt"
)
FAILED_PY_PACKAGES=()
for pkg in "${PYTHON_PACKAGES[@]}"; do
if pip install "$pkg" >> "$LOG_FILE" 2>&1; then
echo -n "+"
else
FAILED_PY_PACKAGES+=("$pkg")
echo -n "x"
fi
done
echo ""
if [ ${#FAILED_PY_PACKAGES[@]} -gt 0 ]; then
print_warning "Some Python packages failed: ${FAILED_PY_PACKAGES[*]}"
print_info "Trying alternative package names..."
# Try alternatives
for pkg in "${FAILED_PY_PACKAGES[@]}"; do
case "$pkg" in
"pyalsaaudio")
pip install alsaaudio >> "$LOG_FILE" 2>&1 || true
;;
esac
done
fi
deactivate
print_status "Python environment ready"
#######################################
# Step 9: Create Helper Scripts
#######################################
print_step "[9/10] Creating Helper Scripts"
# Playback status scripts for Shairport Sync hooks
# Install to /usr/local/bin/ so shairport-sync user can execute them
cat > "/usr/local/bin/airplay_on_start.sh" << 'EOF'
#!/bin/bash
echo "playing" > /tmp/airplay_status
EOF
cat > "/usr/local/bin/airplay_on_stop.sh" << 'EOF'
#!/bin/bash
echo "idle" > /tmp/airplay_status
EOF
chmod 755 /usr/local/bin/airplay_on_start.sh
chmod 755 /usr/local/bin/airplay_on_stop.sh
# Create status file with world-writable permissions for shairport-sync
touch /tmp/airplay_status
chmod 666 /tmp/airplay_status
echo "idle" > /tmp/airplay_status
# Create a convenience script to run manually
cat > "${INSTALL_DIR}/run.sh" << EOF
#!/bin/bash
cd "${INSTALL_DIR}"
source venv/bin/activate
python3 src/main.py
EOF
chmod +x "${INSTALL_DIR}/run.sh"
# Set ownership
chown -R "${USER_NAME}:${USER_NAME}" "${INSTALL_DIR}"
# Add user to hardware access groups (gpio, i2c, spi)
print_info "Adding ${USER_NAME} to hardware groups..."
for grp in gpio i2c spi audio; do
if getent group "$grp" >/dev/null 2>&1; then
usermod -a -G "$grp" "${USER_NAME}" 2>/dev/null && \
echo -n " +$grp" || echo -n " ~$grp"
fi
done
echo ""
print_status "Helper scripts created"
#######################################
# Step 10: Install Systemd Services
#######################################
print_step "[10/10] Installing Systemd Services"
# Main UI service - create fresh to avoid group issues
cat > /etc/systemd/system/airplay-ui.service << EOF
[Unit]
Description=Portable AirPlay UI Service
After=network.target shairport-sync.service
Wants=shairport-sync.service
[Service]
Type=simple
User=${USER_NAME}
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/venv/bin/python3 ${INSTALL_DIR}/src/main.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
EOF
print_status "UI service created"
# Wi-Fi portal service (runs as root for network control)
cat > /etc/systemd/system/wifi-portal.service << EOF
[Unit]
Description=AirPlay Wi-Fi Setup Portal
After=network.target hostapd.service dnsmasq.service
Wants=hostapd.service dnsmasq.service
[Service]
Type=simple
User=root
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/venv/bin/python3 ${INSTALL_DIR}/src/wifi_portal.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
EOF
print_status "Wi-Fi portal service created"
# Reload and enable
systemctl daemon-reload
systemctl enable airplay-ui >> "$LOG_FILE" 2>&1
print_status "Systemd services configured"
#######################################
# Create Default Config
#######################################
# Auto-detect if WiFi is already configured and connected
WIFI_CONFIGURED="false"
WIFI_SSID=""
if iwgetid -r >/dev/null 2>&1; then
WIFI_SSID=$(iwgetid -r)
if [ -n "$WIFI_SSID" ]; then
WIFI_CONFIGURED="true"
print_info "WiFi already connected to: ${WIFI_SSID}"
fi
fi
cat > "${INSTALL_DIR}/device_config.json" << EOF
{
"device_name": "Portable AirPlay",
"volume": 70,
"muted": false,
"led_enabled": true,
"led_brightness": 20,
"display_timeout_enabled": true,
"display_timeout_secs": 60,
"screensaver_clock": true,
"power_saver_enabled": true,
"audio_profile": "normal",
"wifi_configured": ${WIFI_CONFIGURED},
"wifi_ssid": "${WIFI_SSID}",
"saved_networks": []
}
EOF
chown "${USER_NAME}:${USER_NAME}" "${INSTALL_DIR}/device_config.json"
if [ "$WIFI_CONFIGURED" = "true" ]; then
print_status "WiFi marked as configured (connected to ${WIFI_SSID})"
else
print_warning "WiFi not detected - AP mode will start on first boot"
fi
#######################################
# Cleanup
#######################################
print_info "Cleaning up temporary files..."
cd /tmp
rm -rf nqptp shairport-sync 2>/dev/null || true
#######################################
# Final Summary
#######################################
echo ""
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Installation Complete! ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
echo ""
# Verify installations
echo -e "${BLUE}Verification:${NC}"
if command_exists shairport-sync; then
VERSION=$(shairport-sync -V 2>&1 | head -1)
echo -e " ${GREEN}✓${NC} Shairport Sync: $VERSION"
if echo "$VERSION" | grep -q "metadata"; then
echo -e " ${GREEN}✓${NC} Metadata support: Enabled"
else
echo -e " ${YELLOW}!${NC} Metadata support: Not detected"
fi
else
echo -e " ${RED}✗${NC} Shairport Sync: Not found"
fi
if systemctl is-enabled nqptp >/dev/null 2>&1; then