install.sh 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  1. #!/usr/bin/env bash
  2. #
  3. # SpoolBuddy Installation Script for Raspberry Pi
  4. #
  5. # Supports two scenarios:
  6. # 1) SpoolBuddy only — NFC/scale companion connecting to a remote Bambuddy instance
  7. # 2) SpoolBuddy + Bambuddy — both running natively on this Raspberry Pi
  8. #
  9. # Usage:
  10. # Interactive: curl -fsSL https://raw.githubusercontent.com/maziggy/bambuddy/main/spoolbuddy/install.sh -o install.sh && chmod +x install.sh && sudo ./install.sh
  11. # Unattended: sudo ./install.sh --mode spoolbuddy --bambuddy-url http://192.168.1.100:8000 --api-key bb_xxx --yes
  12. #
  13. # Options:
  14. # --mode MODE Installation mode: "spoolbuddy" (companion only) or "full" (both)
  15. # --repo URL Git repository URL to install from (default: upstream repo)
  16. # --ref REF Git ref to install (branch/tag/commit, default: main)
  17. # --bambuddy-url URL Bambuddy server URL (required for spoolbuddy mode)
  18. # --api-key KEY Bambuddy API key (required for spoolbuddy mode)
  19. # --path PATH Installation directory (default: /opt/spoolbuddy or /opt/bambuddy)
  20. # --port PORT Bambuddy port (full mode only, default: 8000)
  21. # --ssh-pubkey KEY Bambuddy SSH public key for remote updates
  22. # --yes, -y Non-interactive mode, accept defaults
  23. # --help, -h Show this help message
  24. #
  25. set -e
  26. # ─────────────────────────────────────────────────────────────────────────────
  27. # Constants
  28. # ─────────────────────────────────────────────────────────────────────────────
  29. RED='\033[0;31m'
  30. GREEN='\033[0;32m'
  31. YELLOW='\033[1;33m'
  32. CYAN='\033[0;36m'
  33. BOLD='\033[1m'
  34. NC='\033[0m'
  35. GITHUB_REPO="https://github.com/maziggy/bambuddy.git"
  36. SPOOLBUDDY_SERVICE_USER="spoolbuddy"
  37. BAMBUDDY_SERVICE_USER="bambuddy"
  38. # Packages needed for SpoolBuddy hardware (NFC reader + scale)
  39. SYSTEM_PACKAGES="python3 python3-pip python3-venv python3-dev python3-spidev python3-libgpiod gpiod libgpiod-dev i2c-tools git plymouth-themes"
  40. # Python packages for SpoolBuddy daemon
  41. SPOOLBUDDY_PIP_PACKAGES="spidev gpiod smbus2 httpx"
  42. # ─────────────────────────────────────────────────────────────────────────────
  43. # Variables (set by args or prompts)
  44. # ─────────────────────────────────────────────────────────────────────────────
  45. INSTALL_MODE="" # "spoolbuddy" or "full"
  46. INSTALL_PATH=""
  47. INSTALL_REPO=""
  48. INSTALL_REF=""
  49. DETECTED_INSTALLER_REPO=""
  50. DETECTED_INSTALLER_REF=""
  51. BAMBUDDY_URL=""
  52. API_KEY=""
  53. BAMBUDDY_PORT="8000"
  54. NON_INTERACTIVE="false"
  55. REBOOT_NEEDED="false"
  56. KIOSK_USER="" # auto-detected from $SUDO_USER
  57. KIOSK_URL="" # derived from $BAMBUDDY_URL/spoolbuddy?token=$API_KEY
  58. SSH_PUBKEY="" # Bambuddy's SSH public key for remote updates
  59. # ─────────────────────────────────────────────────────────────────────────────
  60. # Helpers
  61. # ─────────────────────────────────────────────────────────────────────────────
  62. info() { echo -e "${CYAN}[INFO]${NC} $1"; }
  63. success() { echo -e "${GREEN}[OK]${NC} $1"; }
  64. warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
  65. error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }
  66. # Run a long-running command with a spinner + live progress output.
  67. # Usage: run_with_progress "description" command [args...]
  68. run_with_progress() {
  69. local desc="$1"
  70. shift
  71. local log_file
  72. log_file=$(mktemp /tmp/spoolbuddy-install.XXXXXX)
  73. local start_time=$SECONDS
  74. # Run command in background, capture stdout+stderr
  75. "$@" > "$log_file" 2>&1 &
  76. local pid=$!
  77. # Spinner frames (braille pattern)
  78. local -a spin=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
  79. local i=0
  80. while kill -0 "$pid" 2>/dev/null; do
  81. local elapsed=$(( SECONDS - start_time ))
  82. local time_str
  83. if (( elapsed >= 60 )); then
  84. time_str="$(( elapsed / 60 ))m$(printf '%02d' $(( elapsed % 60 )))s"
  85. else
  86. time_str="${elapsed}s"
  87. fi
  88. # Last chunk of output (handles \r progress lines and regular \n lines)
  89. local last_line=""
  90. last_line=$(tail -c 4096 "$log_file" 2>/dev/null | tr '\r' '\n' | sed 's/\x1b\[[0-9;]*[mGKHJ]//g' | sed '/^[[:space:]]*$/d' | tail -1 | sed 's/^[[:space:]]*//' | cut -c1-50) || true
  91. printf "\r ${spin[$((i % 10))]} %-36s ${CYAN}%6s${NC} %s\033[K" "$desc" "$time_str" "$last_line"
  92. i=$(( i + 1 ))
  93. sleep 0.15
  94. done
  95. local exit_code=0
  96. wait "$pid" || exit_code=$?
  97. # Clear spinner line
  98. printf "\r\033[K"
  99. # Format elapsed time for summary
  100. local elapsed=$(( SECONDS - start_time ))
  101. local time_suffix=""
  102. if (( elapsed >= 60 )); then
  103. time_suffix=" ($(( elapsed / 60 ))m $(( elapsed % 60 ))s)"
  104. elif (( elapsed >= 5 )); then
  105. time_suffix=" (${elapsed}s)"
  106. fi
  107. if [[ $exit_code -eq 0 ]]; then
  108. success "${desc}${time_suffix}"
  109. rm -f "$log_file"
  110. else
  111. echo -e "${RED}[FAIL]${NC} ${desc}${time_suffix}"
  112. echo ""
  113. echo -e " ${YELLOW}Last 20 lines:${NC}"
  114. tail -20 "$log_file" 2>/dev/null | sed 's/^/ /'
  115. echo ""
  116. echo -e " Full log: ${CYAN}$log_file${NC}"
  117. exit 1
  118. fi
  119. }
  120. prompt() {
  121. local prompt_text="$1"
  122. local default_value="$2"
  123. local var_name="$3"
  124. if [[ "$NON_INTERACTIVE" == "true" ]]; then
  125. eval "$var_name=\"$default_value\""
  126. return
  127. fi
  128. if [[ -n "$default_value" ]]; then
  129. echo -en "${BOLD}$prompt_text${NC} [${CYAN}$default_value${NC}]: "
  130. else
  131. echo -en "${BOLD}$prompt_text${NC}: "
  132. fi
  133. read -r input
  134. if [[ -z "$input" ]]; then
  135. eval "$var_name=\"$default_value\""
  136. else
  137. eval "$var_name=\"$input\""
  138. fi
  139. }
  140. prompt_yes_no() {
  141. local prompt_text="$1"
  142. local default="$2"
  143. if [[ "$NON_INTERACTIVE" == "true" ]]; then
  144. [[ "$default" == "y" ]] && return 0 || return 1
  145. fi
  146. local yn_hint="[y/n]"
  147. [[ "$default" == "y" ]] && yn_hint="[Y/n]"
  148. [[ "$default" == "n" ]] && yn_hint="[y/N]"
  149. while true; do
  150. echo -en "${BOLD}$prompt_text${NC} $yn_hint: "
  151. read -r yn
  152. [[ -z "$yn" ]] && yn="$default"
  153. case "$yn" in
  154. [Yy]* ) return 0;;
  155. [Nn]* ) return 1;;
  156. * ) echo "Please answer yes or no.";;
  157. esac
  158. done
  159. }
  160. show_help() {
  161. echo "SpoolBuddy Installation Script for Raspberry Pi"
  162. echo ""
  163. echo "Usage: sudo $0 [OPTIONS]"
  164. echo ""
  165. echo "Options:"
  166. echo " --mode MODE \"spoolbuddy\" (companion only) or \"full\" (Bambuddy + SpoolBuddy)"
  167. echo " --repo URL Git repository URL to install from"
  168. echo " --ref REF Git ref to install (branch/tag/commit)"
  169. echo " --bambuddy-url URL Bambuddy server URL (required for spoolbuddy mode)"
  170. echo " --api-key KEY Bambuddy API key (required for spoolbuddy mode)"
  171. echo " --path PATH Installation directory (default: /opt/spoolbuddy or /opt/bambuddy)"
  172. echo " --port PORT Bambuddy port (full mode only, default: 8000)"
  173. echo " --ssh-pubkey KEY Bambuddy SSH public key for remote updates"
  174. echo " --yes, -y Non-interactive mode, accept defaults"
  175. echo " --help, -h Show this help message"
  176. echo ""
  177. echo "Examples:"
  178. echo " Interactive:"
  179. echo " sudo ./install.sh"
  180. echo ""
  181. echo " SpoolBuddy companion (unattended):"
  182. echo " sudo ./install.sh --mode spoolbuddy --bambuddy-url http://192.168.1.100:8000 --api-key bb_xxx -y"
  183. echo ""
  184. echo " Full install (unattended):"
  185. echo " sudo ./install.sh --mode full --port 8000 -y"
  186. exit 0
  187. }
  188. normalize_github_repo_url() {
  189. local url="$1"
  190. if [[ -z "$url" ]]; then
  191. echo ""
  192. return
  193. fi
  194. # Convert git@github.com:owner/repo(.git) to https://github.com/owner/repo.git
  195. if [[ "$url" =~ ^git@github.com:(.+)$ ]]; then
  196. url="https://github.com/${BASH_REMATCH[1]}"
  197. fi
  198. # Keep remote URL style consistent.
  199. url="${url%.git}"
  200. echo "${url}.git"
  201. }
  202. detect_installer_source_context() {
  203. local script_dir
  204. script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  205. if git -C "$script_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  206. DETECTED_INSTALLER_REF="$(git -C "$script_dir" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
  207. local origin_url
  208. origin_url="$(git -C "$script_dir" remote get-url origin 2>/dev/null || true)"
  209. DETECTED_INSTALLER_REPO="$(normalize_github_repo_url "$origin_url")"
  210. fi
  211. # Optional environment overrides for raw-download installs.
  212. if [[ -n "${SPOOLBUDDY_INSTALL_REPO:-}" ]]; then
  213. DETECTED_INSTALLER_REPO="$(normalize_github_repo_url "$SPOOLBUDDY_INSTALL_REPO")"
  214. fi
  215. if [[ -n "${SPOOLBUDDY_INSTALL_REF:-}" ]]; then
  216. DETECTED_INSTALLER_REF="$SPOOLBUDDY_INSTALL_REF"
  217. fi
  218. if [[ -z "$INSTALL_REPO" ]]; then
  219. if [[ -n "$DETECTED_INSTALLER_REPO" ]]; then
  220. INSTALL_REPO="$DETECTED_INSTALLER_REPO"
  221. else
  222. INSTALL_REPO="$GITHUB_REPO"
  223. fi
  224. fi
  225. if [[ -z "$INSTALL_REF" ]]; then
  226. if [[ -n "$DETECTED_INSTALLER_REF" && "$DETECTED_INSTALLER_REF" != "HEAD" ]]; then
  227. INSTALL_REF="$DETECTED_INSTALLER_REF"
  228. else
  229. INSTALL_REF="main"
  230. fi
  231. fi
  232. }
  233. resolve_install_ref() {
  234. local ref="$1"
  235. # If ref exists on origin as a branch, track/reset it. Otherwise treat it as tag/commit.
  236. if git ls-remote --exit-code --heads origin "$ref" >/dev/null 2>&1; then
  237. git checkout -B "$ref" "origin/$ref" > /dev/null 2>&1
  238. git reset --hard "origin/$ref" > /dev/null 2>&1
  239. else
  240. git checkout "$ref" > /dev/null 2>&1
  241. fi
  242. }
  243. # ─────────────────────────────────────────────────────────────────────────────
  244. # Pre-flight Checks
  245. # ─────────────────────────────────────────────────────────────────────────────
  246. check_root() {
  247. if [[ $EUID -ne 0 ]]; then
  248. error "This script must be run as root (use sudo)"
  249. fi
  250. }
  251. check_raspberry_pi() {
  252. if ! grep -q "Raspberry Pi\|BCM2" /proc/cpuinfo 2>/dev/null; then
  253. error "This script is designed for Raspberry Pi only"
  254. fi
  255. # Detect Pi model for hardware recommendations
  256. local model
  257. model=$(tr -d '\0' < /proc/device-tree/model 2>/dev/null) || model="Unknown"
  258. success "Detected: $model"
  259. }
  260. check_raspberry_pi_os() {
  261. if [[ ! -f /etc/os-release ]]; then
  262. error "Cannot detect operating system"
  263. fi
  264. . /etc/os-release
  265. if [[ "$ID" != "raspbian" && "$ID" != "debian" ]]; then
  266. warn "Expected Raspberry Pi OS (Debian-based), found: $ID"
  267. if ! prompt_yes_no "Continue anyway?" "n"; then
  268. exit 0
  269. fi
  270. fi
  271. success "OS: $PRETTY_NAME"
  272. }
  273. detect_python() {
  274. local cmd=""
  275. if command -v python3 &>/dev/null; then
  276. cmd="python3"
  277. elif command -v python &>/dev/null; then
  278. local ver
  279. ver=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1)
  280. if [[ "$ver" -ge 3 ]]; then
  281. cmd="python"
  282. fi
  283. fi
  284. if [[ -z "$cmd" ]]; then
  285. return 1
  286. fi
  287. local version
  288. version=$($cmd -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
  289. local major minor
  290. major=$(echo "$version" | cut -d'.' -f1)
  291. minor=$(echo "$version" | cut -d'.' -f2)
  292. if [[ "$major" -lt 3 ]] || { [[ "$major" -eq 3 ]] && [[ "$minor" -lt 10 ]]; }; then
  293. warn "Python $version found, but 3.10+ is required"
  294. return 1
  295. fi
  296. PYTHON_CMD="$cmd"
  297. success "Found Python $version"
  298. return 0
  299. }
  300. # ─────────────────────────────────────────────────────────────────────────────
  301. # Raspberry Pi Hardware Configuration
  302. # ─────────────────────────────────────────────────────────────────────────────
  303. enable_spi() {
  304. if raspi-config nonint get_spi 2>/dev/null | grep -q "1"; then
  305. info "Enabling SPI..."
  306. raspi-config nonint do_spi 0
  307. REBOOT_NEEDED="true"
  308. success "SPI enabled"
  309. else
  310. success "SPI already enabled"
  311. fi
  312. }
  313. enable_i2c() {
  314. if raspi-config nonint get_i2c 2>/dev/null | grep -q "1"; then
  315. info "Enabling I2C..."
  316. raspi-config nonint do_i2c 0
  317. REBOOT_NEEDED="true"
  318. success "I2C enabled"
  319. else
  320. success "I2C already enabled"
  321. fi
  322. }
  323. configure_boot_config() {
  324. # Find the boot config file (Bookworm+ uses /boot/firmware/config.txt)
  325. local boot_config="/boot/firmware/config.txt"
  326. if [[ ! -f "$boot_config" ]]; then
  327. boot_config="/boot/config.txt"
  328. fi
  329. if [[ ! -f "$boot_config" ]]; then
  330. warn "Boot config not found at /boot/firmware/config.txt or /boot/config.txt"
  331. warn "You may need to manually add: dtparam=i2c_arm=on and dtoverlay=spi0-0cs"
  332. return
  333. fi
  334. info "Configuring $boot_config..."
  335. # Migrate legacy SpoolBuddy setting (bus 0 / i2c_vc) to bus 1 / i2c_arm.
  336. if grep -q "^dtparam=i2c_vc=on" "$boot_config"; then
  337. sed -i "s/^dtparam=i2c_vc=on$/# dtparam=i2c_vc=on (disabled by SpoolBuddy installer; use i2c_arm bus 1)/" "$boot_config"
  338. REBOOT_NEEDED="true"
  339. success "Disabled legacy dtparam=i2c_vc=on"
  340. fi
  341. if grep -q "^# SpoolBuddy: I2C bus 0 for NAU7802 scale (GPIO0/GPIO1)" "$boot_config"; then
  342. sed -i "s/^# SpoolBuddy: I2C bus 0 for NAU7802 scale (GPIO0\/GPIO1)$/# SpoolBuddy: I2C bus 1 for NAU7802 scale (GPIO2\/GPIO3)/" "$boot_config"
  343. fi
  344. # Ensure I2C bus 1 (GPIO2/GPIO3) is enabled for NAU7802 scale
  345. if ! grep -q "^dtparam=i2c_arm=on" "$boot_config"; then
  346. echo "" >> "$boot_config"
  347. echo "# SpoolBuddy: I2C bus 1 for NAU7802 scale (GPIO2/GPIO3)" >> "$boot_config"
  348. echo "dtparam=i2c_arm=on" >> "$boot_config"
  349. REBOOT_NEEDED="true"
  350. success "Added dtparam=i2c_arm=on"
  351. else
  352. success "dtparam=i2c_arm=on already set"
  353. fi
  354. # Disable SPI auto chip-select (manual CS on GPIO23 for PN5180)
  355. if ! grep -q "^dtoverlay=spi0-0cs" "$boot_config"; then
  356. echo "" >> "$boot_config"
  357. echo "# SpoolBuddy: Disable SPI auto CS (manual CS on GPIO23 for PN5180)" >> "$boot_config"
  358. echo "dtoverlay=spi0-0cs" >> "$boot_config"
  359. REBOOT_NEEDED="true"
  360. success "Added dtoverlay=spi0-0cs"
  361. else
  362. success "dtoverlay=spi0-0cs already set"
  363. fi
  364. }
  365. # ─────────────────────────────────────────────────────────────────────────────
  366. # Package Installation
  367. # ─────────────────────────────────────────────────────────────────────────────
  368. install_system_packages() {
  369. run_with_progress "Updating package lists" apt-get update
  370. run_with_progress "Installing system packages" apt-get install -y $SYSTEM_PACKAGES
  371. }
  372. install_wifi_safeguard() {
  373. # Protect WiFi credentials from being wiped by apt upgrades.
  374. # Raspberry Pi OS Bookworm migrated from wpa_supplicant/dhcpcd to
  375. # NetworkManager, but certain package upgrades (raspberrypi-sys-mods,
  376. # raspi-config, NetworkManager itself) can delete saved connections
  377. # from /etc/NetworkManager/system-connections/. This hook backs them
  378. # up before dpkg runs and restores them if they vanish.
  379. local hook_file="/etc/apt/apt.conf.d/80-preserve-wifi"
  380. if [[ -f "$hook_file" ]]; then
  381. success "WiFi safeguard already installed"
  382. return
  383. fi
  384. # Only install if NetworkManager is the active network manager
  385. if ! systemctl is-active --quiet NetworkManager 2>/dev/null; then
  386. return
  387. fi
  388. # Write a helper script (avoids quote escaping issues in APT config)
  389. local helper="/usr/local/sbin/preserve-wifi"
  390. cat > "$helper" << 'HELPEREOF'
  391. #!/bin/sh
  392. # Called by APT hooks to preserve NetworkManager WiFi connections.
  393. NM_DIR="/etc/NetworkManager/system-connections"
  394. BAK_DIR="/etc/NetworkManager/system-connections.bak"
  395. case "$1" in
  396. backup)
  397. if [ -d "$NM_DIR" ] && [ -n "$(ls -A "$NM_DIR" 2>/dev/null)" ]; then
  398. cp -a "$NM_DIR/" "$BAK_DIR/"
  399. fi
  400. ;;
  401. restore)
  402. if [ -d "$BAK_DIR" ] && [ -z "$(ls -A "$NM_DIR" 2>/dev/null)" ]; then
  403. cp -a "$BAK_DIR"/* "$NM_DIR"/
  404. nmcli general reload 2>/dev/null
  405. fi
  406. rm -rf "$BAK_DIR" 2>/dev/null
  407. ;;
  408. esac
  409. HELPEREOF
  410. chmod +x "$helper"
  411. cat > "$hook_file" << 'APTEOF'
  412. // Preserve NetworkManager WiFi connections across apt upgrades.
  413. // Installed by SpoolBuddy.
  414. DPkg::Pre-Invoke {"/usr/local/sbin/preserve-wifi backup";};
  415. DPkg::Post-Invoke {"/usr/local/sbin/preserve-wifi restore";};
  416. APTEOF
  417. success "WiFi safeguard installed (${hook_file})"
  418. }
  419. upgrade_system_packages() {
  420. run_with_progress "Upgrading system packages" apt-get upgrade -y
  421. }
  422. # ─────────────────────────────────────────────────────────────────────────────
  423. # SpoolBuddy Installation
  424. # ─────────────────────────────────────────────────────────────────────────────
  425. create_spoolbuddy_user() {
  426. if id "$SPOOLBUDDY_SERVICE_USER" &>/dev/null; then
  427. info "User '$SPOOLBUDDY_SERVICE_USER' already exists"
  428. # Ensure existing installs get a real shell for SSH access
  429. usermod --shell /bin/bash "$SPOOLBUDDY_SERVICE_USER" 2>/dev/null || true
  430. else
  431. info "Creating service user '$SPOOLBUDDY_SERVICE_USER'..."
  432. useradd --system --shell /bin/bash --home-dir "$INSTALL_PATH" "$SPOOLBUDDY_SERVICE_USER"
  433. success "Service user created"
  434. fi
  435. # Add to hardware access groups (gpio, spi, i2c, video for backlight)
  436. for group in gpio spi i2c video; do
  437. if getent group "$group" &>/dev/null; then
  438. usermod -aG "$group" "$SPOOLBUDDY_SERVICE_USER" 2>/dev/null || true
  439. fi
  440. done
  441. success "User added to gpio, spi, i2c, video groups"
  442. # Allow passwordless restart of daemon + kiosk (needed for SSH-based updates from Bambuddy)
  443. cat > /etc/sudoers.d/spoolbuddy << 'SUDOERS'
  444. spoolbuddy ALL=(root) NOPASSWD: /usr/bin/systemctl restart spoolbuddy.service
  445. spoolbuddy ALL=(root) NOPASSWD: /usr/bin/systemctl restart getty@tty1.service
  446. spoolbuddy ALL=(root) NOPASSWD: /usr/bin/find /home -maxdepth 5 *
  447. spoolbuddy ALL=(root) NOPASSWD: /sbin/reboot
  448. spoolbuddy ALL=(root) NOPASSWD: /sbin/shutdown -h now
  449. SUDOERS
  450. chmod 440 /etc/sudoers.d/spoolbuddy
  451. success "Sudoers entries created for service, kiosk restart, reboot and shutdown"
  452. }
  453. download_spoolbuddy() {
  454. if [[ -d "$INSTALL_PATH/.git" ]]; then
  455. info "Existing installation found, updating..."
  456. # Pre-emptively normalise tree ownership before git touches anything.
  457. # Stray root-owned files (e.g. static/assets/* left by an earlier
  458. # `sudo` run, or a frontend build that wrote as root) make
  459. # `git reset --hard` fail with EACCES on the unlink/replace step,
  460. # aborting the update before the post-install chown below ever
  461. # runs. The script already runs as root (see check_root), so this
  462. # is always safe.
  463. chown -R "$SPOOLBUDDY_SERVICE_USER:$SPOOLBUDDY_SERVICE_USER" "$INSTALL_PATH"
  464. git config --global --add safe.directory "$INSTALL_PATH" 2>/dev/null || true
  465. cd "$INSTALL_PATH"
  466. git remote set-url origin "$INSTALL_REPO" 2>/dev/null || true
  467. run_with_progress "Fetching updates" git fetch origin
  468. resolve_install_ref "$INSTALL_REF"
  469. else
  470. mkdir -p "$INSTALL_PATH"
  471. run_with_progress "Cloning repository" git clone "$INSTALL_REPO" "$INSTALL_PATH"
  472. cd "$INSTALL_PATH"
  473. resolve_install_ref "$INSTALL_REF"
  474. fi
  475. chown -R "$SPOOLBUDDY_SERVICE_USER:$SPOOLBUDDY_SERVICE_USER" "$INSTALL_PATH"
  476. }
  477. setup_spoolbuddy_venv() {
  478. cd "$INSTALL_PATH/spoolbuddy"
  479. run_with_progress "Creating SpoolBuddy venv" $PYTHON_CMD -m venv --system-site-packages venv
  480. run_with_progress "Upgrading pip" "$INSTALL_PATH/spoolbuddy/venv/bin/pip" install --upgrade pip
  481. run_with_progress "Installing SpoolBuddy packages" "$INSTALL_PATH/spoolbuddy/venv/bin/pip" install $SPOOLBUDDY_PIP_PACKAGES
  482. chown -R "$SPOOLBUDDY_SERVICE_USER:$SPOOLBUDDY_SERVICE_USER" "$INSTALL_PATH/spoolbuddy/venv"
  483. }
  484. create_spoolbuddy_env() {
  485. info "Creating SpoolBuddy configuration..."
  486. local env_file="$INSTALL_PATH/spoolbuddy/.env"
  487. cat > "$env_file" << EOF
  488. # SpoolBuddy Configuration
  489. # Generated by install.sh on $(date)
  490. # Bambuddy backend URL
  491. SPOOLBUDDY_BACKEND_URL=$BAMBUDDY_URL
  492. # API key (create one in Bambuddy Settings -> API Keys)
  493. SPOOLBUDDY_API_KEY=$API_KEY
  494. # NAU7802 scale bus (RPi GPIO2/GPIO3)
  495. SPOOLBUDDY_I2C_BUS=1
  496. EOF
  497. chown "$SPOOLBUDDY_SERVICE_USER:$SPOOLBUDDY_SERVICE_USER" "$env_file"
  498. # Keep secrets owner-writable while allowing kiosk user (in spoolbuddy group)
  499. # to read backend URL/API key for dynamic launcher URL resolution.
  500. chgrp "$SPOOLBUDDY_SERVICE_USER" "$env_file"
  501. chmod 640 "$env_file"
  502. success "Configuration saved to $env_file"
  503. }
  504. ensure_kiosk_env_access() {
  505. local env_file="$INSTALL_PATH/spoolbuddy/.env"
  506. if [[ ! -f "$env_file" ]]; then
  507. warn "SpoolBuddy env file not found at $env_file"
  508. return
  509. fi
  510. # Ensure kiosk user is known even when this function is called outside setup_kiosk.
  511. if [[ -z "$KIOSK_USER" ]]; then
  512. KIOSK_USER="${SUDO_USER:-$(logname 2>/dev/null || echo pi)}"
  513. fi
  514. if id "$KIOSK_USER" &>/dev/null; then
  515. usermod -aG "$SPOOLBUDDY_SERVICE_USER" "$KIOSK_USER" 2>/dev/null || true
  516. fi
  517. chgrp "$SPOOLBUDDY_SERVICE_USER" "$env_file"
  518. chmod 640 "$env_file"
  519. if ! su -s /bin/sh -c "test -r '$env_file'" "$KIOSK_USER"; then
  520. error "Kiosk user '$KIOSK_USER' cannot read $env_file (required for dynamic kiosk URL). Check groups/permissions."
  521. fi
  522. success "Verified kiosk user '$KIOSK_USER' can read SpoolBuddy env"
  523. }
  524. setup_ssh_key() {
  525. info "Setting up SSH access for Bambuddy remote updates..."
  526. local ssh_dir="$INSTALL_PATH/.ssh"
  527. local auth_keys="$ssh_dir/authorized_keys"
  528. mkdir -p "$ssh_dir"
  529. chmod 700 "$ssh_dir"
  530. if [[ -n "$SSH_PUBKEY" ]]; then
  531. # Manual key provided via --ssh-pubkey flag
  532. if [[ -f "$auth_keys" ]] && grep -qF "$SSH_PUBKEY" "$auth_keys" 2>/dev/null; then
  533. info "SSH key already present in authorized_keys"
  534. else
  535. echo "$SSH_PUBKEY" >> "$auth_keys"
  536. success "SSH public key added"
  537. fi
  538. else
  539. # No manual key — the daemon will auto-deploy it on first registration
  540. info "SSH key will be deployed automatically when the daemon connects to Bambuddy"
  541. touch "$auth_keys"
  542. fi
  543. chmod 600 "$auth_keys"
  544. chown -R "$SPOOLBUDDY_SERVICE_USER:$SPOOLBUDDY_SERVICE_USER" "$ssh_dir"
  545. }
  546. create_spoolbuddy_service() {
  547. info "Creating SpoolBuddy systemd service..."
  548. local after_line="After=network-online.target"
  549. if [[ "$INSTALL_MODE" == "full" ]]; then
  550. after_line="After=network-online.target bambuddy.service"
  551. fi
  552. cat > /etc/systemd/system/spoolbuddy.service << EOF
  553. [Unit]
  554. Description=SpoolBuddy - NFC Spool Management Daemon
  555. Documentation=https://github.com/maziggy/bambuddy
  556. $after_line
  557. Wants=network-online.target
  558. [Service]
  559. Type=simple
  560. User=$SPOOLBUDDY_SERVICE_USER
  561. WorkingDirectory=$INSTALL_PATH/spoolbuddy
  562. EnvironmentFile=$INSTALL_PATH/spoolbuddy/.env
  563. ExecStart=$INSTALL_PATH/spoolbuddy/venv/bin/python -m daemon.main
  564. Restart=always
  565. RestartSec=5
  566. StandardOutput=journal
  567. StandardError=journal
  568. [Install]
  569. WantedBy=multi-user.target
  570. EOF
  571. systemctl daemon-reload
  572. systemctl enable spoolbuddy.service
  573. success "SpoolBuddy service created and enabled"
  574. }
  575. # ─────────────────────────────────────────────────────────────────────────────
  576. # Bambuddy Installation (full mode only)
  577. # ─────────────────────────────────────────────────────────────────────────────
  578. create_bambuddy_user() {
  579. if id "$BAMBUDDY_SERVICE_USER" &>/dev/null; then
  580. info "User '$BAMBUDDY_SERVICE_USER' already exists"
  581. return
  582. fi
  583. info "Creating service user '$BAMBUDDY_SERVICE_USER'..."
  584. useradd --system --shell /usr/sbin/nologin --home-dir "$INSTALL_PATH" "$BAMBUDDY_SERVICE_USER"
  585. success "Service user created"
  586. }
  587. setup_bambuddy_venv() {
  588. cd "$INSTALL_PATH"
  589. run_with_progress "Creating Bambuddy venv" $PYTHON_CMD -m venv venv
  590. run_with_progress "Upgrading pip" "$INSTALL_PATH/venv/bin/pip" install --upgrade pip
  591. run_with_progress "Installing Bambuddy dependencies" "$INSTALL_PATH/venv/bin/pip" install -r requirements.txt
  592. chown -R "$BAMBUDDY_SERVICE_USER:$BAMBUDDY_SERVICE_USER" "$INSTALL_PATH/venv"
  593. }
  594. install_nodejs() {
  595. if command -v node &>/dev/null; then
  596. local version
  597. version=$(node --version 2>/dev/null | sed 's/^v//')
  598. local major
  599. major=$(echo "$version" | cut -d'.' -f1)
  600. if [[ "$major" -ge 20 ]]; then
  601. success "Found Node.js v$version"
  602. return
  603. fi
  604. fi
  605. apt-get remove -y nodejs npm > /dev/null 2>&1 || true
  606. run_with_progress "Setting up Node.js repository" bash -c "curl -fsSL https://deb.nodesource.com/setup_22.x | bash -"
  607. run_with_progress "Installing Node.js" apt-get install -y nodejs
  608. hash -r 2>/dev/null || true
  609. success "Node.js installed: $(node --version)"
  610. }
  611. build_frontend() {
  612. cd "$INSTALL_PATH/frontend"
  613. run_with_progress "Installing frontend dependencies" npm ci
  614. run_with_progress "Building frontend" npm run build
  615. }
  616. create_bambuddy_env() {
  617. info "Creating Bambuddy configuration..."
  618. local env_file="$INSTALL_PATH/.env"
  619. cat > "$env_file" << EOF
  620. # Bambuddy Configuration
  621. # Generated by install.sh on $(date)
  622. DEBUG=false
  623. LOG_LEVEL=INFO
  624. LOG_TO_FILE=true
  625. EOF
  626. chown "$BAMBUDDY_SERVICE_USER:$BAMBUDDY_SERVICE_USER" "$env_file"
  627. chmod 600 "$env_file"
  628. success "Configuration saved to $env_file"
  629. }
  630. create_bambuddy_directories() {
  631. mkdir -p "$INSTALL_PATH/data" "$INSTALL_PATH/logs"
  632. chown -R "$BAMBUDDY_SERVICE_USER:$BAMBUDDY_SERVICE_USER" "$INSTALL_PATH/data" "$INSTALL_PATH/logs"
  633. success "Data directories created"
  634. }
  635. create_bambuddy_service() {
  636. info "Creating Bambuddy systemd service..."
  637. # Overwriting the unit used to silently drop any ReadWritePaths the operator
  638. # had added — a NAS share for Scheduled Backups, typically — after which the
  639. # backups failed with EROFS, which looks like a permission problem and is not
  640. # one (issue #2544). Back the old unit up and carry those paths forward.
  641. local existing_unit="/etc/systemd/system/bambuddy.service"
  642. local extra_rw=""
  643. if [[ -f "$existing_unit" ]]; then
  644. local backup_unit="${existing_unit}.bak-$(date +%Y%m%d-%H%M%S)"
  645. cp "$existing_unit" "$backup_unit"
  646. info "Existing service backed up to $backup_unit"
  647. local prev_rw p
  648. prev_rw=$(grep -hE '^ReadWritePaths=' "$existing_unit" 2>/dev/null | sed 's/^ReadWritePaths=//' || true)
  649. for p in $prev_rw; do
  650. case "$p" in
  651. "$INSTALL_PATH/data" | "$INSTALL_PATH/logs" | "$INSTALL_PATH") continue ;;
  652. esac
  653. extra_rw+=" $p"
  654. done
  655. if [[ -n "$extra_rw" ]]; then
  656. info "Keeping custom writable paths from the previous service:$extra_rw"
  657. fi
  658. fi
  659. cat > /etc/systemd/system/bambuddy.service << EOF
  660. [Unit]
  661. Description=Bambuddy - Bambu Lab Print Management
  662. Documentation=https://github.com/maziggy/bambuddy
  663. After=network.target
  664. [Service]
  665. Type=simple
  666. User=$BAMBUDDY_SERVICE_USER
  667. Group=$BAMBUDDY_SERVICE_USER
  668. WorkingDirectory=$INSTALL_PATH
  669. EnvironmentFile=$INSTALL_PATH/.env
  670. Environment="DATA_DIR=$INSTALL_PATH/data"
  671. Environment="LOG_DIR=$INSTALL_PATH/logs"
  672. # --loop asyncio required: uvloop can truncate VP FTP uploads (#1896)
  673. # --timeout-graceful-shutdown required: uvicorn otherwise waits forever for
  674. # in-flight requests, and an MJPEG camera stream never completes — one open
  675. # camera tile hangs the stop until systemd SIGKILLs, skipping the WAL
  676. # checkpoint and the MQTT / virtual-printer teardown. A kiosk sitting on the
  677. # printers page holds exactly such a stream open, so this bites every reboot.
  678. ExecStart=$INSTALL_PATH/venv/bin/uvicorn backend.app.main:app --host 0.0.0.0 --port $BAMBUDDY_PORT --loop asyncio --timeout-graceful-shutdown 5
  679. Restart=on-failure
  680. RestartSec=5
  681. # Backstop only — uvicorn bounds its own wait at 5s and teardown takes ~1-2s.
  682. TimeoutStopSec=30
  683. StandardOutput=journal
  684. StandardError=journal
  685. NoNewPrivileges=true
  686. PrivateTmp=true
  687. ProtectSystem=strict
  688. ProtectHome=true
  689. # ProtectSystem=strict makes every path outside the ones below read-only for this
  690. # service. To back up to a NAS share, add it here or in a drop-in that survives a
  691. # reinstall: sudo systemctl edit bambuddy → [Service] → ReadWritePaths=/mnt/share
  692. ReadWritePaths=$INSTALL_PATH/data $INSTALL_PATH/logs $INSTALL_PATH$extra_rw
  693. [Install]
  694. WantedBy=multi-user.target
  695. EOF
  696. systemctl daemon-reload
  697. systemctl enable bambuddy.service
  698. success "Bambuddy service created and enabled"
  699. }
  700. bootstrap_spoolbuddy_kiosk_key() {
  701. # Provision an API key for the local SpoolBuddy kiosk and write it into
  702. # spoolbuddy/.env. Runs against the Bambuddy DB directly (via the CLI),
  703. # so the bambuddy service does not need to be running yet.
  704. info "Provisioning SpoolBuddy kiosk API key..."
  705. local env_file="$INSTALL_PATH/spoolbuddy/.env"
  706. if [[ ! -f "$env_file" ]]; then
  707. warn "SpoolBuddy env file not found at $env_file — skipping kiosk key bootstrap"
  708. return
  709. fi
  710. # CWD must be $INSTALL_PATH so `python -m backend.app.cli` finds the backend
  711. # package on sys.path (matches the systemd unit's WorkingDirectory).
  712. local kiosk_key
  713. if ! kiosk_key="$(cd "$INSTALL_PATH" && sudo -u "$BAMBUDDY_SERVICE_USER" \
  714. env DATA_DIR="$INSTALL_PATH/data" LOG_DIR="$INSTALL_PATH/logs" \
  715. "$INSTALL_PATH/venv/bin/python" -m backend.app.cli kiosk-bootstrap --force)"; then
  716. error "Failed to bootstrap SpoolBuddy kiosk API key"
  717. fi
  718. if [[ -z "$kiosk_key" || "$kiosk_key" != bb_* ]]; then
  719. error "CLI returned an invalid API key (got: ${kiosk_key:0:8}...)"
  720. fi
  721. if ! grep -q '^SPOOLBUDDY_API_KEY=' "$env_file"; then
  722. error "Sentinel 'SPOOLBUDDY_API_KEY=' line missing in $env_file"
  723. fi
  724. # Escape for sed replacement (the key is base64url-safe, no slashes, but be defensive)
  725. local escaped_key
  726. escaped_key=$(printf '%s\n' "$kiosk_key" | sed -e 's/[\/&]/\\&/g')
  727. sed -i "s/^SPOOLBUDDY_API_KEY=.*/SPOOLBUDDY_API_KEY=${escaped_key}/" "$env_file"
  728. success "SpoolBuddy kiosk API key provisioned"
  729. }
  730. # ─────────────────────────────────────────────────────────────────────────────
  731. # System Strip-Down (dedicated appliance — remove unnecessary services/packages)
  732. # ─────────────────────────────────────────────────────────────────────────────
  733. strip_services() {
  734. info "Disabling unnecessary services..."
  735. local services=(
  736. bluetooth.service
  737. lightdm.service
  738. cloud-init-local.service
  739. cloud-init.service
  740. cloud-init-network.service
  741. cloud-config.service
  742. cloud-final.service
  743. cloud-init-hotplugd.socket
  744. avahi-daemon.service
  745. avahi-daemon.socket
  746. ModemManager.service
  747. udisks2.service
  748. apparmor.service
  749. man-db.timer
  750. e2scrub_all.timer
  751. e2scrub_reap.service
  752. # Audio stack (no speakers on a spool reader)
  753. pipewire.service
  754. pipewire.socket
  755. pipewire-pulse.service
  756. pipewire-pulse.socket
  757. wireplumber.service
  758. # Printing
  759. cups.service
  760. cups.socket
  761. cups-browsed.service
  762. # Desktop services
  763. accounts-daemon.service
  764. upower.service
  765. polkit.service
  766. # Flatpak portals (not using Flatpak)
  767. xdg-desktop-portal.service
  768. xdg-desktop-portal-gtk.service
  769. xdg-document-portal.service
  770. xdg-permission-store.service
  771. # NFS/RPC (unnecessary + security surface)
  772. rpcbind.service
  773. rpcbind.socket
  774. # Bluetooth media proxy
  775. mpris-proxy.service
  776. )
  777. local disabled=0
  778. for svc in "${services[@]}"; do
  779. if systemctl is-enabled "$svc" &>/dev/null; then
  780. systemctl disable "$svc" 2>/dev/null || true
  781. systemctl mask "$svc" 2>/dev/null || true
  782. (( ++disabled ))
  783. fi
  784. done
  785. if (( disabled > 0 )); then
  786. success "Disabled $disabled unnecessary services"
  787. else
  788. success "No unnecessary services to disable"
  789. fi
  790. # Mask user-level services globally via /etc/systemd/user/ overrides.
  791. # The su-based approach doesn't reliably reach the user's systemd instance
  792. # when run from sudo, so we create global masks that apply before login.
  793. local user_services=(
  794. pipewire.service
  795. pipewire.socket
  796. pipewire-pulse.service
  797. pipewire-pulse.socket
  798. wireplumber.service
  799. xdg-desktop-portal.service
  800. xdg-desktop-portal-gtk.service
  801. xdg-document-portal.service
  802. xdg-permission-store.service
  803. mpris-proxy.service
  804. )
  805. mkdir -p /etc/systemd/user
  806. local user_masked=0
  807. for svc in "${user_services[@]}"; do
  808. if [[ ! -L "/etc/systemd/user/$svc" ]] || [[ "$(readlink /etc/systemd/user/$svc)" != "/dev/null" ]]; then
  809. ln -sf /dev/null "/etc/systemd/user/$svc"
  810. (( ++user_masked ))
  811. fi
  812. done
  813. if (( user_masked > 0 )); then
  814. success "Masked $user_masked unnecessary user services globally"
  815. fi
  816. }
  817. strip_packages() {
  818. info "Removing unnecessary packages..."
  819. local packages=(
  820. mkvtoolnix
  821. firmware-atheros
  822. firmware-mediatek
  823. cloud-init
  824. rpi-cloud-init-mods
  825. rpi-connect-lite
  826. avahi-daemon
  827. modemmanager
  828. udisks2
  829. pipewire
  830. pipewire-pulse
  831. wireplumber
  832. cups
  833. cups-browsed
  834. cups-common
  835. cups-client
  836. rpcbind
  837. )
  838. local to_remove=()
  839. for pkg in "${packages[@]}"; do
  840. if dpkg -l "$pkg" &>/dev/null 2>&1; then
  841. to_remove+=("$pkg")
  842. fi
  843. done
  844. if (( ${#to_remove[@]} > 0 )); then
  845. run_with_progress "Removing ${#to_remove[@]} packages" apt-get remove --purge -y "${to_remove[@]}"
  846. run_with_progress "Cleaning up dependencies" apt-get autoremove --purge -y
  847. else
  848. success "No unnecessary packages to remove"
  849. fi
  850. }
  851. # ─────────────────────────────────────────────────────────────────────────────
  852. # Kiosk Setup (labwc + Chromium + Plymouth splash)
  853. # ─────────────────────────────────────────────────────────────────────────────
  854. setup_kiosk() {
  855. info "Setting up touchscreen kiosk..."
  856. # Detect kiosk user (the human user who ran sudo)
  857. KIOSK_USER="${SUDO_USER:-$(logname 2>/dev/null || echo pi)}"
  858. KIOSK_URL="${BAMBUDDY_URL}/spoolbuddy?token=${API_KEY}"
  859. local KIOSK_HOME
  860. KIOSK_HOME=$(eval echo "~$KIOSK_USER")
  861. info "Kiosk user: $KIOSK_USER (home: $KIOSK_HOME)"
  862. info "Kiosk URL: $KIOSK_URL"
  863. # Allow kiosk user to read SpoolBuddy env so launcher can resolve backend URL
  864. # and API key dynamically instead of using stale install-time fallback values.
  865. local spoolbuddy_env="$INSTALL_PATH/spoolbuddy/.env"
  866. if [[ -f "$spoolbuddy_env" ]]; then
  867. usermod -aG "$SPOOLBUDDY_SERVICE_USER" "$KIOSK_USER" 2>/dev/null || true
  868. chgrp "$SPOOLBUDDY_SERVICE_USER" "$spoolbuddy_env" 2>/dev/null || true
  869. chmod 640 "$spoolbuddy_env" 2>/dev/null || true
  870. fi
  871. # ── Install kiosk packages ────────────────────────────────────────────
  872. # Temporarily block initramfs rebuilds during package install — we rebuild
  873. # once at the end after the Plymouth theme is configured, saving ~4 runs
  874. # (one per installed kernel per hook trigger).
  875. if [[ -x /usr/sbin/update-initramfs ]]; then
  876. dpkg-divert --local --rename --add /usr/sbin/update-initramfs >/dev/null 2>&1 || true
  877. ln -sf /bin/true /usr/sbin/update-initramfs
  878. fi
  879. run_with_progress "Installing kiosk packages" apt-get install -y labwc chromium plymouth wlr-randr swayidle wlopm jq curl
  880. # Restore real update-initramfs
  881. if dpkg-divert --list /usr/sbin/update-initramfs 2>/dev/null | grep -q local; then
  882. rm -f /usr/sbin/update-initramfs
  883. dpkg-divert --local --rename --remove /usr/sbin/update-initramfs >/dev/null 2>&1 || true
  884. fi
  885. # ── config.txt tweaks ─────────────────────────────────────────────────
  886. local boot_config="/boot/firmware/config.txt"
  887. if [[ ! -f "$boot_config" ]]; then
  888. boot_config="/boot/config.txt"
  889. fi
  890. if [[ -f "$boot_config" ]]; then
  891. info "Configuring $boot_config for kiosk..."
  892. # Disable audio (change existing on→off)
  893. sed -i 's/^dtparam=audio=on/dtparam=audio=off/' "$boot_config"
  894. # Disable camera auto-detect (change existing 1→0)
  895. sed -i 's/^camera_auto_detect=1/camera_auto_detect=0/' "$boot_config"
  896. # Append if missing: gpu_mem=32
  897. if ! grep -q "^gpu_mem=" "$boot_config"; then
  898. echo "" >> "$boot_config"
  899. echo "# Kiosk: Minimal GPU firmware memory (KMS uses CMA from system RAM)" >> "$boot_config"
  900. echo "gpu_mem=32" >> "$boot_config"
  901. fi
  902. # Append if missing: dtoverlay=disable-bt
  903. if ! grep -q "^dtoverlay=disable-bt" "$boot_config"; then
  904. echo "" >> "$boot_config"
  905. echo "# Kiosk: Disable Bluetooth hardware" >> "$boot_config"
  906. echo "dtoverlay=disable-bt" >> "$boot_config"
  907. fi
  908. # Append if missing: disable_splash=1
  909. if ! grep -q "^disable_splash=" "$boot_config"; then
  910. echo "" >> "$boot_config"
  911. echo "# Kiosk: Disable Raspberry Pi firmware splash, use custom splash.png" >> "$boot_config"
  912. echo "disable_splash=1" >> "$boot_config"
  913. fi
  914. success "Boot config updated"
  915. fi
  916. # ── cmdline.txt tweaks ────────────────────────────────────────────────
  917. local cmdline="/boot/firmware/cmdline.txt"
  918. if [[ ! -f "$cmdline" ]]; then
  919. cmdline="/boot/cmdline.txt"
  920. fi
  921. if [[ -f "$cmdline" ]]; then
  922. info "Configuring $cmdline for kiosk..."
  923. # Remove serial console (Plymouth needs tty-only console)
  924. sed -i 's/console=serial0,[0-9]* //' "$cmdline"
  925. # Disable console blanking (kernel default is 600s, can blank during boot transition)
  926. grep -q "consoleblank=" "$cmdline" || sed -i 's/$/ consoleblank=0/' "$cmdline"
  927. # Add splash quiet loglevel=3 logo.nologo if missing
  928. grep -q "splash" "$cmdline" || sed -i 's/$/ splash quiet loglevel=3 logo.nologo/' "$cmdline"
  929. # Add video mode if missing
  930. grep -q "video=HDMI-A-1" "$cmdline" || sed -i 's/$/ video=HDMI-A-1:1024x600@60/' "$cmdline"
  931. success "Kernel cmdline updated"
  932. fi
  933. # ── Plymouth splash theme ─────────────────────────────────────────────
  934. info "Installing Plymouth boot splash..."
  935. local theme_dir="/usr/share/plymouth/themes/spoolbuddy"
  936. mkdir -p "$theme_dir"
  937. # Copy bundled splash image from the install directory
  938. local script_dir
  939. script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  940. if [[ -f "$script_dir/splash.png" ]]; then
  941. cp "$script_dir/splash.png" "$theme_dir/splash.png"
  942. elif [[ -f "$INSTALL_PATH/spoolbuddy/install/splash.png" ]]; then
  943. cp "$INSTALL_PATH/spoolbuddy/install/splash.png" "$theme_dir/splash.png"
  944. else
  945. warn "splash.png not found — Plymouth splash will not display an image"
  946. fi
  947. # Write .plymouth theme file
  948. cat > "$theme_dir/spoolbuddy.plymouth" << 'EOF'
  949. [Plymouth Theme]
  950. Name=SpoolBuddy
  951. Description=SpoolBuddy boot splash
  952. ModuleName=script
  953. [script]
  954. ImageDir=/usr/share/plymouth/themes/spoolbuddy
  955. ScriptFile=/usr/share/plymouth/themes/spoolbuddy/spoolbuddy.script
  956. EOF
  957. # Write .script theme file
  958. cat > "$theme_dir/spoolbuddy.script" << 'EOF'
  959. wallpaper_image = Image("splash.png");
  960. screen_width = Window.GetWidth();
  961. screen_height = Window.GetHeight();
  962. resized_wallpaper_image = wallpaper_image.Scale(screen_width, screen_height);
  963. wallpaper_sprite = Sprite(resized_wallpaper_image);
  964. wallpaper_sprite.SetZ(-100);
  965. EOF
  966. plymouth-set-default-theme spoolbuddy
  967. run_with_progress "Updating initramfs" update-initramfs -u
  968. success "Plymouth splash installed"
  969. # ── Auto-login on tty1 ────────────────────────────────────────────────
  970. info "Configuring auto-login for $KIOSK_USER..."
  971. mkdir -p /etc/systemd/system/getty@tty1.service.d
  972. cat > /etc/systemd/system/getty@tty1.service.d/autologin.conf << EOF
  973. [Unit]
  974. After=network-online.target
  975. Wants=network-online.target
  976. [Service]
  977. ExecStart=
  978. ExecStart=-/sbin/agetty --autologin $KIOSK_USER --noclear %I \$TERM
  979. EOF
  980. success "Auto-login configured"
  981. # ── labwc rc.xml (no decorations, no keybinds) ────────────────────────
  982. info "Configuring labwc window manager..."
  983. local labwc_dir="$KIOSK_HOME/.config/labwc"
  984. mkdir -p "$labwc_dir"
  985. cat > "$labwc_dir/rc.xml" << 'EOF'
  986. <?xml version="1.0"?>
  987. <labwc_config>
  988. <!-- Disable screen blanking — kiosk must stay on -->
  989. <core>
  990. <screenBlankTimeout>0</screenBlankTimeout>
  991. </core>
  992. <theme>
  993. <name></name>
  994. <cornerRadius>0</cornerRadius>
  995. </theme>
  996. <!-- Disable all keybindings - kiosk lockdown -->
  997. <keyboard>
  998. </keyboard>
  999. <!-- Disable right-click menu -->
  1000. <mouse>
  1001. <default />
  1002. </mouse>
  1003. <!-- Remove window decorations, maximize Chromium, prevent unfullscreen -->
  1004. <windowRules>
  1005. <windowRule identifier="*">
  1006. <serverDecoration>no</serverDecoration>
  1007. </windowRule>
  1008. <windowRule identifier="chromium">
  1009. <skipTaskbar>yes</skipTaskbar>
  1010. <fixedPosition>yes</fixedPosition>
  1011. </windowRule>
  1012. </windowRules>
  1013. </labwc_config>
  1014. EOF
  1015. # ── Override Debian/RPi Chromium defaults for kiosk performance ──────
  1016. cat > /etc/chromium.d/spoolbuddy-kiosk << 'CHROMIUM_EOF'
  1017. # SpoolBuddy kiosk: add kiosk-specific flags on top of Pi defaults.
  1018. # Preserves Pi GPU settings (gpu-rasterization, ANGLE/GLES) for stability.
  1019. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-smooth-scrolling"
  1020. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-extensions"
  1021. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-background-timer-throttling"
  1022. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-renderer-backgrounding"
  1023. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-crash-reporter"
  1024. CHROMIUM_EOF
  1025. success "Chromium kiosk performance flags installed"
  1026. # ── kiosk launcher (dynamic URL from spoolbuddy/.env) ─────────────────
  1027. local kiosk_launcher="/usr/local/bin/spoolbuddy-kiosk-launch"
  1028. cat > "$kiosk_launcher" << EOF
  1029. #!/usr/bin/env bash
  1030. set -euo pipefail
  1031. ENV_FILE="$INSTALL_PATH/spoolbuddy/.env"
  1032. FALLBACK_URL="$KIOSK_URL"
  1033. backend_url=""
  1034. api_key=""
  1035. if [[ -r "\$ENV_FILE" ]]; then
  1036. backend_url="\$(sed -n 's/^SPOOLBUDDY_BACKEND_URL=//p' "\$ENV_FILE" | tail -n1 | tr -d '\r')"
  1037. api_key="\$(sed -n 's/^SPOOLBUDDY_API_KEY=//p' "\$ENV_FILE" | tail -n1 | tr -d '\r')"
  1038. backend_url="\${backend_url%\"}"
  1039. backend_url="\${backend_url#\"}"
  1040. api_key="\${api_key%\"}"
  1041. api_key="\${api_key#\"}"
  1042. elif [[ -f "\$ENV_FILE" ]]; then
  1043. echo "spoolbuddy-kiosk-launch: ERROR: \$ENV_FILE exists but is not readable" >&2
  1044. echo "spoolbuddy-kiosk-launch: Fix permissions (group-readable by kiosk user) and restart kiosk" >&2
  1045. exit 1
  1046. fi
  1047. if [[ -n "\$backend_url" && -n "\$api_key" ]]; then
  1048. backend_url="\${backend_url%/}"
  1049. kiosk_url="\${backend_url}/spoolbuddy?token=\${api_key}"
  1050. else
  1051. kiosk_url="\$FALLBACK_URL"
  1052. fi
  1053. # Wait for the Bambuddy backend to be reachable before launching Chromium.
  1054. # Without this the browser opens before uvicorn has bound to the port on a
  1055. # cold boot and the user sees an ERR_CONNECTION_REFUSED splash until they
  1056. # manually reload. Probe /health (no auth, no body) with a short timeout.
  1057. probe_url="\${backend_url:-http://localhost}/health"
  1058. for _i in \$(seq 1 60); do
  1059. if curl -sf --max-time 2 "\$probe_url" >/dev/null 2>&1; then
  1060. break
  1061. fi
  1062. sleep 1
  1063. done
  1064. # Ephemeral user-data-dir under /tmp + wipe on every launch.
  1065. #
  1066. # The kiosk has no per-user state worth persisting (the auth token is in
  1067. # the URL query, not a stored cookie), but the default profile at
  1068. # ~/.config/chromium was accumulating two specific kinds of state across
  1069. # reboots that broke deploys badly:
  1070. #
  1071. # 1. HTTP disk cache holding old index.html across browser restarts.
  1072. # Chromium's heuristic-cache freshness window kept the old HTML
  1073. # "fresh" for days, which referenced an old content-hashed bundle,
  1074. # so newly deployed code never reached the running tab even after
  1075. # pkill+relaunch. Reproduced in the wild during the #1133 rollout
  1076. # — the kiosk kept showing the pre-fix picker for hours after every
  1077. # cache-clear attempt because the persistent profile would re-seed
  1078. # the cache from disk on next start.
  1079. # 2. A stuck Service Worker registration, which intercepted requests
  1080. # with its own cache layer (CacheStorage), independent of the HTTP
  1081. # cache. Even after \`rm -rf Default/Cache/*\` the SW could replay
  1082. # stale responses from CacheStorage until explicitly unregistered.
  1083. #
  1084. # Wiping the user-data-dir on every launch is the simplest, most
  1085. # bulletproof escape hatch — every kiosk restart is now functionally
  1086. # equivalent to a private-window first-load. Future deploys propagate
  1087. # automatically: the next chromium launch picks up the latest bundle
  1088. # without any extra tooling. Trade-off is a slightly slower first paint
  1089. # (no warm cache) and zero offline support, neither of which matter for
  1090. # a single-purpose kiosk facing a backend on the same LAN.
  1091. USER_DATA_DIR="/tmp/spoolbuddy-kiosk-userdata"
  1092. rm -rf "\$USER_DATA_DIR"
  1093. exec chromium --kiosk --no-first-run --disable-infobars \
  1094. --disable-session-crashed-bubble --disable-features=TranslateUI \
  1095. --noerrdialogs --disable-component-update \
  1096. --overscroll-history-navigation=0 \
  1097. --ozone-platform=wayland \
  1098. --disable-crash-reporter --disable-breakpad \
  1099. --user-data-dir="\$USER_DATA_DIR" \
  1100. "\$kiosk_url"
  1101. EOF
  1102. chmod 755 "$kiosk_launcher"
  1103. # Tiny self-check: ensure sed command substitutions were not expanded
  1104. # while generating the launcher script.
  1105. if ! grep -Fq 'backend_url="$(sed -n' "$kiosk_launcher" || ! grep -Fq 'api_key="$(sed -n' "$kiosk_launcher"; then
  1106. error "Kiosk launcher generation failed: dynamic env parsing commands were expanded unexpectedly"
  1107. fi
  1108. # ── labwc autostart ───────────────────────────────────────────────────
  1109. cat > "$labwc_dir/autostart" << EOF
  1110. # Force 1024x600 (panel doesn't advertise this natively)
  1111. wlr-randr --output HDMI-A-1 --custom-mode 1024x600@60 &
  1112. # Idle watchdog: powers off HDMI via wlopm after the configured inactivity
  1113. # timeout (SpoolBuddy Settings → Display → Screen blank timeout). Reads the
  1114. # current value from the backend on startup; UI changes take effect on the
  1115. # next reboot / kiosk restart.
  1116. $INSTALL_PATH/spoolbuddy/install/spoolbuddy-idle.sh &
  1117. # Launch Chromium via helper that resolves URL from spoolbuddy/.env
  1118. $kiosk_launcher &
  1119. EOF
  1120. chown -R "$KIOSK_USER:$KIOSK_USER" "$labwc_dir"
  1121. # ── .bash_profile (source .bashrc, exec labwc on tty1) ────────────────
  1122. cat > "$KIOSK_HOME/.bash_profile" << 'EOF'
  1123. # Source .bashrc if it exists
  1124. if [ -f ~/.bashrc ]; then
  1125. . ~/.bashrc
  1126. fi
  1127. # Auto-start kiosk on tty1
  1128. if [ "$(tty)" = "/dev/tty1" ]; then
  1129. exec labwc
  1130. fi
  1131. EOF
  1132. chown "$KIOSK_USER:$KIOSK_USER" "$KIOSK_HOME/.bash_profile"
  1133. REBOOT_NEEDED="true"
  1134. success "Kiosk setup complete"
  1135. }
  1136. # ─────────────────────────────────────────────────────────────────────────────
  1137. # User Prompts
  1138. # ─────────────────────────────────────────────────────────────────────────────
  1139. parse_args() {
  1140. while [[ $# -gt 0 ]]; do
  1141. case "$1" in
  1142. --mode)
  1143. INSTALL_MODE="$2"
  1144. shift 2
  1145. ;;
  1146. --repo)
  1147. INSTALL_REPO="$(normalize_github_repo_url "$2")"
  1148. shift 2
  1149. ;;
  1150. --ref)
  1151. INSTALL_REF="$2"
  1152. shift 2
  1153. ;;
  1154. --bambuddy-url)
  1155. BAMBUDDY_URL="$2"
  1156. shift 2
  1157. ;;
  1158. --api-key)
  1159. API_KEY="$2"
  1160. shift 2
  1161. ;;
  1162. --path)
  1163. INSTALL_PATH="$2"
  1164. shift 2
  1165. ;;
  1166. --port)
  1167. BAMBUDDY_PORT="$2"
  1168. shift 2
  1169. ;;
  1170. --ssh-pubkey)
  1171. SSH_PUBKEY="$2"
  1172. shift 2
  1173. ;;
  1174. --yes|-y)
  1175. NON_INTERACTIVE="true"
  1176. shift
  1177. ;;
  1178. --help|-h)
  1179. show_help
  1180. ;;
  1181. *)
  1182. error "Unknown option: $1 (use --help for usage)"
  1183. ;;
  1184. esac
  1185. done
  1186. }
  1187. ask_install_mode() {
  1188. if [[ -n "$INSTALL_MODE" ]]; then
  1189. return
  1190. fi
  1191. echo ""
  1192. echo -e "${BOLD}How would you like to set up SpoolBuddy?${NC}"
  1193. echo ""
  1194. echo -e " ${CYAN}1)${NC} SpoolBuddy only"
  1195. echo " NFC reader + scale on this RPi, Bambuddy runs on another device"
  1196. echo ""
  1197. echo -e " ${CYAN}2)${NC} SpoolBuddy + Bambuddy"
  1198. echo " Both running natively on this Raspberry Pi"
  1199. echo ""
  1200. while true; do
  1201. echo -en "${BOLD}Choose${NC} [${CYAN}1${NC}/${CYAN}2${NC}]: "
  1202. read -r choice
  1203. case "$choice" in
  1204. 1) INSTALL_MODE="spoolbuddy"; return;;
  1205. 2) INSTALL_MODE="full"; return;;
  1206. *) echo "Please enter 1 or 2.";;
  1207. esac
  1208. done
  1209. }
  1210. gather_config() {
  1211. echo ""
  1212. echo -e "${BOLD}Configuration${NC}"
  1213. echo -e "${CYAN}─────────────────────────────────────────${NC}"
  1214. echo ""
  1215. # Set default install path based on mode
  1216. if [[ -z "$INSTALL_PATH" ]]; then
  1217. if [[ "$INSTALL_MODE" == "full" ]]; then
  1218. INSTALL_PATH="/opt/bambuddy"
  1219. else
  1220. INSTALL_PATH="/opt/bambuddy"
  1221. fi
  1222. fi
  1223. prompt "Installation directory" "$INSTALL_PATH" INSTALL_PATH
  1224. if [[ -z "$INSTALL_REPO" ]]; then
  1225. INSTALL_REPO="$GITHUB_REPO"
  1226. fi
  1227. prompt "Git repository URL" "$INSTALL_REPO" INSTALL_REPO
  1228. INSTALL_REPO="$(normalize_github_repo_url "$INSTALL_REPO")"
  1229. if [[ -z "$INSTALL_REF" ]]; then
  1230. INSTALL_REF="main"
  1231. fi
  1232. if [[ "$NON_INTERACTIVE" != "true" && -n "$DETECTED_INSTALLER_REF" && "$DETECTED_INSTALLER_REF" != "HEAD" ]]; then
  1233. echo ""
  1234. echo -e "${BOLD}Install Source Ref${NC}"
  1235. echo "1) main"
  1236. echo "2) $DETECTED_INSTALLER_REF (detected from installer context)"
  1237. echo "3) custom"
  1238. while true; do
  1239. echo -en "${BOLD}Choose${NC} [1/2/3]: "
  1240. read -r ref_choice
  1241. case "$ref_choice" in
  1242. ""|1)
  1243. INSTALL_REF="main"
  1244. break
  1245. ;;
  1246. 2)
  1247. INSTALL_REF="$DETECTED_INSTALLER_REF"
  1248. break
  1249. ;;
  1250. 3)
  1251. prompt "Git ref (branch/tag/commit)" "$INSTALL_REF" INSTALL_REF
  1252. break
  1253. ;;
  1254. *)
  1255. echo "Please enter 1, 2, or 3."
  1256. ;;
  1257. esac
  1258. done
  1259. else
  1260. prompt "Git ref (branch/tag/commit)" "$INSTALL_REF" INSTALL_REF
  1261. fi
  1262. if [[ "$INSTALL_MODE" == "spoolbuddy" ]]; then
  1263. # Need remote Bambuddy URL and API key
  1264. echo ""
  1265. info "SpoolBuddy needs to connect to your Bambuddy server."
  1266. info "You can find/create an API key in Bambuddy under Settings -> API Keys."
  1267. echo ""
  1268. while [[ -z "$BAMBUDDY_URL" ]]; do
  1269. prompt "Bambuddy server URL (e.g. http://192.168.1.100:8000)" "" BAMBUDDY_URL
  1270. if [[ -z "$BAMBUDDY_URL" ]]; then
  1271. warn "Bambuddy URL is required"
  1272. fi
  1273. done
  1274. while [[ -z "$API_KEY" ]]; do
  1275. prompt "Bambuddy API key" "" API_KEY
  1276. if [[ -z "$API_KEY" ]]; then
  1277. warn "API key is required"
  1278. fi
  1279. done
  1280. else
  1281. # Full mode — Bambuddy runs locally
  1282. prompt "Bambuddy port" "$BAMBUDDY_PORT" BAMBUDDY_PORT
  1283. BAMBUDDY_URL="http://localhost:$BAMBUDDY_PORT"
  1284. echo ""
  1285. info "After installation, create an API key in Bambuddy (Settings -> API Keys)"
  1286. info "and update it in: $INSTALL_PATH/spoolbuddy/.env"
  1287. API_KEY="CHANGE_ME_AFTER_SETUP"
  1288. fi
  1289. # Summary
  1290. echo ""
  1291. echo -e "${BOLD}Installation Summary${NC}"
  1292. echo -e "${CYAN}─────────────────────────────────────────${NC}"
  1293. echo -e " Mode: ${GREEN}$([ "$INSTALL_MODE" == "full" ] && echo "Bambuddy + SpoolBuddy" || echo "SpoolBuddy only")${NC}"
  1294. echo -e " Install path: ${GREEN}$INSTALL_PATH${NC}"
  1295. echo -e " Git repo: ${GREEN}$INSTALL_REPO${NC}"
  1296. echo -e " Git ref: ${GREEN}$INSTALL_REF${NC}"
  1297. if [[ "$INSTALL_MODE" == "full" ]]; then
  1298. echo -e " Bambuddy port: ${GREEN}$BAMBUDDY_PORT${NC}"
  1299. echo -e " Bambuddy URL: ${GREEN}$BAMBUDDY_URL${NC}"
  1300. else
  1301. echo -e " Bambuddy URL: ${GREEN}$BAMBUDDY_URL${NC}"
  1302. fi
  1303. echo ""
  1304. if ! prompt_yes_no "Proceed with installation?" "y"; then
  1305. echo "Installation cancelled."
  1306. exit 0
  1307. fi
  1308. }
  1309. # ─────────────────────────────────────────────────────────────────────────────
  1310. # Main
  1311. # ─────────────────────────────────────────────────────────────────────────────
  1312. main() {
  1313. parse_args "$@"
  1314. detect_installer_source_context
  1315. echo ""
  1316. echo -e "${CYAN}╔══════════════════════════════════════════════════════════╗${NC}"
  1317. echo -e "${CYAN}║ ║${NC}"
  1318. echo -e "${CYAN}║ ____ _ ____ _ _ ║${NC}"
  1319. echo -e "${CYAN}║ / ___| _ __ ___ ___ | | __ ) _ _ __| | __| |_ _ ║${NC}"
  1320. echo -e "${CYAN}║ \\___ \\| '_ \\ / _ \\ / _ \\| | _ \\| | | |/ _\` |/ _\` | | | |║${NC}"
  1321. echo -e "${CYAN}║ ___) | |_) | (_) | (_) | | |_) | |_| | (_| | (_| | |_| |║${NC}"
  1322. echo -e "${CYAN}║ |____/| .__/ \\___/ \\___/|_|____/ \\__,_|\\__,_|\\__,_|\\__, |║${NC}"
  1323. echo -e "${CYAN}║ |_| |___/ ║${NC}"
  1324. echo -e "${CYAN}║ ║${NC}"
  1325. echo -e "${CYAN}║ NFC Spool Management for Bambuddy ║${NC}"
  1326. echo -e "${CYAN}║ ║${NC}"
  1327. echo -e "${CYAN}╚══════════════════════════════════════════════════════════╝${NC}"
  1328. echo ""
  1329. # Check if running via pipe without -y
  1330. if [[ ! -t 0 ]] && [[ "$NON_INTERACTIVE" != "true" ]]; then
  1331. error "Interactive mode requires a terminal. Use -y for unattended install, or download and run directly."
  1332. fi
  1333. # Pre-flight checks
  1334. check_root
  1335. check_raspberry_pi
  1336. check_raspberry_pi_os
  1337. if ! detect_python; then
  1338. info "Python 3.10+ not found, will install..."
  1339. fi
  1340. # Gather user preferences
  1341. ask_install_mode
  1342. gather_config
  1343. # Validate mode
  1344. if [[ "$INSTALL_MODE" != "spoolbuddy" && "$INSTALL_MODE" != "full" ]]; then
  1345. error "Invalid mode: $INSTALL_MODE (must be 'spoolbuddy' or 'full')"
  1346. fi
  1347. echo ""
  1348. echo -e "${BOLD}Starting Installation${NC}"
  1349. echo -e "${CYAN}─────────────────────────────────────────${NC}"
  1350. echo ""
  1351. # ── Step 1: Raspberry Pi hardware config ──────────────────────────────
  1352. info "Configuring Raspberry Pi hardware..."
  1353. enable_spi
  1354. enable_i2c
  1355. configure_boot_config
  1356. echo ""
  1357. # ── Step 2: System packages ───────────────────────────────────────────
  1358. install_system_packages
  1359. install_wifi_safeguard
  1360. upgrade_system_packages
  1361. detect_python || error "Failed to install Python 3.10+"
  1362. echo ""
  1363. # ── Step 2b: Strip unnecessary services & packages ────────────────────
  1364. strip_services
  1365. strip_packages
  1366. echo ""
  1367. # ── Step 3: Download source code ──────────────────────────────────────
  1368. create_spoolbuddy_user
  1369. download_spoolbuddy
  1370. echo ""
  1371. # ── Step 3b: Kiosk setup (labwc + Chromium + squeekboard + Plymouth) ──
  1372. setup_kiosk
  1373. echo ""
  1374. # ── Step 4: SpoolBuddy setup ──────────────────────────────────────────
  1375. info "Setting up SpoolBuddy..."
  1376. setup_spoolbuddy_venv
  1377. create_spoolbuddy_env
  1378. # Kiosk env access: only needed if actual kiosk hardware is available
  1379. if [[ -f /boot/firmware/config.txt ]] || [[ -f /boot/config.txt ]]; then
  1380. ensure_kiosk_env_access
  1381. fi
  1382. setup_ssh_key
  1383. create_spoolbuddy_service
  1384. echo ""
  1385. # ── Step 5: Bambuddy setup (full mode only) ───────────────────────────
  1386. if [[ "$INSTALL_MODE" == "full" ]]; then
  1387. info "Setting up Bambuddy..."
  1388. create_bambuddy_user
  1389. setup_bambuddy_venv
  1390. install_nodejs
  1391. build_frontend
  1392. create_bambuddy_directories
  1393. create_bambuddy_env
  1394. create_bambuddy_service
  1395. bootstrap_spoolbuddy_kiosk_key
  1396. echo ""
  1397. fi
  1398. # ── Done ──────────────────────────────────────────────────────────────
  1399. echo ""
  1400. echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
  1401. echo -e "${GREEN}║ ║${NC}"
  1402. echo -e "${GREEN}║ Installation Complete! ║${NC}"
  1403. echo -e "${GREEN}║ ║${NC}"
  1404. echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${NC}"
  1405. echo ""
  1406. local ip_addr
  1407. ip_addr=$(hostname -I 2>/dev/null | awk '{print $1}') || ip_addr="<your-ip>"
  1408. if [[ "$INSTALL_MODE" == "full" ]]; then
  1409. echo -e " ${BOLD}Bambuddy:${NC} ${CYAN}http://$ip_addr:$BAMBUDDY_PORT${NC}"
  1410. else
  1411. echo -e " ${BOLD}SpoolBuddy:${NC} Connecting to ${CYAN}$BAMBUDDY_URL${NC}"
  1412. fi
  1413. echo -e " ${BOLD}Kiosk URL:${NC} ${CYAN}$KIOSK_URL${NC}"
  1414. echo -e " ${BOLD}Kiosk user:${NC} ${CYAN}$KIOSK_USER${NC}"
  1415. echo ""
  1416. if [[ "$INSTALL_MODE" == "full" ]]; then
  1417. echo -e " ${BOLD}Next steps:${NC}"
  1418. echo -e " 1. Reboot (required for kiosk, Plymouth splash, and hardware changes)"
  1419. echo -e " 2. The touchscreen kiosk will start automatically after reboot"
  1420. echo -e " 3. On another device, open ${CYAN}http://$ip_addr:$BAMBUDDY_PORT${NC} to complete first-run admin setup"
  1421. fi
  1422. echo ""
  1423. echo -e " ${BOLD}Manage services:${NC}"
  1424. echo -e " SpoolBuddy status: ${CYAN}sudo systemctl status spoolbuddy${NC}"
  1425. echo -e " SpoolBuddy logs: ${CYAN}sudo journalctl -u spoolbuddy -f${NC}"
  1426. if [[ "$INSTALL_MODE" == "full" ]]; then
  1427. echo -e " Bambuddy status: ${CYAN}sudo systemctl status bambuddy${NC}"
  1428. echo -e " Bambuddy logs: ${CYAN}sudo journalctl -u bambuddy -f${NC}"
  1429. fi
  1430. echo ""
  1431. echo -e " ${BOLD}Configuration:${NC} ${CYAN}$INSTALL_PATH/spoolbuddy/.env${NC}"
  1432. echo -e " ${BOLD}Hardware wiring:${NC} ${CYAN}$INSTALL_PATH/spoolbuddy/README.md${NC}"
  1433. echo -e " ${BOLD}Diagnostics:${NC} ${CYAN}sudo $INSTALL_PATH/spoolbuddy/venv/bin/python $INSTALL_PATH/spoolbuddy/pn5180_diag.py${NC}"
  1434. echo ""
  1435. echo -e " ${YELLOW}A reboot is required to apply all changes (kiosk, Plymouth splash, hardware).${NC}"
  1436. echo ""
  1437. if prompt_yes_no "Reboot now?" "y"; then
  1438. reboot
  1439. else
  1440. echo -e " Run ${CYAN}sudo reboot${NC} when ready."
  1441. fi
  1442. echo ""
  1443. }
  1444. main "$@"