-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild-pi-image.sh
More file actions
executable file
·1326 lines (1110 loc) · 41.8 KB
/
build-pi-image.sh
File metadata and controls
executable file
·1326 lines (1110 loc) · 41.8 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
# LabLink Raspberry Pi Image Builder
# Creates a bootable Raspberry Pi image with LabLink pre-installed
#
# Requirements: Linux host with root access, qemu-user-static, kpartx
# Usage: sudo ./build-pi-image.sh [output-image-name.img]
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# Configuration
PI_MODEL="${PI_MODEL:-5}" # Default to Pi 5
PI_OS_VERSION="${PI_OS_VERSION:-2024-03-15}"
# Select appropriate image URL based on Pi model
case "$PI_MODEL" in
"3")
# Pi 3 uses 32-bit armhf image
PI_OS_URL="https://downloads.raspberrypi.org/raspios_lite_armhf/images/raspios_lite_armhf-2024-03-15/2024-03-15-raspios-bookworm-armhf-lite.img.xz"
;;
"4")
# Pi 4 can use 64-bit arm64 image
PI_OS_URL="https://downloads.raspberrypi.org/raspios_lite_arm64/images/raspios_lite_arm64-2024-03-15/2024-03-15-raspios-bookworm-arm64-lite.img.xz"
;;
"5"|*)
# Pi 5 uses 64-bit arm64 image (default)
PI_OS_URL="https://downloads.raspberrypi.org/raspios_lite_arm64/images/raspios_lite_arm64-2024-03-15/2024-03-15-raspios-bookworm-arm64-lite.img.xz"
;;
esac
# Use environment variable if set, otherwise use command-line arg, otherwise default with date
OUTPUT_IMAGE="${OUTPUT_IMAGE:-${1:-lablink-pi-$(date +%Y%m%d).img}}"
WORK_DIR="/tmp/lablink-pi-build"
MOUNT_BOOT="$WORK_DIR/boot"
MOUNT_ROOT="$WORK_DIR/root"
# LabLink configuration
LABLINK_VERSION="${LABLINK_VERSION:-latest}"
LABLINK_HOSTNAME="${LABLINK_HOSTNAME:-lablink}"
ENABLE_SSH="${ENABLE_SSH:-yes}"
WIFI_SSID="${WIFI_SSID:-}"
WIFI_PASSWORD="${WIFI_PASSWORD:-}"
LABLINK_ADMIN_PASSWORD="${LABLINK_ADMIN_PASSWORD:-lablink}"
# Functions
print_header() {
echo -e "${BLUE}"
echo "╔═══════════════════════════════════════════════════════╗"
echo "║ ║"
echo "║ LabLink Raspberry Pi Image Builder ║"
echo "║ ║"
echo "╚═══════════════════════════════════════════════════════╝"
echo -e "${NC}"
}
print_step() {
echo -e "${GREEN}[$(date +%H:%M:%S)]${NC} $1" >&2
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1" >&2
}
check_root() {
if [ "$EUID" -ne 0 ]; then
print_error "This script must be run as root (use sudo)"
exit 1
fi
}
check_dependencies() {
print_step "Checking dependencies..."
local missing=()
for cmd in wget xz kpartx qemu-arm-static losetup parted; do
if ! command -v $cmd &> /dev/null; then
missing+=($cmd)
fi
done
if [ ${#missing[@]} -gt 0 ]; then
print_error "Missing dependencies: ${missing[*]}"
echo ""
echo "Install with:"
echo " Ubuntu/Debian: sudo apt install wget xz-utils kpartx qemu-user-static parted"
echo " Fedora: sudo dnf install wget xz kpartx qemu-user-static parted"
exit 1
fi
print_step "All dependencies found"
}
download_pi_os() {
print_step "Downloading Raspberry Pi OS..."
local pi_os_file="$WORK_DIR/raspios.img.xz"
if [ -f "$pi_os_file" ]; then
print_step "Using cached Raspberry Pi OS image"
else
wget -O "$pi_os_file" "$PI_OS_URL" || {
print_error "Failed to download Raspberry Pi OS"
exit 1
}
fi
print_step "Extracting image..."
xz -d -v -k -f "$pi_os_file" || {
print_error "Failed to extract Raspberry Pi OS image"
exit 1
}
local extracted_img="${pi_os_file%.xz}"
# Verify extraction succeeded
if [ ! -f "$extracted_img" ]; then
print_error "Extracted image not found at: $extracted_img"
ls -lh "$WORK_DIR/" || true
exit 1
fi
print_step "Image extracted successfully: $extracted_img"
echo "$extracted_img"
}
expand_image() {
local img_file="$1"
local extra_space_mb="$2"
print_step "Expanding image by ${extra_space_mb}MB..."
# Debug: verify file exists before dd
if [ ! -f "$img_file" ]; then
print_error "Image file not found before expand: $img_file"
ls -lh "$(dirname "$img_file")/" || true
exit 1
fi
print_step "Image file verified: $(ls -lh "$img_file")"
# Add extra space for LabLink installation
if ! dd if=/dev/zero bs=1M count=$extra_space_mb >> "$img_file" 2>/dev/null; then
print_error "Failed to expand image with dd"
# Show disk space for debugging
df -h /tmp >&2
exit 1
fi
# Resize partition
parted "$img_file" resizepart 2 100% || true
print_step "Image expanded"
}
mount_image() {
local img_file="$1"
print_step "Mounting image..."
# Set up loop device
LOOP_DEVICE=$(losetup -f --show -P "$img_file")
print_step "Loop device: $LOOP_DEVICE"
# Wait for partitions
sleep 2
# Mount partitions
mkdir -p "$MOUNT_BOOT" "$MOUNT_ROOT"
mount "${LOOP_DEVICE}p1" "$MOUNT_BOOT"
mount "${LOOP_DEVICE}p2" "$MOUNT_ROOT"
# Resize root filesystem
resize2fs "${LOOP_DEVICE}p2" || true
print_step "Image mounted at $MOUNT_ROOT"
}
unmount_image() {
print_step "Unmounting image..."
sync
umount "$MOUNT_BOOT" || true
umount "$MOUNT_ROOT" || true
if [ -n "$LOOP_DEVICE" ]; then
losetup -d "$LOOP_DEVICE" || true
fi
print_step "Image unmounted"
}
configure_first_boot() {
print_step "Configuring first boot..."
# Create admin user (Raspberry Pi OS 2022+ doesn't create default user)
print_step "Creating admin user..."
# Copy qemu for ARM emulation if needed
if [ ! -f "$MOUNT_ROOT/usr/bin/qemu-arm-static" ] && [ ! -f "$MOUNT_ROOT/usr/bin/qemu-aarch64-static" ]; then
cp /usr/bin/qemu-arm-static "$MOUNT_ROOT/usr/bin/" 2>/dev/null || \
cp /usr/bin/qemu-aarch64-static "$MOUNT_ROOT/usr/bin/qemu-arm-static" 2>/dev/null || true
fi
# Create admin user with all necessary groups
chroot "$MOUNT_ROOT" useradd -m -G sudo,adm,dialout,cdrom,audio,video,plugdev,games,users,input,netdev,gpio,i2c,spi -s /bin/bash admin 2>/dev/null || {
print_warning "User admin may already exist, updating password..."
}
# Set password for admin user
PASSWORD="${LABLINK_ADMIN_PASSWORD:-lablink}"
echo "admin:$PASSWORD" | chroot "$MOUNT_ROOT" chpasswd
print_step "Admin user created with password"
# Give sudo without password
echo "admin ALL=(ALL) NOPASSWD:ALL" > "$MOUNT_ROOT/etc/sudoers.d/010_admin-nopasswd"
chmod 0440 "$MOUNT_ROOT/etc/sudoers.d/010_admin-nopasswd"
# Disable first-boot wizard (piwiz) and userconfig
print_step "Disabling first-boot wizard..."
# Method 1: Remove piwiz from autostart
rm -f "$MOUNT_ROOT/etc/xdg/autostart/piwiz.desktop" 2>/dev/null || true
# Method 2: Create Hidden=true override if it exists
if [ -f "$MOUNT_ROOT/usr/share/applications/piwiz.desktop" ]; then
mkdir -p "$MOUNT_ROOT/etc/xdg/autostart"
cat > "$MOUNT_ROOT/etc/xdg/autostart/piwiz.desktop" <<EOF
[Desktop Entry]
Hidden=true
EOF
fi
# Method 3: Disable userconfig service (runs first-boot setup)
if [ -f "$MOUNT_ROOT/etc/systemd/system/multi-user.target.wants/userconfig.service" ]; then
rm -f "$MOUNT_ROOT/etc/systemd/system/multi-user.target.wants/userconfig.service"
fi
if [ -f "$MOUNT_ROOT/lib/systemd/system/userconfig.service" ]; then
chroot "$MOUNT_ROOT" systemctl disable userconfig.service 2>/dev/null || true
fi
# Method 4: Create userconf file to indicate user is already configured
# This prevents the first-boot user creation wizard
# Format: username:encrypted_password
ENCRYPTED_PASS=$(echo "${PASSWORD}" | openssl passwd -6 -stdin)
echo "admin:${ENCRYPTED_PASS}" > "$MOUNT_BOOT/userconf.txt" || \
echo "admin:${ENCRYPTED_PASS}" > "$MOUNT_BOOT/userconf"
# Method 5: Create sentinel files
mkdir -p "$MOUNT_ROOT/home/admin"
touch "$MOUNT_ROOT/home/admin/.piwiz_done"
chroot "$MOUNT_ROOT" chown admin:admin /home/admin/.piwiz_done 2>/dev/null || true
# Pre-configure locale (US English UTF-8)
print_step "Configuring locale..."
sed -i 's/^# *en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' "$MOUNT_ROOT/etc/locale.gen"
chroot "$MOUNT_ROOT" locale-gen en_US.UTF-8
chroot "$MOUNT_ROOT" update-locale LANG=en_US.UTF-8
# Pre-configure keyboard layout (US)
print_step "Configuring keyboard layout..."
cat > "$MOUNT_ROOT/etc/default/keyboard" <<EOF
# KEYBOARD configuration file
XKBMODEL="pc105"
XKBLAYOUT="us"
XKBVARIANT=""
XKBOPTIONS=""
BACKSPACE="guess"
EOF
# Pre-configure timezone (America/New_York)
print_step "Configuring timezone..."
ln -sf /usr/share/zoneinfo/America/New_York "$MOUNT_ROOT/etc/localtime"
echo "America/New_York" > "$MOUNT_ROOT/etc/timezone"
# Configure auto-login for admin user (bypasses all setup wizards)
print_step "Configuring auto-login..."
# Create lightdm auto-login configuration
mkdir -p "$MOUNT_ROOT/etc/lightdm/lightdm.conf.d"
cat > "$MOUNT_ROOT/etc/lightdm/lightdm.conf.d/autologin.conf" <<EOF
[Seat:*]
autologin-user=admin
autologin-user-timeout=0
EOF
# Also configure for console auto-login (in case lightdm isn't used)
mkdir -p "$MOUNT_ROOT/etc/systemd/system/getty@tty1.service.d"
cat > "$MOUNT_ROOT/etc/systemd/system/getty@tty1.service.d/autologin.conf" <<EOF
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin admin --noclear %I \$TERM
EOF
# Enable SSH
if [ "$ENABLE_SSH" = "yes" ]; then
touch "$MOUNT_BOOT/ssh"
print_step "SSH enabled"
fi
# Configure Wi-Fi
if [ -n "$WIFI_SSID" ]; then
print_step "Configuring Wi-Fi for SSID: $WIFI_SSID"
# Generate encrypted PSK using wpa_passphrase
# This is more reliable than plaintext passwords
WPA_CONFIG=$(wpa_passphrase "$WIFI_SSID" "$WIFI_PASSWORD" 2>/dev/null || echo "")
if [ -n "$WPA_CONFIG" ]; then
# Extract just the PSK hash from wpa_passphrase output
PSK_HASH=$(echo "$WPA_CONFIG" | grep -E '^\s*psk=' | head -1 | sed 's/.*psk=//' | tr -d ' ')
# Determine WiFi security based on Pi model
# Pi 5 supports WPA3, Pi 3/4 only support WPA2
if [ "$PI_MODEL" = "5" ]; then
print_step "Creating WPA3/WPA2 compatible configuration for Pi 5..."
WPA_KEY_MGMT="SAE WPA-PSK"
WPA_IEEE80211W="1"
NM_KEY_MGMT="sae,wpa-psk"
NM_PMF="1"
else
print_step "Creating WPA2 configuration for Pi $PI_MODEL..."
WPA_KEY_MGMT="WPA-PSK"
WPA_IEEE80211W="0"
NM_KEY_MGMT="wpa-psk"
NM_PMF="0"
fi
# Method 1: Write to boot partition (for first-boot auto-config)
cat > "$MOUNT_BOOT/wpa_supplicant.conf" <<EOF
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="$WIFI_SSID"
key_mgmt=$WPA_KEY_MGMT
psk=$PSK_HASH
ieee80211w=$WPA_IEEE80211W
priority=1
}
EOF
print_step "Wrote wpa_supplicant.conf to boot partition: $MOUNT_BOOT/wpa_supplicant.conf"
# Method 2: Also create in firmware subdirectory if it exists (newer Pi OS)
if [ -d "$MOUNT_BOOT/firmware" ]; then
cp "$MOUNT_BOOT/wpa_supplicant.conf" "$MOUNT_BOOT/firmware/wpa_supplicant.conf"
print_step "Also wrote to firmware subdirectory"
fi
# Method 3: Write directly to rootfs wpa_supplicant.conf
cat > "$MOUNT_ROOT/etc/wpa_supplicant/wpa_supplicant.conf" <<EOF
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="$WIFI_SSID"
key_mgmt=$WPA_KEY_MGMT
psk=$PSK_HASH
ieee80211w=$WPA_IEEE80211W
priority=1
}
EOF
print_step "Wrote wpa_supplicant.conf to rootfs: $MOUNT_ROOT/etc/wpa_supplicant/wpa_supplicant.conf"
# Method 4: Create NetworkManager connection file (for modern Pi OS Bookworm+)
# NetworkManager is the default network manager in newer Pi OS versions
print_step "Creating NetworkManager connection file..."
mkdir -p "$MOUNT_ROOT/etc/NetworkManager/system-connections"
cat > "$MOUNT_ROOT/etc/NetworkManager/system-connections/$WIFI_SSID.nmconnection" <<NMEOF
[connection]
id=$WIFI_SSID
uuid=$(uuidgen 2>/dev/null || echo "$(date +%s)-$(head -c 8 /dev/urandom | xxd -p)")
type=wifi
autoconnect=true
autoconnect-priority=1
[wifi]
mode=infrastructure
ssid=$WIFI_SSID
[wifi-security]
auth-alg=open
key-mgmt=$NM_KEY_MGMT
psk=$PSK_HASH
pmf=$NM_PMF
[ipv4]
method=auto
[ipv6]
addr-gen-mode=default
method=auto
NMEOF
# NetworkManager requires strict permissions on connection files
chmod 600 "$MOUNT_ROOT/etc/NetworkManager/system-connections/$WIFI_SSID.nmconnection"
print_step "Created NetworkManager connection: $WIFI_SSID.nmconnection"
if [ "$PI_MODEL" = "5" ]; then
print_step "Wi-Fi configured with WPA3/WPA2 compatibility for SSID: $WIFI_SSID"
else
print_step "Wi-Fi configured with WPA2 for SSID: $WIFI_SSID"
fi
else
# Fallback to plaintext if wpa_passphrase fails
print_warning "wpa_passphrase not available, using plaintext password"
# Determine WiFi security based on Pi model
if [ "$PI_MODEL" = "5" ]; then
WPA_KEY_MGMT="SAE WPA-PSK"
WPA_IEEE80211W="1"
NM_KEY_MGMT="sae,wpa-psk"
NM_PMF="1"
else
WPA_KEY_MGMT="WPA-PSK"
WPA_IEEE80211W="0"
NM_KEY_MGMT="wpa-psk"
NM_PMF="0"
fi
cat > "$MOUNT_BOOT/wpa_supplicant.conf" <<EOF
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="$WIFI_SSID"
psk="$WIFI_PASSWORD"
key_mgmt=$WPA_KEY_MGMT
ieee80211w=$WPA_IEEE80211W
priority=1
}
EOF
print_step "Wrote wpa_supplicant.conf to boot partition (plaintext)"
# Also write to firmware subdirectory if it exists
if [ -d "$MOUNT_BOOT/firmware" ]; then
cp "$MOUNT_BOOT/wpa_supplicant.conf" "$MOUNT_BOOT/firmware/wpa_supplicant.conf"
print_step "Also wrote to firmware subdirectory"
fi
cat > "$MOUNT_ROOT/etc/wpa_supplicant/wpa_supplicant.conf" <<EOF
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="$WIFI_SSID"
psk="$WIFI_PASSWORD"
key_mgmt=$WPA_KEY_MGMT
ieee80211w=$WPA_IEEE80211W
priority=1
}
EOF
print_step "Wrote wpa_supplicant.conf to rootfs (plaintext)"
# Also create NetworkManager connection file (plaintext)
print_step "Creating NetworkManager connection file (plaintext)..."
mkdir -p "$MOUNT_ROOT/etc/NetworkManager/system-connections"
cat > "$MOUNT_ROOT/etc/NetworkManager/system-connections/$WIFI_SSID.nmconnection" <<NMEOF
[connection]
id=$WIFI_SSID
uuid=$(uuidgen 2>/dev/null || echo "$(date +%s)-$(head -c 8 /dev/urandom | xxd -p)")
type=wifi
autoconnect=true
autoconnect-priority=1
[wifi]
mode=infrastructure
ssid=$WIFI_SSID
[wifi-security]
auth-alg=open
key-mgmt=$NM_KEY_MGMT
psk=$WIFI_PASSWORD
pmf=$NM_PMF
[ipv4]
method=auto
[ipv6]
addr-gen-mode=default
method=auto
NMEOF
chmod 600 "$MOUNT_ROOT/etc/NetworkManager/system-connections/$WIFI_SSID.nmconnection"
print_step "Created NetworkManager connection: $WIFI_SSID.nmconnection"
if [ "$PI_MODEL" = "5" ]; then
print_step "Wi-Fi configured with WPA3/WPA2 compatibility (plaintext) for SSID: $WIFI_SSID"
else
print_step "Wi-Fi configured with WPA2 (plaintext) for SSID: $WIFI_SSID"
fi
fi
else
# No WiFi credentials provided, create basic config
cat > "$MOUNT_ROOT/etc/wpa_supplicant/wpa_supplicant.conf" <<EOF
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
EOF
print_step "Wi-Fi country set to US (no credentials provided)"
fi
# Set hostname
echo "$LABLINK_HOSTNAME" > "$MOUNT_ROOT/etc/hostname"
# Update /etc/hosts
sed -i "s/raspberrypi/$LABLINK_HOSTNAME/g" "$MOUNT_ROOT/etc/hosts"
print_step "Hostname set to: $LABLINK_HOSTNAME"
}
install_lablink() {
print_step "Installing LabLink server..."
# Copy qemu-arm-static for chroot
cp /usr/bin/qemu-arm-static "$MOUNT_ROOT/usr/bin/" || \
cp /usr/bin/qemu-aarch64-static "$MOUNT_ROOT/usr/bin/qemu-arm-static" || {
print_warning "Could not copy qemu-arm-static, chroot may not work"
}
# Create first-boot script
cat > "$MOUNT_ROOT/usr/local/bin/lablink-first-boot.sh" <<'FIRSTBOOT'
#!/bin/bash
# LabLink First Boot Setup
# Log to both journal and file
exec 1> >(tee -a /var/log/lablink-first-boot.log)
exec 2>&1
echo "[LabLink] Starting first boot setup..."
echo "[LabLink] $(date)"
# Check if setup already completed
if [ -f /var/lib/lablink-setup-complete ]; then
echo "[LabLink] Setup already completed, exiting"
systemctl disable lablink-first-boot.service
exit 0
fi
# Function to wait for network
wait_for_network() {
local max_attempts=30
local attempt=1
echo "[LabLink] Waiting for network connectivity..."
while [ $attempt -le $max_attempts ]; do
if ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1; then
echo "[LabLink] Network is ready (attempt $attempt)"
return 0
fi
echo "[LabLink] Network not ready, attempt $attempt/$max_attempts..."
sleep 2
attempt=$((attempt + 1))
done
echo "[LabLink] WARNING: Network not available after $max_attempts attempts"
return 1
}
# Function to sync time
sync_time() {
echo "[LabLink] Synchronizing system time via NTP..."
# Enable NTP
timedatectl set-ntp true
# Restart timesyncd to force sync
systemctl restart systemd-timesyncd
# Wait for time sync with timeout
local max_wait=30
local waited=0
while [ $waited -lt $max_wait ]; do
if timedatectl status | grep -q "System clock synchronized: yes"; then
echo "[LabLink] Time synchronized successfully"
echo "[LabLink] Current time: $(date)"
return 0
fi
sleep 1
waited=$((waited + 1))
done
echo "[LabLink] WARNING: Time sync timeout, but continuing anyway"
echo "[LabLink] Current time: $(date)"
return 0
}
# Function to wait for DNS resolution
wait_for_dns() {
local max_attempts=20
local attempt=1
echo "[LabLink] Waiting for DNS resolution..."
while [ $attempt -le $max_attempts ]; do
if ping -c 1 -W 2 github.com >/dev/null 2>&1; then
echo "[LabLink] DNS is ready (attempt $attempt)"
return 0
fi
echo "[LabLink] DNS not ready, attempt $attempt/$max_attempts..."
sleep 3
attempt=$((attempt + 1))
done
echo "[LabLink] WARNING: DNS not available after $max_attempts attempts"
echo "[LabLink] Service will retry on next boot"
return 1
}
# Wait for network
if ! wait_for_network; then
echo "[LabLink] Skipping setup due to network unavailability"
echo "[LabLink] Service will retry on next boot"
echo "[LabLink] You can manually run this script: sudo /usr/local/bin/lablink-first-boot.sh"
exit 0
fi
# Sync time BEFORE doing any SSL operations
sync_time
# Wait for DNS to be ready BEFORE downloading anything
if ! wait_for_dns; then
echo "[LabLink] Skipping setup due to DNS unavailability"
echo "[LabLink] Service will retry on next boot"
echo "[LabLink] You can manually run this script: sudo /usr/local/bin/lablink-first-boot.sh"
exit 0
fi
# Update system
echo "[LabLink] Updating system packages..."
if apt-get update && apt-get upgrade -y; then
echo "[LabLink] System updated successfully"
else
echo "[LabLink] WARNING: System update failed, continuing anyway..."
fi
# Install Docker
echo "[LabLink] Installing Docker..."
if curl -fsSL https://get.docker.com | sh; then
echo "[LabLink] Docker installed successfully"
usermod -aG docker admin
echo "[LabLink] Added admin user to docker group"
else
echo "[LabLink] ERROR: Docker installation failed"
echo "[LabLink] Service will retry on next boot"
echo "[LabLink] Or manually run: sudo /usr/local/bin/lablink-first-boot.sh"
exit 1
fi
# Install LabLink
echo "[LabLink] Downloading LabLink..."
mkdir -p /opt/lablink
cd /opt/lablink
if curl -L https://github.com/X9X0/LabLink/archive/refs/heads/main.tar.gz -o lablink.tar.gz; then
echo "[LabLink] Download successful, extracting..."
tar -xzf lablink.tar.gz --strip-components=1
rm lablink.tar.gz
else
echo "[LabLink] ERROR: Failed to download LabLink"
echo "[LabLink] Service will retry on next boot"
echo "[LabLink] Or manually run: sudo /usr/local/bin/lablink-first-boot.sh"
exit 1
fi
# Configure environment
if [ -f .env.example ]; then
cp .env.example .env
# Generate JWT secret
JWT_SECRET=$(openssl rand -hex 32)
sed -i "s/your-secret-key-change-this-in-production/$JWT_SECRET/" .env
# Set default admin password for web UI
# Password must meet requirements: 8+ chars, uppercase letter
WEB_ADMIN_PASSWORD="${LABLINK_ADMIN_PASSWORD:-LabLink@2025}"
sed -i "s/LABLINK_DEFAULT_ADMIN_PASSWORD=.*/LABLINK_DEFAULT_ADMIN_PASSWORD=$WEB_ADMIN_PASSWORD/" .env
sed -i "s/LABLINK_DEFAULT_ADMIN_EMAIL=.*/LABLINK_DEFAULT_ADMIN_EMAIL=admin@example.com/" .env
echo "[LabLink] Environment configured with admin password: $WEB_ADMIN_PASSWORD"
else
echo "[LabLink] WARNING: .env.example not found"
fi
# Ensure Docker daemon is fully ready
echo "[LabLink] Ensuring Docker daemon is ready..."
for i in {1..30}; do
if docker info >/dev/null 2>&1; then
echo "[LabLink] Docker daemon is ready"
break
fi
echo "[LabLink] Waiting for Docker daemon (attempt $i/30)..."
sleep 2
done
# Verify Docker is working
if ! docker info >/dev/null 2>&1; then
echo "[LabLink] ✗ ERROR: Docker daemon is not responding"
echo "[LabLink] Service will retry on next boot"
echo "[LabLink] Or manually run: sudo /usr/local/bin/lablink-first-boot.sh"
exit 1
fi
# Start LabLink
echo "[LabLink] Starting LabLink with Docker Compose..."
if docker compose up -d; then
echo "[LabLink] LabLink containers starting..."
# Wait for containers to be healthy
echo "[LabLink] Waiting for services to be ready..."
local max_wait=60
local waited=0
local containers_up=false
while [ $waited -lt $max_wait ]; do
if docker compose ps 2>/dev/null | grep -q "Up"; then
containers_up=true
break
fi
sleep 2
waited=$((waited + 2))
echo "[LabLink] Waiting for containers... ($waited/${max_wait}s)"
done
# Check container status
if [ "$containers_up" = true ]; then
echo "[LabLink] ✓ LabLink started successfully"
# Show container status
echo "[LabLink] Container status:"
docker compose ps
else
echo "[LabLink] ⚠ WARNING: Containers started but may not be healthy"
echo "[LabLink] Container status:"
docker compose ps
echo "[LabLink] Logs:"
docker compose logs --tail=20
fi
else
echo "[LabLink] ✗ ERROR: Failed to start LabLink"
echo "[LabLink] Docker Compose logs:"
docker compose logs --tail=50
echo "[LabLink] Service will retry on next boot"
echo "[LabLink] Or manually run: sudo /usr/local/bin/lablink-first-boot.sh"
exit 1
fi
# Enable LabLink on boot
cat > /etc/systemd/system/lablink.service <<EOF
[Unit]
Description=LabLink Server
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target
[Service]
Type=forking
RemainAfterExit=yes
WorkingDirectory=/opt/lablink
# Ensure Docker is fully ready before starting
ExecStartPre=/bin/sleep 2
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
# Wait for containers to be healthy
ExecStartPost=/bin/bash -c 'for i in {1..30}; do if /usr/bin/docker compose ps 2>/dev/null | grep -q "Up"; then exit 0; fi; sleep 1; done; exit 0'
# Restart on failure with backoff
Restart=on-failure
RestartSec=10s
# Give Docker Compose enough time to start containers
TimeoutStartSec=120
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
EOF
systemctl enable lablink.service
# Create status check script
cat > /usr/local/bin/lablink-status <<'STATUSSCRIPT'
#!/bin/bash
# LabLink Status Checker
echo "════════════════════════════════════════════════════════"
echo " LabLink Server Status"
echo "════════════════════════════════════════════════════════"
echo ""
# Check network
echo "Network Status:"
if ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1; then
echo " ✓ Internet connectivity: OK"
else
echo " ✗ Internet connectivity: OFFLINE"
fi
# Show IP addresses
echo " IP Addresses:"
ip -4 addr show | grep inet | grep -v 127.0.0.1 | awk '{print " - " $2}' || echo " No IP addresses"
echo ""
# Check Docker
echo "Docker Status:"
if systemctl is-active --quiet docker; then
echo " ✓ Docker service: Running"
else
echo " ✗ Docker service: Not running"
fi
echo ""
# Check LabLink service
echo "LabLink Service Status:"
if systemctl is-active --quiet lablink; then
echo " ✓ LabLink service: Enabled and active"
else
echo " ⚠ LabLink service: Not active"
systemctl status lablink --no-pager 2>&1 | head -5 | sed 's/^/ /'
fi
echo ""
# Check LabLink containers
if [ -d /opt/lablink ]; then
echo "LabLink Containers:"
cd /opt/lablink
if docker compose ps 2>/dev/null | grep -q "Up"; then
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}" | sed 's/^/ /'
echo ""
echo " ✓ LabLink is running"
echo ""
echo "Access Points:"
echo " Web UI: http://$(hostname).local"
echo " API: http://$(hostname).local:8000"
echo " API Docs: http://$(hostname).local:8000/docs"
else
echo " ✗ No containers running"
echo ""
echo "To start LabLink:"
echo " cd /opt/lablink && sudo docker compose up -d"
echo ""
echo "To view logs:"
echo " cd /opt/lablink && sudo docker compose logs -f"
fi
else
echo " ✗ LabLink not installed at /opt/lablink"
fi
echo ""
echo "════════════════════════════════════════════════════════"
echo ""
echo "Useful Commands:"
echo " lablink-status - Show this status"
echo " lablink-start - Start LabLink"
echo " lablink-stop - Stop LabLink"
echo " lablink-restart - Restart LabLink"
echo " lablink-logs - View LabLink logs"
echo " lablink-update - Update code and rebuild containers"
echo ""
STATUSSCRIPT
chmod +x /usr/local/bin/lablink-status
# Create convenience commands
cat > /usr/local/bin/lablink-start <<'STARTSCRIPT'
#!/bin/bash
echo "Starting LabLink..."
cd /opt/lablink && sudo docker compose up -d
sleep 3
lablink-status
STARTSCRIPT
chmod +x /usr/local/bin/lablink-start
cat > /usr/local/bin/lablink-stop <<'STOPSCRIPT'
#!/bin/bash
echo "Stopping LabLink..."
cd /opt/lablink && sudo docker compose down
echo "LabLink stopped."
STOPSCRIPT
chmod +x /usr/local/bin/lablink-stop
cat > /usr/local/bin/lablink-restart <<'RESTARTSCRIPT'
#!/bin/bash
echo "Restarting LabLink..."
cd /opt/lablink && sudo docker compose restart
sleep 3
lablink-status
RESTARTSCRIPT
chmod +x /usr/local/bin/lablink-restart
cat > /usr/local/bin/lablink-logs <<'LOGSSCRIPT'
#!/bin/bash
cd /opt/lablink && sudo docker compose logs -f --tail=100
LOGSSCRIPT
chmod +x /usr/local/bin/lablink-logs
cat > /usr/local/bin/lablink-update <<'UPDATESCRIPT'
#!/bin/bash
# LabLink Update Script
# Updates code from git and rebuilds containers
echo "╔═══════════════════════════════════════════════════════╗"
echo "║ ║"
echo "║ LabLink Update & Rebuild ║"
echo "║ ║"
echo "╚═══════════════════════════════════════════════════════╝"
echo ""
cd /opt/lablink || exit 1
echo "Step 1: Checking current version..."
CURRENT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
echo " Current commit: $CURRENT_COMMIT"
echo ""
echo "Step 2: Pulling latest code from git..."
if git pull; then
NEW_COMMIT=$(git rev-parse --short HEAD)
echo " ✓ Code updated to: $NEW_COMMIT"
if [ "$CURRENT_COMMIT" = "$NEW_COMMIT" ]; then
echo " Already up to date!"
read -p "Rebuild anyway? (y/N): " rebuild
if [ "$rebuild" != "y" ] && [ "$rebuild" != "Y" ]; then
echo "No rebuild needed. Exiting."
exit 0
fi
fi
else
echo " ✗ Git pull failed"
echo " Continuing with rebuild anyway..."
fi
echo ""
echo "Step 3: Stopping containers..."
docker compose down
echo ""
echo "Step 4: Rebuilding containers (this may take 2-3 minutes)..."
if docker compose build --no-cache; then
echo " ✓ Rebuild successful"
else
echo " ✗ Rebuild failed"
echo " Check logs above for errors"
exit 1
fi
echo ""
echo "Step 5: Starting containers..."
if docker compose up -d; then
echo " ✓ Containers started"
else
echo " ✗ Failed to start containers"
exit 1
fi
echo ""
echo "Step 6: Waiting for services to be ready..."
sleep 5
# Wait for containers to be healthy
MAX_WAIT=30
WAITED=0
while [ $WAITED -lt $MAX_WAIT ]; do
if docker compose ps 2>/dev/null | grep -q "Up"; then
echo " ✓ Services are ready"
break
fi
sleep 2
WAITED=$((WAITED + 2))
done
echo ""
echo "╔═══════════════════════════════════════════════════════╗"
echo "║ Update Complete! ║"
echo "╚═══════════════════════════════════════════════════════╝"
echo ""
# Show final status
lablink-status
UPDATESCRIPT
chmod +x /usr/local/bin/lablink-update