install.sh 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  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"
  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. cat > /etc/systemd/system/bambuddy.service << EOF
  638. [Unit]
  639. Description=Bambuddy - Bambu Lab Print Management
  640. Documentation=https://github.com/maziggy/bambuddy
  641. After=network.target
  642. [Service]
  643. Type=simple
  644. User=$BAMBUDDY_SERVICE_USER
  645. Group=$BAMBUDDY_SERVICE_USER
  646. WorkingDirectory=$INSTALL_PATH
  647. EnvironmentFile=$INSTALL_PATH/.env
  648. Environment="DATA_DIR=$INSTALL_PATH/data"
  649. Environment="LOG_DIR=$INSTALL_PATH/logs"
  650. ExecStart=$INSTALL_PATH/venv/bin/uvicorn backend.app.main:app --host 0.0.0.0 --port $BAMBUDDY_PORT
  651. Restart=on-failure
  652. RestartSec=5
  653. StandardOutput=journal
  654. StandardError=journal
  655. NoNewPrivileges=true
  656. PrivateTmp=true
  657. ProtectSystem=strict
  658. ProtectHome=true
  659. ReadWritePaths=$INSTALL_PATH/data $INSTALL_PATH/logs $INSTALL_PATH
  660. [Install]
  661. WantedBy=multi-user.target
  662. EOF
  663. systemctl daemon-reload
  664. systemctl enable bambuddy.service
  665. success "Bambuddy service created and enabled"
  666. }
  667. bootstrap_spoolbuddy_kiosk_key() {
  668. # Provision an API key for the local SpoolBuddy kiosk and write it into
  669. # spoolbuddy/.env. Runs against the Bambuddy DB directly (via the CLI),
  670. # so the bambuddy service does not need to be running yet.
  671. info "Provisioning SpoolBuddy kiosk API key..."
  672. local env_file="$INSTALL_PATH/spoolbuddy/.env"
  673. if [[ ! -f "$env_file" ]]; then
  674. warn "SpoolBuddy env file not found at $env_file — skipping kiosk key bootstrap"
  675. return
  676. fi
  677. # CWD must be $INSTALL_PATH so `python -m backend.app.cli` finds the backend
  678. # package on sys.path (matches the systemd unit's WorkingDirectory).
  679. local kiosk_key
  680. if ! kiosk_key="$(cd "$INSTALL_PATH" && sudo -u "$BAMBUDDY_SERVICE_USER" \
  681. env DATA_DIR="$INSTALL_PATH/data" LOG_DIR="$INSTALL_PATH/logs" \
  682. "$INSTALL_PATH/venv/bin/python" -m backend.app.cli kiosk-bootstrap --force)"; then
  683. error "Failed to bootstrap SpoolBuddy kiosk API key"
  684. fi
  685. if [[ -z "$kiosk_key" || "$kiosk_key" != bb_* ]]; then
  686. error "CLI returned an invalid API key (got: ${kiosk_key:0:8}...)"
  687. fi
  688. if ! grep -q '^SPOOLBUDDY_API_KEY=' "$env_file"; then
  689. error "Sentinel 'SPOOLBUDDY_API_KEY=' line missing in $env_file"
  690. fi
  691. # Escape for sed replacement (the key is base64url-safe, no slashes, but be defensive)
  692. local escaped_key
  693. escaped_key=$(printf '%s\n' "$kiosk_key" | sed -e 's/[\/&]/\\&/g')
  694. sed -i "s/^SPOOLBUDDY_API_KEY=.*/SPOOLBUDDY_API_KEY=${escaped_key}/" "$env_file"
  695. success "SpoolBuddy kiosk API key provisioned"
  696. }
  697. # ─────────────────────────────────────────────────────────────────────────────
  698. # System Strip-Down (dedicated appliance — remove unnecessary services/packages)
  699. # ─────────────────────────────────────────────────────────────────────────────
  700. strip_services() {
  701. info "Disabling unnecessary services..."
  702. local services=(
  703. bluetooth.service
  704. lightdm.service
  705. cloud-init-local.service
  706. cloud-init.service
  707. cloud-init-network.service
  708. cloud-config.service
  709. cloud-final.service
  710. cloud-init-hotplugd.socket
  711. avahi-daemon.service
  712. avahi-daemon.socket
  713. ModemManager.service
  714. udisks2.service
  715. apparmor.service
  716. man-db.timer
  717. e2scrub_all.timer
  718. e2scrub_reap.service
  719. # Audio stack (no speakers on a spool reader)
  720. pipewire.service
  721. pipewire.socket
  722. pipewire-pulse.service
  723. pipewire-pulse.socket
  724. wireplumber.service
  725. # Printing
  726. cups.service
  727. cups.socket
  728. cups-browsed.service
  729. # Desktop services
  730. accounts-daemon.service
  731. upower.service
  732. polkit.service
  733. # Flatpak portals (not using Flatpak)
  734. xdg-desktop-portal.service
  735. xdg-desktop-portal-gtk.service
  736. xdg-document-portal.service
  737. xdg-permission-store.service
  738. # NFS/RPC (unnecessary + security surface)
  739. rpcbind.service
  740. rpcbind.socket
  741. # Bluetooth media proxy
  742. mpris-proxy.service
  743. )
  744. local disabled=0
  745. for svc in "${services[@]}"; do
  746. if systemctl is-enabled "$svc" &>/dev/null; then
  747. systemctl disable "$svc" 2>/dev/null || true
  748. systemctl mask "$svc" 2>/dev/null || true
  749. (( ++disabled ))
  750. fi
  751. done
  752. if (( disabled > 0 )); then
  753. success "Disabled $disabled unnecessary services"
  754. else
  755. success "No unnecessary services to disable"
  756. fi
  757. # Mask user-level services globally via /etc/systemd/user/ overrides.
  758. # The su-based approach doesn't reliably reach the user's systemd instance
  759. # when run from sudo, so we create global masks that apply before login.
  760. local user_services=(
  761. pipewire.service
  762. pipewire.socket
  763. pipewire-pulse.service
  764. pipewire-pulse.socket
  765. wireplumber.service
  766. xdg-desktop-portal.service
  767. xdg-desktop-portal-gtk.service
  768. xdg-document-portal.service
  769. xdg-permission-store.service
  770. mpris-proxy.service
  771. )
  772. mkdir -p /etc/systemd/user
  773. local user_masked=0
  774. for svc in "${user_services[@]}"; do
  775. if [[ ! -L "/etc/systemd/user/$svc" ]] || [[ "$(readlink /etc/systemd/user/$svc)" != "/dev/null" ]]; then
  776. ln -sf /dev/null "/etc/systemd/user/$svc"
  777. (( ++user_masked ))
  778. fi
  779. done
  780. if (( user_masked > 0 )); then
  781. success "Masked $user_masked unnecessary user services globally"
  782. fi
  783. }
  784. strip_packages() {
  785. info "Removing unnecessary packages..."
  786. local packages=(
  787. mkvtoolnix
  788. firmware-atheros
  789. firmware-mediatek
  790. cloud-init
  791. rpi-cloud-init-mods
  792. rpi-connect-lite
  793. avahi-daemon
  794. modemmanager
  795. udisks2
  796. pipewire
  797. pipewire-pulse
  798. wireplumber
  799. cups
  800. cups-browsed
  801. cups-common
  802. cups-client
  803. rpcbind
  804. )
  805. local to_remove=()
  806. for pkg in "${packages[@]}"; do
  807. if dpkg -l "$pkg" &>/dev/null 2>&1; then
  808. to_remove+=("$pkg")
  809. fi
  810. done
  811. if (( ${#to_remove[@]} > 0 )); then
  812. run_with_progress "Removing ${#to_remove[@]} packages" apt-get remove --purge -y "${to_remove[@]}"
  813. run_with_progress "Cleaning up dependencies" apt-get autoremove --purge -y
  814. else
  815. success "No unnecessary packages to remove"
  816. fi
  817. }
  818. # ─────────────────────────────────────────────────────────────────────────────
  819. # Kiosk Setup (labwc + Chromium + Plymouth splash)
  820. # ─────────────────────────────────────────────────────────────────────────────
  821. setup_kiosk() {
  822. info "Setting up touchscreen kiosk..."
  823. # Detect kiosk user (the human user who ran sudo)
  824. KIOSK_USER="${SUDO_USER:-$(logname 2>/dev/null || echo pi)}"
  825. KIOSK_URL="${BAMBUDDY_URL}/spoolbuddy?token=${API_KEY}"
  826. local KIOSK_HOME
  827. KIOSK_HOME=$(eval echo "~$KIOSK_USER")
  828. info "Kiosk user: $KIOSK_USER (home: $KIOSK_HOME)"
  829. info "Kiosk URL: $KIOSK_URL"
  830. # Allow kiosk user to read SpoolBuddy env so launcher can resolve backend URL
  831. # and API key dynamically instead of using stale install-time fallback values.
  832. local spoolbuddy_env="$INSTALL_PATH/spoolbuddy/.env"
  833. if [[ -f "$spoolbuddy_env" ]]; then
  834. usermod -aG "$SPOOLBUDDY_SERVICE_USER" "$KIOSK_USER" 2>/dev/null || true
  835. chgrp "$SPOOLBUDDY_SERVICE_USER" "$spoolbuddy_env" 2>/dev/null || true
  836. chmod 640 "$spoolbuddy_env" 2>/dev/null || true
  837. fi
  838. # ── Install kiosk packages ────────────────────────────────────────────
  839. # Temporarily block initramfs rebuilds during package install — we rebuild
  840. # once at the end after the Plymouth theme is configured, saving ~4 runs
  841. # (one per installed kernel per hook trigger).
  842. if [[ -x /usr/sbin/update-initramfs ]]; then
  843. dpkg-divert --local --rename --add /usr/sbin/update-initramfs >/dev/null 2>&1 || true
  844. ln -sf /bin/true /usr/sbin/update-initramfs
  845. fi
  846. run_with_progress "Installing kiosk packages" apt-get install -y labwc chromium plymouth wlr-randr swayidle wlopm jq curl
  847. # Restore real update-initramfs
  848. if dpkg-divert --list /usr/sbin/update-initramfs 2>/dev/null | grep -q local; then
  849. rm -f /usr/sbin/update-initramfs
  850. dpkg-divert --local --rename --remove /usr/sbin/update-initramfs >/dev/null 2>&1 || true
  851. fi
  852. # ── config.txt tweaks ─────────────────────────────────────────────────
  853. local boot_config="/boot/firmware/config.txt"
  854. if [[ ! -f "$boot_config" ]]; then
  855. boot_config="/boot/config.txt"
  856. fi
  857. if [[ -f "$boot_config" ]]; then
  858. info "Configuring $boot_config for kiosk..."
  859. # Disable audio (change existing on→off)
  860. sed -i 's/^dtparam=audio=on/dtparam=audio=off/' "$boot_config"
  861. # Disable camera auto-detect (change existing 1→0)
  862. sed -i 's/^camera_auto_detect=1/camera_auto_detect=0/' "$boot_config"
  863. # Append if missing: gpu_mem=32
  864. if ! grep -q "^gpu_mem=" "$boot_config"; then
  865. echo "" >> "$boot_config"
  866. echo "# Kiosk: Minimal GPU firmware memory (KMS uses CMA from system RAM)" >> "$boot_config"
  867. echo "gpu_mem=32" >> "$boot_config"
  868. fi
  869. # Append if missing: dtoverlay=disable-bt
  870. if ! grep -q "^dtoverlay=disable-bt" "$boot_config"; then
  871. echo "" >> "$boot_config"
  872. echo "# Kiosk: Disable Bluetooth hardware" >> "$boot_config"
  873. echo "dtoverlay=disable-bt" >> "$boot_config"
  874. fi
  875. # Append if missing: disable_splash=1
  876. if ! grep -q "^disable_splash=" "$boot_config"; then
  877. echo "" >> "$boot_config"
  878. echo "# Kiosk: Disable Raspberry Pi firmware splash, use custom splash.png" >> "$boot_config"
  879. echo "disable_splash=1" >> "$boot_config"
  880. fi
  881. success "Boot config updated"
  882. fi
  883. # ── cmdline.txt tweaks ────────────────────────────────────────────────
  884. local cmdline="/boot/firmware/cmdline.txt"
  885. if [[ ! -f "$cmdline" ]]; then
  886. cmdline="/boot/cmdline.txt"
  887. fi
  888. if [[ -f "$cmdline" ]]; then
  889. info "Configuring $cmdline for kiosk..."
  890. # Remove serial console (Plymouth needs tty-only console)
  891. sed -i 's/console=serial0,[0-9]* //' "$cmdline"
  892. # Disable console blanking (kernel default is 600s, can blank during boot transition)
  893. grep -q "consoleblank=" "$cmdline" || sed -i 's/$/ consoleblank=0/' "$cmdline"
  894. # Add splash quiet loglevel=3 logo.nologo if missing
  895. grep -q "splash" "$cmdline" || sed -i 's/$/ splash quiet loglevel=3 logo.nologo/' "$cmdline"
  896. # Add video mode if missing
  897. grep -q "video=HDMI-A-1" "$cmdline" || sed -i 's/$/ video=HDMI-A-1:1024x600@60/' "$cmdline"
  898. success "Kernel cmdline updated"
  899. fi
  900. # ── Plymouth splash theme ─────────────────────────────────────────────
  901. info "Installing Plymouth boot splash..."
  902. local theme_dir="/usr/share/plymouth/themes/spoolbuddy"
  903. mkdir -p "$theme_dir"
  904. # Copy bundled splash image from the install directory
  905. local script_dir
  906. script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  907. if [[ -f "$script_dir/splash.png" ]]; then
  908. cp "$script_dir/splash.png" "$theme_dir/splash.png"
  909. elif [[ -f "$INSTALL_PATH/spoolbuddy/install/splash.png" ]]; then
  910. cp "$INSTALL_PATH/spoolbuddy/install/splash.png" "$theme_dir/splash.png"
  911. else
  912. warn "splash.png not found — Plymouth splash will not display an image"
  913. fi
  914. # Write .plymouth theme file
  915. cat > "$theme_dir/spoolbuddy.plymouth" << 'EOF'
  916. [Plymouth Theme]
  917. Name=SpoolBuddy
  918. Description=SpoolBuddy boot splash
  919. ModuleName=script
  920. [script]
  921. ImageDir=/usr/share/plymouth/themes/spoolbuddy
  922. ScriptFile=/usr/share/plymouth/themes/spoolbuddy/spoolbuddy.script
  923. EOF
  924. # Write .script theme file
  925. cat > "$theme_dir/spoolbuddy.script" << 'EOF'
  926. wallpaper_image = Image("splash.png");
  927. screen_width = Window.GetWidth();
  928. screen_height = Window.GetHeight();
  929. resized_wallpaper_image = wallpaper_image.Scale(screen_width, screen_height);
  930. wallpaper_sprite = Sprite(resized_wallpaper_image);
  931. wallpaper_sprite.SetZ(-100);
  932. EOF
  933. plymouth-set-default-theme spoolbuddy
  934. run_with_progress "Updating initramfs" update-initramfs -u
  935. success "Plymouth splash installed"
  936. # ── Auto-login on tty1 ────────────────────────────────────────────────
  937. info "Configuring auto-login for $KIOSK_USER..."
  938. mkdir -p /etc/systemd/system/getty@tty1.service.d
  939. cat > /etc/systemd/system/getty@tty1.service.d/autologin.conf << EOF
  940. [Unit]
  941. After=network-online.target
  942. Wants=network-online.target
  943. [Service]
  944. ExecStart=
  945. ExecStart=-/sbin/agetty --autologin $KIOSK_USER --noclear %I \$TERM
  946. EOF
  947. success "Auto-login configured"
  948. # ── labwc rc.xml (no decorations, no keybinds) ────────────────────────
  949. info "Configuring labwc window manager..."
  950. local labwc_dir="$KIOSK_HOME/.config/labwc"
  951. mkdir -p "$labwc_dir"
  952. cat > "$labwc_dir/rc.xml" << 'EOF'
  953. <?xml version="1.0"?>
  954. <labwc_config>
  955. <!-- Disable screen blanking — kiosk must stay on -->
  956. <core>
  957. <screenBlankTimeout>0</screenBlankTimeout>
  958. </core>
  959. <theme>
  960. <name></name>
  961. <cornerRadius>0</cornerRadius>
  962. </theme>
  963. <!-- Disable all keybindings - kiosk lockdown -->
  964. <keyboard>
  965. </keyboard>
  966. <!-- Disable right-click menu -->
  967. <mouse>
  968. <default />
  969. </mouse>
  970. <!-- Remove window decorations, maximize Chromium, prevent unfullscreen -->
  971. <windowRules>
  972. <windowRule identifier="*">
  973. <serverDecoration>no</serverDecoration>
  974. </windowRule>
  975. <windowRule identifier="chromium">
  976. <skipTaskbar>yes</skipTaskbar>
  977. <fixedPosition>yes</fixedPosition>
  978. </windowRule>
  979. </windowRules>
  980. </labwc_config>
  981. EOF
  982. # ── Override Debian/RPi Chromium defaults for kiosk performance ──────
  983. cat > /etc/chromium.d/spoolbuddy-kiosk << 'CHROMIUM_EOF'
  984. # SpoolBuddy kiosk: add kiosk-specific flags on top of Pi defaults.
  985. # Preserves Pi GPU settings (gpu-rasterization, ANGLE/GLES) for stability.
  986. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-smooth-scrolling"
  987. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-extensions"
  988. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-background-timer-throttling"
  989. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-renderer-backgrounding"
  990. CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disable-crash-reporter"
  991. CHROMIUM_EOF
  992. success "Chromium kiosk performance flags installed"
  993. # ── kiosk launcher (dynamic URL from spoolbuddy/.env) ─────────────────
  994. local kiosk_launcher="/usr/local/bin/spoolbuddy-kiosk-launch"
  995. cat > "$kiosk_launcher" << EOF
  996. #!/usr/bin/env bash
  997. set -euo pipefail
  998. ENV_FILE="$INSTALL_PATH/spoolbuddy/.env"
  999. FALLBACK_URL="$KIOSK_URL"
  1000. backend_url=""
  1001. api_key=""
  1002. if [[ -r "\$ENV_FILE" ]]; then
  1003. backend_url="\$(sed -n 's/^SPOOLBUDDY_BACKEND_URL=//p' "\$ENV_FILE" | tail -n1 | tr -d '\r')"
  1004. api_key="\$(sed -n 's/^SPOOLBUDDY_API_KEY=//p' "\$ENV_FILE" | tail -n1 | tr -d '\r')"
  1005. backend_url="\${backend_url%\"}"
  1006. backend_url="\${backend_url#\"}"
  1007. api_key="\${api_key%\"}"
  1008. api_key="\${api_key#\"}"
  1009. elif [[ -f "\$ENV_FILE" ]]; then
  1010. echo "spoolbuddy-kiosk-launch: ERROR: \$ENV_FILE exists but is not readable" >&2
  1011. echo "spoolbuddy-kiosk-launch: Fix permissions (group-readable by kiosk user) and restart kiosk" >&2
  1012. exit 1
  1013. fi
  1014. if [[ -n "\$backend_url" && -n "\$api_key" ]]; then
  1015. backend_url="\${backend_url%/}"
  1016. kiosk_url="\${backend_url}/spoolbuddy?token=\${api_key}"
  1017. else
  1018. kiosk_url="\$FALLBACK_URL"
  1019. fi
  1020. # Wait for the Bambuddy backend to be reachable before launching Chromium.
  1021. # Without this the browser opens before uvicorn has bound to the port on a
  1022. # cold boot and the user sees an ERR_CONNECTION_REFUSED splash until they
  1023. # manually reload. Probe /health (no auth, no body) with a short timeout.
  1024. probe_url="\${backend_url:-http://localhost}/health"
  1025. for _i in \$(seq 1 60); do
  1026. if curl -sf --max-time 2 "\$probe_url" >/dev/null 2>&1; then
  1027. break
  1028. fi
  1029. sleep 1
  1030. done
  1031. # Ephemeral user-data-dir under /tmp + wipe on every launch.
  1032. #
  1033. # The kiosk has no per-user state worth persisting (the auth token is in
  1034. # the URL query, not a stored cookie), but the default profile at
  1035. # ~/.config/chromium was accumulating two specific kinds of state across
  1036. # reboots that broke deploys badly:
  1037. #
  1038. # 1. HTTP disk cache holding old index.html across browser restarts.
  1039. # Chromium's heuristic-cache freshness window kept the old HTML
  1040. # "fresh" for days, which referenced an old content-hashed bundle,
  1041. # so newly deployed code never reached the running tab even after
  1042. # pkill+relaunch. Reproduced in the wild during the #1133 rollout
  1043. # — the kiosk kept showing the pre-fix picker for hours after every
  1044. # cache-clear attempt because the persistent profile would re-seed
  1045. # the cache from disk on next start.
  1046. # 2. A stuck Service Worker registration, which intercepted requests
  1047. # with its own cache layer (CacheStorage), independent of the HTTP
  1048. # cache. Even after \`rm -rf Default/Cache/*\` the SW could replay
  1049. # stale responses from CacheStorage until explicitly unregistered.
  1050. #
  1051. # Wiping the user-data-dir on every launch is the simplest, most
  1052. # bulletproof escape hatch — every kiosk restart is now functionally
  1053. # equivalent to a private-window first-load. Future deploys propagate
  1054. # automatically: the next chromium launch picks up the latest bundle
  1055. # without any extra tooling. Trade-off is a slightly slower first paint
  1056. # (no warm cache) and zero offline support, neither of which matter for
  1057. # a single-purpose kiosk facing a backend on the same LAN.
  1058. USER_DATA_DIR="/tmp/spoolbuddy-kiosk-userdata"
  1059. rm -rf "\$USER_DATA_DIR"
  1060. exec chromium --kiosk --no-first-run --disable-infobars \
  1061. --disable-session-crashed-bubble --disable-features=TranslateUI \
  1062. --noerrdialogs --disable-component-update \
  1063. --overscroll-history-navigation=0 \
  1064. --ozone-platform=wayland \
  1065. --disable-crash-reporter --disable-breakpad \
  1066. --user-data-dir="\$USER_DATA_DIR" \
  1067. "\$kiosk_url"
  1068. EOF
  1069. chmod 755 "$kiosk_launcher"
  1070. # Tiny self-check: ensure sed command substitutions were not expanded
  1071. # while generating the launcher script.
  1072. if ! grep -Fq 'backend_url="$(sed -n' "$kiosk_launcher" || ! grep -Fq 'api_key="$(sed -n' "$kiosk_launcher"; then
  1073. error "Kiosk launcher generation failed: dynamic env parsing commands were expanded unexpectedly"
  1074. fi
  1075. # ── labwc autostart ───────────────────────────────────────────────────
  1076. cat > "$labwc_dir/autostart" << EOF
  1077. # Force 1024x600 (panel doesn't advertise this natively)
  1078. wlr-randr --output HDMI-A-1 --custom-mode 1024x600@60 &
  1079. # Idle watchdog: powers off HDMI via wlopm after the configured inactivity
  1080. # timeout (SpoolBuddy Settings → Display → Screen blank timeout). Reads the
  1081. # current value from the backend on startup; UI changes take effect on the
  1082. # next reboot / kiosk restart.
  1083. $INSTALL_PATH/spoolbuddy/install/spoolbuddy-idle.sh &
  1084. # Launch Chromium via helper that resolves URL from spoolbuddy/.env
  1085. $kiosk_launcher &
  1086. EOF
  1087. chown -R "$KIOSK_USER:$KIOSK_USER" "$labwc_dir"
  1088. # ── .bash_profile (source .bashrc, exec labwc on tty1) ────────────────
  1089. cat > "$KIOSK_HOME/.bash_profile" << 'EOF'
  1090. # Source .bashrc if it exists
  1091. if [ -f ~/.bashrc ]; then
  1092. . ~/.bashrc
  1093. fi
  1094. # Auto-start kiosk on tty1
  1095. if [ "$(tty)" = "/dev/tty1" ]; then
  1096. exec labwc
  1097. fi
  1098. EOF
  1099. chown "$KIOSK_USER:$KIOSK_USER" "$KIOSK_HOME/.bash_profile"
  1100. REBOOT_NEEDED="true"
  1101. success "Kiosk setup complete"
  1102. }
  1103. # ─────────────────────────────────────────────────────────────────────────────
  1104. # User Prompts
  1105. # ─────────────────────────────────────────────────────────────────────────────
  1106. parse_args() {
  1107. while [[ $# -gt 0 ]]; do
  1108. case "$1" in
  1109. --mode)
  1110. INSTALL_MODE="$2"
  1111. shift 2
  1112. ;;
  1113. --repo)
  1114. INSTALL_REPO="$(normalize_github_repo_url "$2")"
  1115. shift 2
  1116. ;;
  1117. --ref)
  1118. INSTALL_REF="$2"
  1119. shift 2
  1120. ;;
  1121. --bambuddy-url)
  1122. BAMBUDDY_URL="$2"
  1123. shift 2
  1124. ;;
  1125. --api-key)
  1126. API_KEY="$2"
  1127. shift 2
  1128. ;;
  1129. --path)
  1130. INSTALL_PATH="$2"
  1131. shift 2
  1132. ;;
  1133. --port)
  1134. BAMBUDDY_PORT="$2"
  1135. shift 2
  1136. ;;
  1137. --ssh-pubkey)
  1138. SSH_PUBKEY="$2"
  1139. shift 2
  1140. ;;
  1141. --yes|-y)
  1142. NON_INTERACTIVE="true"
  1143. shift
  1144. ;;
  1145. --help|-h)
  1146. show_help
  1147. ;;
  1148. *)
  1149. error "Unknown option: $1 (use --help for usage)"
  1150. ;;
  1151. esac
  1152. done
  1153. }
  1154. ask_install_mode() {
  1155. if [[ -n "$INSTALL_MODE" ]]; then
  1156. return
  1157. fi
  1158. echo ""
  1159. echo -e "${BOLD}How would you like to set up SpoolBuddy?${NC}"
  1160. echo ""
  1161. echo -e " ${CYAN}1)${NC} SpoolBuddy only"
  1162. echo " NFC reader + scale on this RPi, Bambuddy runs on another device"
  1163. echo ""
  1164. echo -e " ${CYAN}2)${NC} SpoolBuddy + Bambuddy"
  1165. echo " Both running natively on this Raspberry Pi"
  1166. echo ""
  1167. while true; do
  1168. echo -en "${BOLD}Choose${NC} [${CYAN}1${NC}/${CYAN}2${NC}]: "
  1169. read -r choice
  1170. case "$choice" in
  1171. 1) INSTALL_MODE="spoolbuddy"; return;;
  1172. 2) INSTALL_MODE="full"; return;;
  1173. *) echo "Please enter 1 or 2.";;
  1174. esac
  1175. done
  1176. }
  1177. gather_config() {
  1178. echo ""
  1179. echo -e "${BOLD}Configuration${NC}"
  1180. echo -e "${CYAN}─────────────────────────────────────────${NC}"
  1181. echo ""
  1182. # Set default install path based on mode
  1183. if [[ -z "$INSTALL_PATH" ]]; then
  1184. if [[ "$INSTALL_MODE" == "full" ]]; then
  1185. INSTALL_PATH="/opt/bambuddy"
  1186. else
  1187. INSTALL_PATH="/opt/bambuddy"
  1188. fi
  1189. fi
  1190. prompt "Installation directory" "$INSTALL_PATH" INSTALL_PATH
  1191. if [[ -z "$INSTALL_REPO" ]]; then
  1192. INSTALL_REPO="$GITHUB_REPO"
  1193. fi
  1194. prompt "Git repository URL" "$INSTALL_REPO" INSTALL_REPO
  1195. INSTALL_REPO="$(normalize_github_repo_url "$INSTALL_REPO")"
  1196. if [[ -z "$INSTALL_REF" ]]; then
  1197. INSTALL_REF="main"
  1198. fi
  1199. if [[ "$NON_INTERACTIVE" != "true" && -n "$DETECTED_INSTALLER_REF" && "$DETECTED_INSTALLER_REF" != "HEAD" ]]; then
  1200. echo ""
  1201. echo -e "${BOLD}Install Source Ref${NC}"
  1202. echo "1) main"
  1203. echo "2) $DETECTED_INSTALLER_REF (detected from installer context)"
  1204. echo "3) custom"
  1205. while true; do
  1206. echo -en "${BOLD}Choose${NC} [1/2/3]: "
  1207. read -r ref_choice
  1208. case "$ref_choice" in
  1209. ""|1)
  1210. INSTALL_REF="main"
  1211. break
  1212. ;;
  1213. 2)
  1214. INSTALL_REF="$DETECTED_INSTALLER_REF"
  1215. break
  1216. ;;
  1217. 3)
  1218. prompt "Git ref (branch/tag/commit)" "$INSTALL_REF" INSTALL_REF
  1219. break
  1220. ;;
  1221. *)
  1222. echo "Please enter 1, 2, or 3."
  1223. ;;
  1224. esac
  1225. done
  1226. else
  1227. prompt "Git ref (branch/tag/commit)" "$INSTALL_REF" INSTALL_REF
  1228. fi
  1229. if [[ "$INSTALL_MODE" == "spoolbuddy" ]]; then
  1230. # Need remote Bambuddy URL and API key
  1231. echo ""
  1232. info "SpoolBuddy needs to connect to your Bambuddy server."
  1233. info "You can find/create an API key in Bambuddy under Settings -> API Keys."
  1234. echo ""
  1235. while [[ -z "$BAMBUDDY_URL" ]]; do
  1236. prompt "Bambuddy server URL (e.g. http://192.168.1.100:8000)" "" BAMBUDDY_URL
  1237. if [[ -z "$BAMBUDDY_URL" ]]; then
  1238. warn "Bambuddy URL is required"
  1239. fi
  1240. done
  1241. while [[ -z "$API_KEY" ]]; do
  1242. prompt "Bambuddy API key" "" API_KEY
  1243. if [[ -z "$API_KEY" ]]; then
  1244. warn "API key is required"
  1245. fi
  1246. done
  1247. else
  1248. # Full mode — Bambuddy runs locally
  1249. prompt "Bambuddy port" "$BAMBUDDY_PORT" BAMBUDDY_PORT
  1250. BAMBUDDY_URL="http://localhost:$BAMBUDDY_PORT"
  1251. echo ""
  1252. info "After installation, create an API key in Bambuddy (Settings -> API Keys)"
  1253. info "and update it in: $INSTALL_PATH/spoolbuddy/.env"
  1254. API_KEY="CHANGE_ME_AFTER_SETUP"
  1255. fi
  1256. # Summary
  1257. echo ""
  1258. echo -e "${BOLD}Installation Summary${NC}"
  1259. echo -e "${CYAN}─────────────────────────────────────────${NC}"
  1260. echo -e " Mode: ${GREEN}$([ "$INSTALL_MODE" == "full" ] && echo "Bambuddy + SpoolBuddy" || echo "SpoolBuddy only")${NC}"
  1261. echo -e " Install path: ${GREEN}$INSTALL_PATH${NC}"
  1262. echo -e " Git repo: ${GREEN}$INSTALL_REPO${NC}"
  1263. echo -e " Git ref: ${GREEN}$INSTALL_REF${NC}"
  1264. if [[ "$INSTALL_MODE" == "full" ]]; then
  1265. echo -e " Bambuddy port: ${GREEN}$BAMBUDDY_PORT${NC}"
  1266. echo -e " Bambuddy URL: ${GREEN}$BAMBUDDY_URL${NC}"
  1267. else
  1268. echo -e " Bambuddy URL: ${GREEN}$BAMBUDDY_URL${NC}"
  1269. fi
  1270. echo ""
  1271. if ! prompt_yes_no "Proceed with installation?" "y"; then
  1272. echo "Installation cancelled."
  1273. exit 0
  1274. fi
  1275. }
  1276. # ─────────────────────────────────────────────────────────────────────────────
  1277. # Main
  1278. # ─────────────────────────────────────────────────────────────────────────────
  1279. main() {
  1280. parse_args "$@"
  1281. detect_installer_source_context
  1282. echo ""
  1283. echo -e "${CYAN}╔══════════════════════════════════════════════════════════╗${NC}"
  1284. echo -e "${CYAN}║ ║${NC}"
  1285. echo -e "${CYAN}║ ____ _ ____ _ _ ║${NC}"
  1286. echo -e "${CYAN}║ / ___| _ __ ___ ___ | | __ ) _ _ __| | __| |_ _ ║${NC}"
  1287. echo -e "${CYAN}║ \\___ \\| '_ \\ / _ \\ / _ \\| | _ \\| | | |/ _\` |/ _\` | | | |║${NC}"
  1288. echo -e "${CYAN}║ ___) | |_) | (_) | (_) | | |_) | |_| | (_| | (_| | |_| |║${NC}"
  1289. echo -e "${CYAN}║ |____/| .__/ \\___/ \\___/|_|____/ \\__,_|\\__,_|\\__,_|\\__, |║${NC}"
  1290. echo -e "${CYAN}║ |_| |___/ ║${NC}"
  1291. echo -e "${CYAN}║ ║${NC}"
  1292. echo -e "${CYAN}║ NFC Spool Management for Bambuddy ║${NC}"
  1293. echo -e "${CYAN}║ ║${NC}"
  1294. echo -e "${CYAN}╚══════════════════════════════════════════════════════════╝${NC}"
  1295. echo ""
  1296. # Check if running via pipe without -y
  1297. if [[ ! -t 0 ]] && [[ "$NON_INTERACTIVE" != "true" ]]; then
  1298. error "Interactive mode requires a terminal. Use -y for unattended install, or download and run directly."
  1299. fi
  1300. # Pre-flight checks
  1301. check_root
  1302. check_raspberry_pi
  1303. check_raspberry_pi_os
  1304. if ! detect_python; then
  1305. info "Python 3.10+ not found, will install..."
  1306. fi
  1307. # Gather user preferences
  1308. ask_install_mode
  1309. gather_config
  1310. # Validate mode
  1311. if [[ "$INSTALL_MODE" != "spoolbuddy" && "$INSTALL_MODE" != "full" ]]; then
  1312. error "Invalid mode: $INSTALL_MODE (must be 'spoolbuddy' or 'full')"
  1313. fi
  1314. echo ""
  1315. echo -e "${BOLD}Starting Installation${NC}"
  1316. echo -e "${CYAN}─────────────────────────────────────────${NC}"
  1317. echo ""
  1318. # ── Step 1: Raspberry Pi hardware config ──────────────────────────────
  1319. info "Configuring Raspberry Pi hardware..."
  1320. enable_spi
  1321. enable_i2c
  1322. configure_boot_config
  1323. echo ""
  1324. # ── Step 2: System packages ───────────────────────────────────────────
  1325. install_system_packages
  1326. install_wifi_safeguard
  1327. upgrade_system_packages
  1328. detect_python || error "Failed to install Python 3.10+"
  1329. echo ""
  1330. # ── Step 2b: Strip unnecessary services & packages ────────────────────
  1331. strip_services
  1332. strip_packages
  1333. echo ""
  1334. # ── Step 3: Download source code ──────────────────────────────────────
  1335. create_spoolbuddy_user
  1336. download_spoolbuddy
  1337. echo ""
  1338. # ── Step 3b: Kiosk setup (labwc + Chromium + squeekboard + Plymouth) ──
  1339. setup_kiosk
  1340. echo ""
  1341. # ── Step 4: SpoolBuddy setup ──────────────────────────────────────────
  1342. info "Setting up SpoolBuddy..."
  1343. setup_spoolbuddy_venv
  1344. create_spoolbuddy_env
  1345. # Kiosk env access: only needed if actual kiosk hardware is available
  1346. if [[ -f /boot/firmware/config.txt ]] || [[ -f /boot/config.txt ]]; then
  1347. ensure_kiosk_env_access
  1348. fi
  1349. setup_ssh_key
  1350. create_spoolbuddy_service
  1351. echo ""
  1352. # ── Step 5: Bambuddy setup (full mode only) ───────────────────────────
  1353. if [[ "$INSTALL_MODE" == "full" ]]; then
  1354. info "Setting up Bambuddy..."
  1355. create_bambuddy_user
  1356. setup_bambuddy_venv
  1357. install_nodejs
  1358. build_frontend
  1359. create_bambuddy_directories
  1360. create_bambuddy_env
  1361. create_bambuddy_service
  1362. bootstrap_spoolbuddy_kiosk_key
  1363. echo ""
  1364. fi
  1365. # ── Done ──────────────────────────────────────────────────────────────
  1366. echo ""
  1367. echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
  1368. echo -e "${GREEN}║ ║${NC}"
  1369. echo -e "${GREEN}║ Installation Complete! ║${NC}"
  1370. echo -e "${GREEN}║ ║${NC}"
  1371. echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${NC}"
  1372. echo ""
  1373. local ip_addr
  1374. ip_addr=$(hostname -I 2>/dev/null | awk '{print $1}') || ip_addr="<your-ip>"
  1375. if [[ "$INSTALL_MODE" == "full" ]]; then
  1376. echo -e " ${BOLD}Bambuddy:${NC} ${CYAN}http://$ip_addr:$BAMBUDDY_PORT${NC}"
  1377. else
  1378. echo -e " ${BOLD}SpoolBuddy:${NC} Connecting to ${CYAN}$BAMBUDDY_URL${NC}"
  1379. fi
  1380. echo -e " ${BOLD}Kiosk URL:${NC} ${CYAN}$KIOSK_URL${NC}"
  1381. echo -e " ${BOLD}Kiosk user:${NC} ${CYAN}$KIOSK_USER${NC}"
  1382. echo ""
  1383. if [[ "$INSTALL_MODE" == "full" ]]; then
  1384. echo -e " ${BOLD}Next steps:${NC}"
  1385. echo -e " 1. Reboot (required for kiosk, Plymouth splash, and hardware changes)"
  1386. echo -e " 2. The touchscreen kiosk will start automatically after reboot"
  1387. echo -e " 3. On another device, open ${CYAN}http://$ip_addr:$BAMBUDDY_PORT${NC} to complete first-run admin setup"
  1388. fi
  1389. echo ""
  1390. echo -e " ${BOLD}Manage services:${NC}"
  1391. echo -e " SpoolBuddy status: ${CYAN}sudo systemctl status spoolbuddy${NC}"
  1392. echo -e " SpoolBuddy logs: ${CYAN}sudo journalctl -u spoolbuddy -f${NC}"
  1393. if [[ "$INSTALL_MODE" == "full" ]]; then
  1394. echo -e " Bambuddy status: ${CYAN}sudo systemctl status bambuddy${NC}"
  1395. echo -e " Bambuddy logs: ${CYAN}sudo journalctl -u bambuddy -f${NC}"
  1396. fi
  1397. echo ""
  1398. echo -e " ${BOLD}Configuration:${NC} ${CYAN}$INSTALL_PATH/spoolbuddy/.env${NC}"
  1399. echo -e " ${BOLD}Hardware wiring:${NC} ${CYAN}$INSTALL_PATH/spoolbuddy/README.md${NC}"
  1400. echo -e " ${BOLD}Diagnostics:${NC} ${CYAN}sudo $INSTALL_PATH/spoolbuddy/venv/bin/python $INSTALL_PATH/spoolbuddy/pn5180_diag.py${NC}"
  1401. echo ""
  1402. echo -e " ${YELLOW}A reboot is required to apply all changes (kiosk, Plymouth splash, hardware).${NC}"
  1403. echo ""
  1404. if prompt_yes_no "Reboot now?" "y"; then
  1405. reboot
  1406. else
  1407. echo -e " Run ${CYAN}sudo reboot${NC} when ready."
  1408. fi
  1409. echo ""
  1410. }
  1411. main "$@"