setup-pi.sh 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. #!/bin/bash
  2. #
  3. # Dune Weaver Raspberry Pi Setup Script
  4. #
  5. # ONE-COMMAND INSTALL (recommended):
  6. # curl -fsSL https://raw.githubusercontent.com/tuanchris/dune-weaver/main/setup-pi.sh | bash
  7. #
  8. # OR from existing clone:
  9. # git clone https://github.com/tuanchris/dune-weaver --single-branch
  10. # cd dune-weaver
  11. # bash setup-pi.sh
  12. #
  13. # Options:
  14. # --no-wifi-fix Skip WiFi stability fix
  15. # --no-hotspot Skip autohotspot setup
  16. # --help Show help
  17. #
  18. set -e
  19. # Colors for output
  20. RED='\033[0;31m'
  21. GREEN='\033[0;32m'
  22. YELLOW='\033[1;33m'
  23. BLUE='\033[0;34m'
  24. NC='\033[0m' # No Color
  25. # Default options
  26. FIX_WIFI=true # Applied by default for stability
  27. SETUP_HOTSPOT=true # Autohotspot for first-time WiFi setup
  28. INSTALL_DIR="$(eval echo ~"${SUDO_USER:-$USER}")/dune-weaver"
  29. REPO_URL="https://github.com/tuanchris/dune-weaver"
  30. # Parse arguments
  31. while [[ $# -gt 0 ]]; do
  32. case $1 in
  33. --no-wifi-fix)
  34. FIX_WIFI=false
  35. shift
  36. ;;
  37. --no-hotspot)
  38. SETUP_HOTSPOT=false
  39. shift
  40. ;;
  41. --help|-h)
  42. echo "Dune Weaver Raspberry Pi Setup Script"
  43. echo ""
  44. echo "One-command install:"
  45. echo " curl -fsSL https://raw.githubusercontent.com/tuanchris/dune-weaver/main/setup-pi.sh | bash"
  46. echo ""
  47. echo "Or from existing clone:"
  48. echo " cd ~/dune-weaver && bash setup-pi.sh [OPTIONS]"
  49. echo ""
  50. echo "Options:"
  51. echo " --no-wifi-fix Skip WiFi stability fix (applied by default)"
  52. echo " --no-hotspot Skip autohotspot setup"
  53. echo " --help, -h Show this help message"
  54. exit 0
  55. ;;
  56. *)
  57. echo -e "${RED}Unknown option: $1${NC}"
  58. echo "Use --help for usage information"
  59. exit 1
  60. ;;
  61. esac
  62. done
  63. # Helper functions
  64. print_step() {
  65. echo -e "\n${BLUE}==>${NC} ${GREEN}$1${NC}"
  66. }
  67. print_warning() {
  68. echo -e "${YELLOW}Warning:${NC} $1"
  69. }
  70. print_error() {
  71. echo -e "${RED}Error:${NC} $1"
  72. }
  73. print_success() {
  74. echo -e "${GREEN}$1${NC}"
  75. }
  76. # Install system dependencies
  77. install_system_deps() {
  78. print_step "Installing system dependencies..."
  79. sudo apt update
  80. sudo DEBIAN_FRONTEND=noninteractive apt install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
  81. python3-venv python3-pip python3-dev \
  82. gcc g++ make swig unzip wget \
  83. libjpeg-dev zlib1g-dev \
  84. libgpiod-dev gpiod \
  85. nginx git vim
  86. print_success "System dependencies installed"
  87. }
  88. # Ensure lgpio C library is available for pip to build against
  89. install_lgpio() {
  90. local syslib="/usr/lib/aarch64-linux-gnu"
  91. # Raspberry Pi OS Trixie ships liblgpio.so.1 but no unversioned
  92. # liblgpio.so symlink (normally provided by a -dev package).
  93. # The build-time linker needs the unversioned name (-llgpio → liblgpio.so).
  94. if [[ ! -e "$syslib/liblgpio.so" ]]; then
  95. # Check if the versioned library exists (from Pi OS)
  96. local versioned
  97. versioned=$(ls "$syslib"/liblgpio.so.* 2>/dev/null | head -1)
  98. if [[ -n "$versioned" ]]; then
  99. print_step "Creating liblgpio.so build symlink..."
  100. sudo ln -sf "$versioned" "$syslib/liblgpio.so"
  101. sudo ldconfig
  102. print_success "liblgpio.so symlink created (-> $(basename "$versioned"))"
  103. else
  104. # Not in system paths — build from source
  105. print_step "Building lgpio C library from source..."
  106. local tmpdir
  107. tmpdir=$(mktemp -d)
  108. cd "$tmpdir"
  109. wget -q https://github.com/joan2937/lg/archive/master.zip
  110. unzip -q master.zip
  111. cd lg-master
  112. make
  113. sudo make install
  114. cd /
  115. rm -rf "$tmpdir"
  116. # Symlink from /usr/local/lib into system path
  117. if [[ -f /usr/local/lib/liblgpio.so ]]; then
  118. sudo ln -sf /usr/local/lib/liblgpio.so "$syslib/liblgpio.so"
  119. fi
  120. sudo ldconfig
  121. print_success "lgpio C library built and installed"
  122. fi
  123. else
  124. echo "liblgpio.so already available for linking"
  125. fi
  126. }
  127. # Check if running on Raspberry Pi
  128. check_raspberry_pi() {
  129. print_step "Checking system compatibility..."
  130. if [[ ! -f /proc/device-tree/model ]]; then
  131. print_warning "Could not detect Raspberry Pi model. Continuing anyway..."
  132. return
  133. fi
  134. MODEL=$(tr -d '\0' < /proc/device-tree/model)
  135. echo "Detected: $MODEL"
  136. # Check for 64-bit OS
  137. ARCH=$(uname -m)
  138. if [[ "$ARCH" != "aarch64" && "$ARCH" != "arm64" ]]; then
  139. print_error "64-bit OS required. Detected: $ARCH"
  140. echo "Please reinstall Raspberry Pi OS (64-bit) using Raspberry Pi Imager"
  141. exit 1
  142. fi
  143. print_success "64-bit OS detected ($ARCH)"
  144. }
  145. # Disable WLAN power save
  146. disable_wlan_powersave() {
  147. print_step "Disabling WLAN power save for better stability..."
  148. # Check if already disabled
  149. if iwconfig wlan0 2>/dev/null | grep -q "Power Management:off"; then
  150. echo "WLAN power save already disabled"
  151. return
  152. fi
  153. # Create config to persist across reboots
  154. sudo tee /etc/NetworkManager/conf.d/wifi-powersave-off.conf > /dev/null << 'EOF'
  155. [connection]
  156. wifi.powersave = 2
  157. EOF
  158. # Also try immediate disable
  159. sudo iwconfig wlan0 power off 2>/dev/null || true
  160. print_success "WLAN power save disabled"
  161. }
  162. # Apply WiFi stability fix
  163. apply_wifi_fix() {
  164. print_step "Applying WiFi stability fix..."
  165. CMDLINE_FILE="/boot/firmware/cmdline.txt"
  166. if [[ ! -f "$CMDLINE_FILE" ]]; then
  167. CMDLINE_FILE="/boot/cmdline.txt"
  168. fi
  169. if [[ ! -f "$CMDLINE_FILE" ]]; then
  170. print_warning "Could not find cmdline.txt, skipping WiFi fix"
  171. return
  172. fi
  173. # Check if fix already applied
  174. if grep -q "brcmfmac.feature_disable=0x82000" "$CMDLINE_FILE"; then
  175. echo "WiFi fix already applied"
  176. return
  177. fi
  178. # Backup and apply fix
  179. sudo cp "$CMDLINE_FILE" "${CMDLINE_FILE}.backup"
  180. sudo sed -i 's/$/ brcmfmac.feature_disable=0x82000/' "$CMDLINE_FILE"
  181. print_success "WiFi fix applied. A reboot is recommended after setup."
  182. NEEDS_REBOOT=true
  183. }
  184. # Verify we're in the dune-weaver directory
  185. ensure_repo() {
  186. print_step "Setting up dune-weaver repository..."
  187. # Check if we're already in the dune-weaver directory
  188. if [[ -f "main.py" ]] && [[ -f "requirements.txt" ]]; then
  189. INSTALL_DIR="$(pwd)"
  190. print_success "Using existing repo at $INSTALL_DIR"
  191. return
  192. fi
  193. # Check if repo exists in home directory
  194. if [[ -d "$INSTALL_DIR" ]] && [[ -f "$INSTALL_DIR/main.py" ]]; then
  195. print_success "Found existing repo at $INSTALL_DIR"
  196. cd "$INSTALL_DIR"
  197. echo "Pulling latest changes..."
  198. git pull
  199. return
  200. fi
  201. # Clone the repository
  202. print_step "Cloning dune-weaver repository..."
  203. git clone "$REPO_URL" --single-branch "$INSTALL_DIR"
  204. cd "$INSTALL_DIR"
  205. print_success "Cloned to $INSTALL_DIR"
  206. }
  207. # Deploy native (venv + systemd + nginx)
  208. deploy_native() {
  209. print_step "Setting up Python virtual environment..."
  210. cd "$INSTALL_DIR"
  211. # Create venv — if running as root (sudo), create as the real user
  212. local real_user="${SUDO_USER:-$USER}"
  213. if [[ $EUID -eq 0 && -n "$SUDO_USER" ]]; then
  214. sudo -u "$SUDO_USER" python3 -m venv .venv
  215. else
  216. python3 -m venv .venv
  217. fi
  218. source .venv/bin/activate
  219. # Install dependencies
  220. print_step "Installing Python packages..."
  221. pip install --upgrade pip
  222. pip install -r requirements.txt
  223. # Ensure venv is owned by the real user (not root)
  224. if [[ $EUID -eq 0 && -n "$SUDO_USER" ]]; then
  225. chown -R "$SUDO_USER:$SUDO_USER" .venv
  226. fi
  227. # Ensure nginx (www-data) can traverse to static files
  228. # chmod o+x grants traversal only, not directory listing
  229. local dir="$INSTALL_DIR"
  230. while [[ "$dir" != "/" ]]; do
  231. sudo chmod o+x "$dir"
  232. dir=$(dirname "$dir")
  233. done
  234. # Configure nginx
  235. print_step "Configuring nginx..."
  236. sudo cp "$INSTALL_DIR/nginx/dune-weaver.conf" /etc/nginx/sites-available/dune-weaver.conf
  237. sudo sed -i "s|INSTALL_DIR_PLACEHOLDER|$INSTALL_DIR|g" /etc/nginx/sites-available/dune-weaver.conf
  238. sudo ln -sf /etc/nginx/sites-available/dune-weaver.conf /etc/nginx/sites-enabled/dune-weaver.conf
  239. sudo rm -f /etc/nginx/sites-enabled/default
  240. sudo nginx -t
  241. sudo systemctl restart nginx
  242. sudo systemctl enable nginx
  243. # Create systemd service
  244. print_step "Creating systemd service..."
  245. sudo cp "$INSTALL_DIR/dune-weaver.service" /etc/systemd/system/dune-weaver.service
  246. sudo sed -i "s|USER_PLACEHOLDER|$USER|g" /etc/systemd/system/dune-weaver.service
  247. sudo sed -i "s|INSTALL_DIR_PLACEHOLDER|$INSTALL_DIR|g" /etc/systemd/system/dune-weaver.service
  248. # Enable and start service
  249. sudo systemctl daemon-reload
  250. sudo systemctl enable dune-weaver
  251. sudo systemctl start dune-weaver
  252. # Create sudoers entry for passwordless systemctl commands
  253. print_step "Configuring sudo permissions..."
  254. sudo tee /etc/sudoers.d/dune-weaver > /dev/null << EOF
  255. $USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart dune-weaver
  256. $USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl stop dune-weaver
  257. $USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl start dune-weaver
  258. $USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl poweroff
  259. $USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
  260. EOF
  261. sudo chmod 0440 /etc/sudoers.d/dune-weaver
  262. print_success "Native deployment complete!"
  263. }
  264. # Install dw CLI command
  265. install_cli() {
  266. print_step "Installing 'dw' command..."
  267. # Copy dw script to /usr/local/bin
  268. sudo cp "$INSTALL_DIR/dw" /usr/local/bin/dw
  269. sudo chmod +x /usr/local/bin/dw
  270. print_success "'dw' command installed"
  271. }
  272. # Setup autohotspot
  273. setup_autohotspot() {
  274. print_step "Setting up autohotspot..."
  275. if [[ ! -f "$INSTALL_DIR/wifi/setup-wifi.sh" ]]; then
  276. print_warning "wifi/setup-wifi.sh not found, skipping autohotspot setup"
  277. return
  278. fi
  279. bash "$INSTALL_DIR/wifi/setup-wifi.sh"
  280. print_success "Autohotspot setup complete"
  281. }
  282. # Configure UART for GPIO pin connection to DLC32/ESP32
  283. configure_uart() {
  284. local CONFIG_FILE="/boot/firmware/config.txt"
  285. if [[ ! -f "$CONFIG_FILE" ]]; then
  286. CONFIG_FILE="/boot/config.txt"
  287. fi
  288. echo ""
  289. echo -e "${GREEN}How is your Raspberry Pi connected to the sand table controller (DLC32/ESP32)?${NC}"
  290. echo ""
  291. echo " 1) USB cable"
  292. echo " 2) UART over GPIO pins (TX/RX wired to header pins)"
  293. echo ""
  294. echo -e " ${YELLOW}Note: USB is not reliable on Pi 3B+. Use UART for Pi 3B+.${NC}"
  295. echo ""
  296. read -p "Enter choice [1/2] (default: 1): " -n 1 -r uart_choice
  297. echo ""
  298. if [[ "$uart_choice" == "2" ]]; then
  299. echo ""
  300. echo -e "${YELLOW}============================================${NC}"
  301. echo -e "${YELLOW} UART Setup — raspi-config will run next${NC}"
  302. echo -e "${YELLOW}============================================${NC}"
  303. echo ""
  304. echo -e " When prompted, select:"
  305. echo -e " Login shell over serial? → ${GREEN}No${NC}"
  306. echo -e " Serial port hardware? → ${GREEN}Yes${NC}"
  307. echo ""
  308. read -p "Press Enter to continue..." -r
  309. echo ""
  310. # Disable serial console, enable serial hardware
  311. if command -v raspi-config &> /dev/null; then
  312. sudo raspi-config nonint do_serial 2
  313. echo "Serial console disabled, serial hardware enabled"
  314. else
  315. print_warning "raspi-config not found, please run 'sudo raspi-config' manually"
  316. print_warning "Go to: 3 Interface Options > I6 Serial Port > No (console) > Yes (hardware)"
  317. fi
  318. print_step "Configuring UART overlays..."
  319. # Add UART overlays to config.txt if not already present
  320. local needs_change=false
  321. for overlay in "dtoverlay=pi3-miniuart-bt" "dtoverlay=miniuart-bt" "enable_uart=1"; do
  322. if ! grep -q "^${overlay}$" "$CONFIG_FILE" 2>/dev/null; then
  323. echo "$overlay" | sudo tee -a "$CONFIG_FILE" > /dev/null
  324. needs_change=true
  325. fi
  326. done
  327. if [[ "$needs_change" == "true" ]]; then
  328. echo "Added UART overlays to $CONFIG_FILE"
  329. else
  330. echo "UART overlays already present in $CONFIG_FILE"
  331. fi
  332. NEEDS_REBOOT=true
  333. print_success "UART configured. A reboot is required for changes to take effect."
  334. else
  335. # USB mode — check if UART config exists and offer to clean it up
  336. local has_uart=false
  337. for overlay in "dtoverlay=pi3-miniuart-bt" "dtoverlay=miniuart-bt" "enable_uart=1"; do
  338. if grep -q "^${overlay}$" "$CONFIG_FILE" 2>/dev/null; then
  339. has_uart=true
  340. break
  341. fi
  342. done
  343. if [[ "$has_uart" == "true" ]]; then
  344. echo -e "${YELLOW}UART overlays found in $CONFIG_FILE from a previous setup.${NC}"
  345. read -p "Remove them? (y/N): " -n 1 -r remove_uart
  346. echo ""
  347. if [[ "$remove_uart" =~ ^[Yy]$ ]]; then
  348. sudo sed -i '/^dtoverlay=pi3-miniuart-bt$/d' "$CONFIG_FILE"
  349. sudo sed -i '/^dtoverlay=miniuart-bt$/d' "$CONFIG_FILE"
  350. sudo sed -i '/^enable_uart=1$/d' "$CONFIG_FILE"
  351. NEEDS_REBOOT=true
  352. print_success "UART overlays removed. A reboot is recommended."
  353. fi
  354. else
  355. echo "USB connection selected, no UART changes needed."
  356. fi
  357. fi
  358. }
  359. # Remove software that is no longer needed on the Pi
  360. cleanup_unused() {
  361. print_step "Cleaning up unused software..."
  362. # Remove Node.js / npm if present from a prior install
  363. if dpkg -l nodejs 2>/dev/null | grep -q '^ii'; then
  364. echo "Removing Node.js (no longer needed — frontend is pre-built)..."
  365. sudo apt purge -y nodejs || true
  366. sudo rm -f /etc/apt/sources.list.d/nodesource.list \
  367. /etc/apt/keyrings/nodesource.gpg 2>/dev/null || true
  368. sudo apt autoremove -y
  369. print_success "Node.js removed"
  370. fi
  371. # Remove Docker if present from old Docker-based deployment
  372. if dpkg -l docker-ce 2>/dev/null | grep -q '^ii'; then
  373. echo "Removing Docker (old deployment method)..."
  374. # Stop running containers
  375. sudo docker stop $(sudo docker ps -aq) 2>/dev/null || true
  376. sudo apt purge -y docker-ce docker-ce-cli containerd.io docker-compose-plugin 2>/dev/null || true
  377. sudo rm -rf /var/lib/docker
  378. sudo apt autoremove -y
  379. print_success "Docker removed"
  380. fi
  381. }
  382. # Get IP address
  383. get_ip_address() {
  384. # Try multiple methods to get IP
  385. IP=$(hostname -I 2>/dev/null | awk '{print $1}')
  386. if [[ -z "$IP" ]]; then
  387. IP=$(ip route get 1 2>/dev/null | awk '{print $7}' | head -1)
  388. fi
  389. if [[ -z "$IP" ]]; then
  390. IP="<your-pi-ip>"
  391. fi
  392. echo "$IP"
  393. }
  394. # Print final instructions
  395. print_final_instructions() {
  396. IP=$(get_ip_address)
  397. HOSTNAME=$(hostname)
  398. echo ""
  399. echo -e "${GREEN}============================================${NC}"
  400. echo -e "${GREEN} Dune Weaver Setup Complete!${NC}"
  401. echo -e "${GREEN}============================================${NC}"
  402. echo ""
  403. echo -e "Access the web interface at:"
  404. echo -e " ${BLUE}http://$IP${NC}"
  405. echo -e " ${BLUE}http://$HOSTNAME.local${NC}"
  406. echo ""
  407. echo "Manage with the 'dw' command:"
  408. echo " dw logs View live logs"
  409. echo " dw restart Restart Dune Weaver"
  410. echo " dw update Pull latest and restart"
  411. echo " dw stop Stop Dune Weaver"
  412. echo " dw status Show status"
  413. echo " dw wifi help WiFi and hotspot management"
  414. echo " dw help Show all commands"
  415. echo ""
  416. if [[ "$SETUP_HOTSPOT" == "true" ]]; then
  417. echo -e "${BLUE}Autohotspot:${NC} If no known WiFi is found on boot,"
  418. echo "a 'Dune Weaver' hotspot will be created automatically."
  419. echo "Connect to it and open the app to configure WiFi."
  420. echo ""
  421. fi
  422. if [[ "$NEEDS_REBOOT" == "true" ]]; then
  423. print_warning "A reboot is required to apply configuration changes"
  424. read -p "Reboot now? (y/N) " -n 1 -r
  425. echo
  426. if [[ $REPLY =~ ^[Yy]$ ]]; then
  427. sudo reboot
  428. fi
  429. fi
  430. }
  431. # Main installation flow
  432. main() {
  433. echo -e "${GREEN}"
  434. echo " ____ __ __ "
  435. echo " | _ \ _ _ _ __ ___\ \ / /__ __ ___ _____ _ __ "
  436. echo " | | | | | | | '_ \ / _ \\ \ /\ / / _ \/ _\` \ \ / / _ \ '__|"
  437. echo " | |_| | |_| | | | | __/ \ V V / __/ (_| |\ V / __/ | "
  438. echo " |____/ \__,_|_| |_|\___| \_/\_/ \___|\__,_| \_/ \___|_| "
  439. echo -e "${NC}"
  440. echo "Raspberry Pi Setup Script"
  441. echo ""
  442. echo "Install directory: $INSTALL_DIR"
  443. echo ""
  444. # Ask connection type upfront (before long-running installs)
  445. configure_uart
  446. # Run setup steps
  447. check_raspberry_pi
  448. install_system_deps
  449. ensure_repo
  450. disable_wlan_powersave
  451. if [[ "$FIX_WIFI" == "true" ]]; then
  452. apply_wifi_fix
  453. fi
  454. if [[ "$SETUP_HOTSPOT" == "true" ]]; then
  455. setup_autohotspot
  456. fi
  457. install_lgpio
  458. deploy_native
  459. install_cli
  460. cleanup_unused
  461. print_final_instructions
  462. }
  463. # Run main
  464. main