Files
opsbox/install.sh
T
2026-11-23 18:23:37 -05:00

1949 lines
85 KiB
Bash

#!/usr/bin/env bash
set -Eeuo pipefail
# OpsBox bootstrap + installer. Keep the Git URL in one place.
OPSBOX_GIT_REPO="${OPSBOX_GIT_REPO:-https://git.zakscode.com/ztimson/opsbox.git}"
OPSBOX_VERSION="1.3.0"
OPSBOX_DIR="${OPSBOX_DIR:-}"
CONFIG_DIR="/etc/opsbox"
STATE_FILE="$CONFIG_DIR/selections"
DL_FILE="$CONFIG_DIR/downloads"
ENV_FILE="$CONFIG_DIR/opsbox.env"
THEME_DIR="/usr/local/share/opsbox"
DATA_ROOT=""
INSTALL_ROOT=""
TMP_DIR=""
LOCK_FILE="/run/lock/opsbox-install.lock"
APT_UPGRADE="no"
USE_CADDY=""
OPSBOX_DOMAIN="${OPSBOX_DOMAIN:-$(hostname -s | tr '[:upper:]' '[:lower:]').internal}"
ADMIN_USER="${SUDO_USER:-${USER:-root}}"
DOCKER_REGISTRY="git.zakscode.com"
DOCKER_USER=""
DOCKER_PASS=""
DOCKER_OK="no"
FAILED=()
SUCCEEDED=()
SELECTED=()
NET_ROWS=()
ZIM_ORDER=()
DL_LOADED=""
SUM=""
declare -A COMP_LABEL=() SEL_DL=() ZIM_NAME=() ZIM_REASON=() ZIM_TITLE=() ZIM_BYTES=() ZIM_URL=() ZIM_MANUAL=()
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; RESET='\033[0m'
log() { printf '%b[opsbox]%b %s\n' "$GREEN" "$RESET" "$*"; }
warn() { printf '%b[warning]%b %s\n' "$YELLOW" "$RESET" "$*" >&2; }
err() { printf '%b[error]%b %s\n' "$RED" "$RESET" "$*" >&2; }
die() { err "$*"; exit 1; }
cleanup() {
[[ -n "$TMP_DIR" && -d "$TMP_DIR" ]] && rm -rf -- "$TMP_DIR"
}
trap cleanup EXIT
trap 'rc=$?; err "Unexpected failure on line $LINENO (exit $rc)"; exit "$rc"' ERR
require_root() { [[ $EUID -eq 0 ]] || die "Run as root: curl ... | sudo bash"; }
# --------------------------------------------------------------------------------------
# Port scheme
# Web UIs live in 8010-8090: one block of ten per service family, in install order.
# 8010 LibreSpeed | 8020-8022 Maps (Cartomake, TileServer, Photon) | 8030-8031 Cloud
# 8040 OpenWebRX+ | 8050 WireGuard Portal | 8060-8061 Bettercap (UI, API)
# 8070 Meshtastic | 8090 TAK web UI
# Fixed ports (not configurable, reserved so nothing else can be assigned to them):
# 53 DNS | 80/443 Caddy | 2947 gpsd | 8089, 8446 TAK streaming/enrollment | 51820/udp WireGuard
# --------------------------------------------------------------------------------------
FIXED_PORTS=(
"53|DNS (*.domain -> this machine)"
"80|Caddy HTTP"
"443|Caddy HTTPS"
"2947|gpsd"
"8089|TAK streaming (TLS)"
"8446|TAK certificate enrollment"
"51820|WireGuard VPN (UDP)"
)
reserved_port() {
local p="$1" e
for e in "${FIXED_PORTS[@]}"; do
if [[ "${e%%|*}" == "$p" ]]; then printf '%s' "${e#*|}"; return 0; fi
done
return 1
}
# Older installs saved the previous defaults; move them onto the new scheme.
# Only values that still equal the old default are touched (custom choices are kept).
migrate_ports() {
local spec var old new cur
for spec in LIBRESPEED_PORT:1900:8010 HARNESS_PORT:8082:8030 OFFICE_PORT:8083:8031 \
OPENWEBRX_PORT:8073:8040 WG_PORTAL_UI_PORT:8888:8050 \
BETTERCAP_UI_PORT:1600:8060 BETTERCAP_API_PORT:8081:8061; do
IFS=: read -r var old new <<<"$spec"
cur="${!var-}"
if [[ "$cur" == "$old" ]]; then
printf -v "$var" '%s' "$new"
log "Port scheme: $var $old -> $new"
fi
done
}
# --------------------------------------------------------------------------------------
# Catalogue of components (alphabetical by tag)
# --------------------------------------------------------------------------------------
COMPONENTS=(
"ai|Local AI (LiteRT)"
"fallback-ap|Fallback wireless access point"
"maps|Maps (Cartomake web UI)"
"pentest|Pen test suite (host tools + Bettercap)"
"personal-cloud|Personal cloud (AI, file editing, notes, ZIM reader)"
"sdr-tools|OpenWebRX+ (SDR receiver)"
"speedtest|LibreSpeed speed test"
"tak|Tactical awareness kit (OpenTAK Server)"
"theme|Terminal prompt theme and login banner"
"tools|Tools (btop, jq, tmux)"
"vnc|VNC remote desktop"
"wireguard|WireGuard VPN"
"wireless-hat|4-in-1 (GPS, Lora, SDR, RTC) + Meshtastic + shared gpsd"
"zims|ZIM archives (offline Wikipedia, manuals, ...)"
)
for _c in "${COMPONENTS[@]}"; do COMP_LABEL["${_c%%|*}"]="${_c#*|}"; done
GB=1073741824
declare -A MAP_LABEL=(
[m_photon]="Photon geocoder (~69 GB)"
[m_tiles]="TileServer GL (serves the tile sets below)"
[m_sat]="MapTiler Satellite tiles (~186 GB)"
[m_vec]="MapTiler Vector tiles (~70 GB)"
[m_cont]="Contour tiles (~18 GB)"
)
declare -A MAP_BYTES=([m_photon]=$((69*GB)) [m_tiles]=0 [m_sat]=$((186*GB)) [m_vec]=$((70*GB)) [m_cont]=$((18*GB)))
ZIM_WANTED=(
"Amateur Radio Q&A|Radio operations, amateur radio reference and troubleshooting"
"based.cooking|Simple, practical cooking recipes and food preparation"
"CD3WD Project|Sustainable technologies, agriculture, water, energy and development"
"CrashCourse|Educational video-course reference across school subjects"
"Food for preppers|Food storage, preservation and practical emergency cooking"
"iFixit|Device repair guides, teardowns and troubleshooting"
"K-12 Education LibreTexts|Open K-12 textbooks and educational resources"
"Khan Academy|Lessons and practice for mathematics, science and other subjects"
"MedlinePlus|Consumer health information from the US National Library of Medicine"
"Medical Library|Medical reference and clinical learning resources"
"Military Manuals|Military field manuals, doctrine and training references"
"Pets Q&A|Veterinary and pet-care questions and answers"
"PhET|Interactive science and mathematics simulations"
"Project Gutenberg|Public-domain books and literature"
"Ready.gov|Disaster preparedness and emergency planning"
"S2 Underground|Open-source intelligence and signal-intelligence topics"
"WikiBooks|Community-authored books and manuals"
"Wikipedia|General-purpose encyclopedia and reference"
"Wikisource|Free source texts, historical documents and literature"
)
# --------------------------------------------------------------------------------------
# Basics
# --------------------------------------------------------------------------------------
init() {
require_root
OPSBOX_DIR="$(realpath -e -- "$OPSBOX_DIR")"
[[ -f "$OPSBOX_DIR/install.sh" && -d "$OPSBOX_DIR/docker" ]] || die "Invalid OpsBox repository directory: $OPSBOX_DIR"
INSTALL_ROOT="$OPSBOX_DIR"
DATA_ROOT="$OPSBOX_DIR/data"
mkdir -p "$CONFIG_DIR" "$DATA_ROOT" /var/log/opsbox
chmod 0750 "$CONFIG_DIR"
TMP_DIR="$(mktemp -d /tmp/opsbox.XXXXXX)"
exec 9>"$LOCK_FILE"
flock -n 9 || die "Another OpsBox installer is already running."
touch "$STATE_FILE" "$DL_FILE" "$ENV_FILE"
chmod 0600 "$ENV_FILE"
# This file is root-owned and generated by this installer.
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a
migrate_ports
DATA_ROOT="${OPSBOX_DATA_ROOT:-$DATA_ROOT}"
OPSBOX_DATA_ROOT="$DATA_ROOT"
ADMIN_USER="${OPSBOX_ADMIN_USER:-$ADMIN_USER}"
# One shared account, reused by every service that needs a first user.
OPSBOX_ADMIN_USERNAME="${OPSBOX_ADMIN_USERNAME:-$ADMIN_USER}"
OPSBOX_ADMIN_EMAIL="${OPSBOX_ADMIN_EMAIL:-${WG_PORTAL_ADMIN_USER:-admin@$OPSBOX_DOMAIN}}"
OPSBOX_ADMIN_PASSWORD="${OPSBOX_ADMIN_PASSWORD:-${BETTERCAP_PASSWORD:-${WG_PORTAL_ADMIN_PASSWORD:-${OPENWEBRX_ADMIN_PASSWORD:-}}}}"
DOCKER_USER="${DOCKER_REGISTRY_USER:-}"
}
has_cmd() { command -v "$1" >/dev/null 2>&1; }
contains() { local needle="$1" x; for x in "${SELECTED[@]}"; do [[ "$x" == "$needle" ]] && return 0; done; return 1; }
ensure_prereqs() {
log "Installing installer prerequisites (dialog, curl, python3)..."
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends dialog curl python3 ca-certificates openssl >/dev/null
}
save_env() {
local key value line sed_line
for key in "$@"; do
value="${!key-}"
value="${value//\\/\\\\}"
value="${value//\"/\\\"}"
value="${value//\$/\\\$}"
value="${value//\`/\\\`}"
line="${key}=\"${value}\""
if grep -q "^${key}=" "$ENV_FILE"; then
sed_line="${line//\\/\\\\}"
sed_line="${sed_line//&/\\&}"
sed_line="${sed_line//|/\\|}"
sed -i "s|^${key}=.*|${sed_line}|" "$ENV_FILE"
else
printf '%s\n' "$line" >> "$ENV_FILE"
fi
done
chmod 0600 "$ENV_FILE"
}
# Plain KEY=value writer for third-party project .env files (no quoting).
env_put() {
local file="$1" key="$2" value="$3"
touch "$file"
if grep -q "^${key}=" "$file"; then
local esc="${value//\\/\\\\}"; esc="${esc//&/\\&}"; esc="${esc//|/\\|}"
sed -i "s|^${key}=.*|${key}=${esc}|" "$file"
else
printf '%s=%s\n' "$key" "$value" >> "$file"
fi
}
valid_sub() { [[ "$1" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ ]]; }
valid_port() { [[ "$1" =~ ^[0-9]+$ ]] && (( 10#$1 >= 1 && 10#$1 <= 65535 )); }
valid_url() { [[ "$1" =~ ^https?:// ]]; }
yesno_norm() { case "${1,,}" in y|yes|true|1) echo yes;; n|no|false|0) echo no;; *) return 1;; esac; }
apt_install() {
local packages=("$@")
((${#packages[@]})) || return 0
apt-get install -y --no-install-recommends "${packages[@]}"
}
fetch() {
local url="$1" output="$2"
curl --fail --location --retry 3 --retry-delay 2 --connect-timeout 20 "$url" -o "$output"
}
zim_size_gb() { awk -v b="${1:-0}" 'BEGIN { printf "%.2f GB", b/1073741824 }'; }
free_bytes() {
local p="$1"
while [[ ! -d "$p" && "$p" != / ]]; do p="$(dirname "$p")"; done
df -PB1 "$p" | awk 'NR==2{print $4}'
}
# --------------------------------------------------------------------------------------
# dialog helpers
# --------------------------------------------------------------------------------------
BACK="Back"
dlg() { dialog --backtitle "OpsBox installer v$OPSBOX_VERSION" --cr-wrap --no-collapse "$@"; }
msg() { dlg --title "OpsBox" --msgbox "$1" 0 0 || true; }
ask_yes() { dlg --title "OpsBox" --yesno "$1" 0 0; }
tlines() { tput lines 2>/dev/null || echo 24; }
tcols() { tput cols 2>/dev/null || echo 80; }
# form_run TITLE TEXT spec... spec = VAR|Label|t (t = text, p = password)
# Pre-fills each field from the variable VAR and writes the edited values back.
# Returns 1 when the user presses Back / Esc.
form_run() {
local title="$1" text="$2"; shift 2
local -a specs=("$@") args=() vals=()
local n=${#specs[@]} i=0 maxl=0 spec var label type val itype out
local lines cols tl h fh w
for spec in "${specs[@]}"; do
IFS='|' read -r var label type <<<"$spec"
if ((${#label} + 1 > maxl)); then maxl=$((${#label} + 1)); fi
done
for spec in "${specs[@]}"; do
IFS='|' read -r var label type <<<"$spec"
i=$((i + 1)); itype=0
if [[ "$type" == p ]]; then itype=1; fi
val="${!var-}"
args+=("$label:" "$i" 1 "$val" "$i" "$((maxl + 3))" 44 255 "$itype")
done
lines="$(tlines)"; cols="$(tcols)"
tl=$(( $(printf '%s' "$text" | wc -l) + 1 ))
h=$((n + tl + 7)); ((h > lines)) && h=$lines || true
fh=$((h - tl - 7)); ((fh < 3)) && fh=3 || true
w=$((maxl + 58)); ((w < 78)) && w=78 || true; ((w > cols)) && w=$cols || true
out="$(dlg --title "$title" --ok-label "Next" --cancel-label "$BACK" --insecure \
--mixedform "$text" "$h" "$w" "$fh" "${args[@]}" 3>&1 1>&2 2>&3)" || return 1
mapfile -t vals <<<"$out"
i=0
for spec in "${specs[@]}"; do
IFS='|' read -r var label type <<<"$spec"
printf -v "$var" '%s' "${vals[i]-}"
i=$((i + 1))
done
}
# run_steps fn... Each fn returns 0 (next), 1 (back) or 10 (not applicable, skip).
# Returns 1 when the user goes back past the first applicable step.
run_steps() {
local -a steps=("$@")
local i=0 dir=1 rc
while ((i >= 0 && i < ${#steps[@]})); do
rc=0; "${steps[i]}" || rc=$?
case $rc in
0) dir=1; i=$((i + 1)) ;;
10) i=$((i + dir)) ;;
*) dir=-1; i=$((i - 1)) ;;
esac
done
((i < 0)) && return 1
return 0
}
# --------------------------------------------------------------------------------------
# Bootstrap
# --------------------------------------------------------------------------------------
bootstrap() {
[[ "${1:-}" == --installed ]] && { OPSBOX_DIR="${2:?Missing install directory}"; return 0; }
[[ $EUID -eq 0 ]] || die "Run as root: curl ... | sudo bash"
local default_dir answer target parent
default_dir="$(pwd -P)"
[[ -r /dev/tty ]] || die "An interactive terminal is required to choose the install directory."
printf '\nOpsBox installation directory [%s]: ' "$default_dir" > /dev/tty
IFS= read -r answer < /dev/tty || die "Could not read install directory."
target="${answer:-$default_dir}"
target="${target/#\~/$HOME}"
[[ "$target" == /* ]] || target="$(pwd -P)/$target"
target="$(realpath -m -- "$target")"
parent="$(dirname "$target")"
mkdir -p "$parent"
log "Updating package indexes..."
apt-get update
log "Installing Git..."
DEBIAN_FRONTEND=noninteractive apt-get install -y git ca-certificates
if [[ -d "$target/.git" ]]; then
local origin
origin="$(git -C "$target" remote get-url origin 2>/dev/null || true)"
[[ "$origin" == "$OPSBOX_GIT_REPO" ]] || die "The directory is a Git repository with a different origin: $origin"
log "Updating existing OpsBox checkout..."
git -C "$target" pull --ff-only
elif [[ -d "$target" ]] && [[ -n "$(find "$target" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then
die "Install directory is not empty and is not a OpsBox checkout: $target\nChoose an empty directory or an existing OpsBox checkout."
else
log "Cloning OpsBox into $target..."
git clone --depth 1 "$OPSBOX_GIT_REPO" "$target"
fi
[[ -f "$target/install.sh" ]] || die "The repository checkout does not contain install.sh."
# stdin is the curl pipe when bootstrapped; the TUI needs the real terminal.
exec bash "$target/install.sh" --installed "$target" </dev/tty
}
run_component() {
local name="$1" fn="$2"
log "Installing $name..."
if "$fn"; then
SUCCEEDED+=("$name")
log "$name completed."
else
FAILED+=("$name")
err "$name failed; continuing with other selections."
fi
}
run_docker_component() {
local name="$1" fn="$2"
if [[ "$DOCKER_OK" != yes ]]; then
FAILED+=("$name (Docker unavailable)")
err "Skipping $name: Docker is not ready."
return 0
fi
run_component "$name" "$fn"
}
# ======================================================================================
# WIZARD
# ======================================================================================
# ---- Step 1: components -------------------------------------------------------------
step_components() {
local -a choices=() sel=()
local pair tag label lines lh selected t
sed -i -e '/^docker$/d' -e 's/^opentak$/tak/' -e 's/^atak$/tak/' -e 's/^hat$/wireless-hat/' "$STATE_FILE"
if grep -qxE '^(adsb|openwebrx|rtl433|sdr)$' "$STATE_FILE"; then
grep -qx 'sdr-tools' "$STATE_FILE" || echo 'sdr-tools' >> "$STATE_FILE"
sed -i -e '/^adsb$/d' -e '/^openwebrx$/d' -e '/^rtl433$/d' -e '/^sdr$/d' "$STATE_FILE"
fi
lines="$(tlines)"; lh=$((lines - 9)); ((lh > 16)) && lh=16 || true; ((lh < 5)) && lh=5 || true
while true; do
choices=()
for pair in "${COMPONENTS[@]}"; do
tag="${pair%%|*}"; label="${pair#*|}"
if grep -qx "$tag" "$STATE_FILE"; then choices+=("$tag" "$label" on); else choices+=("$tag" "$label" off); fi
done
selected="$(dlg --title "OpsBox - Components" --ok-label "Next" --cancel-label "Exit" --separate-output \
--checklist "Select the components to install (Space = toggle).\nDocker Engine is always installed. Existing data and configuration are preserved." \
$((lh + 8)) 92 "$lh" "${choices[@]}" 3>&1 1>&2 2>&3)" || return 1
sel=(); SELECTED=()
mapfile -t sel <<<"$selected"
for t in "${sel[@]}"; do [[ -n "$t" ]] && SELECTED+=("$t"); done
printf '%s\n' "${SELECTED[@]}" > "$STATE_FILE"
if ((${#SELECTED[@]})); then return 0; fi
msg "Select at least one component."
done
}
# ---- Step 2: maps / ZIM downloads ----------------------------------------------------
fetch_zim_catalogue() {
local xml="$TMP_DIR/kiwix-opds.xml" tsv="$TMP_DIR/zims.tsv"
curl -fsSL --compressed --retry 3 'https://opds.library.kiwix.org/catalog/v2/entries?count=-1' -o "$xml" || return 1
python3 - "$xml" "$tsv" <<'PY' || return 1
import sys, xml.etree.ElementTree as ET, re
from urllib.parse import urljoin
src, dst = sys.argv[1:]
root = ET.parse(src).getroot()
ns = {'a':'http://www.w3.org/2005/Atom', 'd':'http://purl.org/dc/terms/'}
items=[]
for e in root.findall('.//a:entry', ns):
title=(e.findtext('a:title', default='', namespaces=ns) or '').strip()
if not title: continue
size=0
for node in e.iter():
tag=node.tag.rsplit('}',1)[-1].lower()
if tag in ('extent','size','filesize') and node.text:
m=re.search(r'([0-9]+(?:\.[0-9]+)?)\s*(gb|gib|mb|mib|bytes?)?', node.text, re.I)
if m:
n=float(m.group(1)); unit=(m.group(2) or 'bytes').lower()
size=int(n * (1024**3 if unit in ('gb','gib') else 1024**2 if unit in ('mb','mib') else 1))
break
language=''
for node in e.iter():
if node.tag.rsplit('}',1)[-1].lower() in ('language', 'lang') and node.text:
language=node.text.strip().lower(); break
if language and language not in ('en','eng','english'): continue
links=[]
for link in e.findall('a:link', ns):
rel=(link.get('rel') or '').lower(); typ=(link.get('type') or '').lower(); href=link.get('href') or ''
if href and ('acquisition' in rel or 'application/x-zim' in typ or '.zim' in href.lower()):
href=re.sub(r'\.meta4$','',urljoin('https://opds.library.kiwix.org/', href))
links.append((href, link.get('length') or ''))
if links:
if not size and links[0][1].isdigit(): size=int(links[0][1])
items.append((title, size, links[0][0]))
clean=lambda s:str(s).replace('\t',' ').replace('\n',' ')
with open(dst,'w',encoding='utf-8') as f:
for title,size,url in sorted(items,key=lambda x:x[0].casefold()):
f.write(f'{clean(title)}\t{size}\t{clean(url)}\n')
PY
printf '%s' "$tsv"
}
build_zim_list() {
if ((${#ZIM_ORDER[@]})); then return 0; fi
local catalog="" spec name reason slug best title bytes url ln lt bestlen
dlg --title "ZIM Archives" --infobox "Fetching the live Kiwix catalogue..." 5 50 || true
catalog="$(fetch_zim_catalogue 2>/dev/null)" || catalog=""
for spec in "${ZIM_WANTED[@]}"; do
name="${spec%%|*}"; reason="${spec#*|}"
slug="$(printf '%s' "$name" | tr -cs '[:alnum:]' '_')"
ZIM_ORDER+=("$slug"); ZIM_NAME[$slug]="$name"; ZIM_REASON[$slug]="$reason"
best=""; bestlen=99999; ln="${name,,}"
if [[ -n "$catalog" ]]; then
while IFS=$'\t' read -r title bytes url; do
lt="${title,,}"
if [[ "$lt" == "$ln" ]]; then best="$title"$'\t'"$bytes"$'\t'"$url"; break; fi
if [[ "$lt" == *"$ln"* ]] && ((${#title} < bestlen)); then best="$title"$'\t'"$bytes"$'\t'"$url"; bestlen=${#title}; fi
done < "$catalog"
fi
if [[ -n "$best" ]]; then
IFS=$'\t' read -r title bytes url <<<"$best"
ZIM_TITLE[$slug]="$title"; ZIM_BYTES[$slug]="$bytes"; ZIM_URL[$slug]="$url"; ZIM_MANUAL[$slug]=no
else
ZIM_TITLE[$slug]="$name"; ZIM_BYTES[$slug]=0; ZIM_URL[$slug]=""; ZIM_MANUAL[$slug]=yes
fi
done
}
dl_has() { [[ -n "${SEL_DL[$1]:-}" ]]; }
dl_state() { if dl_has "$1"; then echo on; else echo off; fi; }
dl_required() {
local t b=0 slug
for t in "${!SEL_DL[@]}"; do
case "$t" in
m_*) b=$((b + ${MAP_BYTES[$t]:-0})) ;;
z_*) slug="${t#z_}"; b=$((b + ${ZIM_BYTES[$slug]:-0})) ;;
esac
done
echo "$b"
}
apply_dl_flags() {
MAP_PHOTON=no; MAP_TILESERVER=no; MAP_SATELLITE=no; MAP_VECTOR=no; MAP_CONTOURS=no
if contains maps; then
dl_has m_photon && MAP_PHOTON=yes || true
dl_has m_tiles && MAP_TILESERVER=yes || true
dl_has m_sat && MAP_SATELLITE=yes || true
dl_has m_vec && MAP_VECTOR=yes || true
dl_has m_cont && MAP_CONTOURS=yes || true
if [[ "$MAP_SATELLITE" == yes || "$MAP_VECTOR" == yes || "$MAP_CONTOURS" == yes ]]; then MAP_TILESERVER=yes; fi
fi
}
step_downloads() {
local want_maps=no want_zims=no t slug line
contains maps && want_maps=yes || true
contains zims && want_zims=yes || true
if [[ -z "$DL_LOADED" ]]; then
while read -r line; do if [[ -n "$line" ]]; then SEL_DL[$line]=1; fi; done < "$DL_FILE"
DL_LOADED=1
fi
for t in "${!SEL_DL[@]}"; do
if [[ "$want_maps" == no && "$t" == m_* ]]; then unset 'SEL_DL[$t]'; fi
if [[ "$want_zims" == no && "$t" == z_* ]]; then unset 'SEL_DL[$t]'; fi
done
if [[ "$want_maps" == no && "$want_zims" == no ]]; then apply_dl_flags; return 10; fi
if [[ "$want_zims" == yes ]]; then build_zim_list; fi
local -a items=() sel=()
local selected req avail lines lh text mapref
lines="$(tlines)"; lh=$((lines - 12)); ((lh > 22)) && lh=22 || true; ((lh < 5)) && lh=5 || true
while true; do
items=()
if [[ "$want_maps" == yes ]]; then
items+=("hdr_maps" "================== MAPS ==================" off)
for t in m_photon m_tiles m_sat m_vec m_cont; do items+=("$t" "${MAP_LABEL[$t]}" "$(dl_state "$t")"); done
fi
if [[ "$want_zims" == yes ]]; then
items+=("hdr_zims" "============= ZIM ARCHIVES ===============" off)
for slug in "${ZIM_ORDER[@]}"; do
if [[ "${ZIM_MANUAL[$slug]}" == yes ]]; then
items+=("z_$slug" "${ZIM_NAME[$slug]} (size unknown, manual URL): ${ZIM_REASON[$slug]}" "$(dl_state "z_$slug")")
elif ((${ZIM_BYTES[$slug]} > 0)); then
items+=("z_$slug" "${ZIM_TITLE[$slug]} ($(zim_size_gb "${ZIM_BYTES[$slug]}")): ${ZIM_REASON[$slug]}" "$(dl_state "z_$slug")")
else
items+=("z_$slug" "${ZIM_TITLE[$slug]} (size unknown): ${ZIM_REASON[$slug]}" "$(dl_state "z_$slug")")
fi
done
fi
req="$(dl_required)"; avail="$(free_bytes "$DATA_ROOT")"
text="Currently selected: $(zim_size_gb "$req") Free space: $(zim_size_gb "$avail") (on $DATA_ROOT)\nThe total is recalculated when you press Next. Archives of unknown size are not counted."
selected="$(dlg --title "Downloads" --ok-label "Next" --cancel-label "$BACK" --separate-output \
--checklist "$text" $((lh + 8)) 120 "$lh" "${items[@]}" 3>&1 1>&2 2>&3)" || return 1
SEL_DL=()
mapfile -t sel <<<"$selected"
for t in "${sel[@]}"; do
if [[ "$t" == m_* || "$t" == z_* ]]; then SEL_DL[$t]=1; fi
done
if dl_has m_sat || dl_has m_vec || dl_has m_cont; then SEL_DL[m_tiles]=1; fi
req="$(dl_required)"; avail="$(free_bytes "$DATA_ROOT")"
if ((req > avail)); then
msg "Not enough disk space.\n\nSelected: $(zim_size_gb "$req")\nAvailable: $(zim_size_gb "$avail") (on $DATA_ROOT)\n\nDeselect something, or go back and pick another data root later."
continue
fi
if dlg --title "Downloads" --yes-label "Continue" --no-label "Change" \
--yesno "Total download size: $(zim_size_gb "$req")\nAvailable space: $(zim_size_gb "$avail") (on $DATA_ROOT)\n\nContinue with this selection?" 0 0; then
break
fi
done
printf '%s\n' "${!SEL_DL[@]}" > "$DL_FILE"
apply_dl_flags
return 0
}
# ---- Step 3: storage / system / registry ---------------------------------------------
step_global() {
local err
while true; do
form_run "Storage, system and registry" \
"Data root holds all Docker/application data.
The admin account below is entered once and reused for every
service that needs a first user (WireGuard, Bettercap, OpenWebRX+, ...).
The username defaults to the current user, who is added to the docker group.
Docker is always installed; images are pulled from $DOCKER_REGISTRY.
(Leave the registry password blank only if this host is already logged in.)" \
"DATA_ROOT|Data root (absolute path)|t" \
"OPSBOX_ADMIN_USERNAME|Admin username|t" \
"OPSBOX_ADMIN_EMAIL|Admin email|t" \
"OPSBOX_ADMIN_PASSWORD|Admin password|p" \
"APT_UPGRADE|Run apt upgrade (yes/no)|t" \
"DOCKER_USER|$DOCKER_REGISTRY username|t" \
"DOCKER_PASS|$DOCKER_REGISTRY password/token|p" || return 1
err=""
DATA_ROOT="${DATA_ROOT%/}"
[[ "$DATA_ROOT" == /* ]] || err+="Data root must be an absolute path.\n"
[[ -n "$OPSBOX_ADMIN_USERNAME" ]] || err+="An administrator username is required.\n"
[[ "$OPSBOX_ADMIN_EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]] || err+="Enter a valid administrator email address.\n"
[[ -n "$OPSBOX_ADMIN_PASSWORD" ]] || err+="An administrator password is required.\n"
APT_UPGRADE="$(yesno_norm "$APT_UPGRADE")" || err+="apt upgrade must be yes or no.\n"
[[ -n "$DOCKER_USER" ]] || err+="A $DOCKER_REGISTRY username is required.\n"
if [[ -z "$DOCKER_PASS" ]] && ! docker_logged_in; then err+="A $DOCKER_REGISTRY password/token is required.\n"; fi
[[ -z "$err" ]] && break
APT_UPGRADE="${APT_UPGRADE:-no}"
msg "$err"
done
OPSBOX_DATA_ROOT="$DATA_ROOT"
return 0
}
# ---- Step 4: network (Caddy + every service, one screen) -----------------------------
build_net_rows() {
NET_ROWS=()
net_add() { NET_ROWS+=("$1|$2|$3|$4|$5|$6|$7"); }
# key | label | default subdomain | default port | bind var ("-" = host service) | port var | needs host name when no Caddy
contains speedtest && net_add SPEEDTEST "LibreSpeed" speedtest 8010 LIBRESPEED_BIND LIBRESPEED_PORT no || true
contains maps && net_add MAPS "Cartomake (maps UI)" maps 8020 CARTOMAKE_BIND CARTOMAKE_PORT no || true
[[ "${MAP_TILESERVER:-no}" == yes ]] && net_add TILES "TileServer GL" tiles 8021 TILESERVER_BIND TILESERVER_PORT yes || true
[[ "${MAP_PHOTON:-no}" == yes ]] && net_add GEOCODE "Photon geocoder" geocode 8022 PHOTON_BIND PHOTON_PORT yes || true
if contains personal-cloud; then
net_add HARNESS "AI harness" home 8030 WEB_BIND HARNESS_PORT yes
net_add OFFICE "OnlyOffice" office 8031 WEB_BIND OFFICE_PORT yes
fi
contains sdr-tools && net_add SDR "SDR tools (OpenWebRX+)" sdr 8040 OPENWEBRX_BIND OPENWEBRX_PORT no || true
contains wireguard && net_add WGPORTAL "WireGuard Portal" vpn 8050 - WG_PORTAL_UI_PORT no || true
if contains pentest; then
net_add BETTERCAP "Bettercap UI" bettercap 8060 - BETTERCAP_UI_PORT no
net_add BETTERCAP_API "Bettercap API" api.bettercap 8061 - BETTERCAP_API_PORT no
fi
contains wireless-hat && net_add MESH "Meshtastic (web UI)" mesh 8070 - MESHTASTIC_PORT no || true
contains tak && net_add OPENTAK "TAK Server (web UI)" tak 8090 OTS_WEB_BIND OTS_WEB_PORT no || true
unset -f net_add
}
step_network() {
build_net_rows
local n=${#NET_ROWS[@]}
if ((n == 0)); then USE_CADDY=no; return 10; fi
local uc="${USE_CADDY:-yes}" dom="$OPSBOX_DOMAIN"
local -a net_sub=() net_port=() args=() vals=()
local i key label dsub dport bindv portv need sv lw=0 col y out err lines cols h fh w r
for ((i = 0; i < n; i++)); do
IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}"
sv="OPSBOX_SUB_$key"
net_sub[i]="${!sv:-$dsub}"
net_port[i]="${!portv:-$dport}"
if ((${#label} > lw)); then lw=${#label}; fi
done
((lw < 22)) && lw=22 || true
col=$((lw + 3))
lines="$(tlines)"; cols="$(tcols)"
h=$((n + 15)); ((h > lines)) && h=$lines || true
fh=$((h - 13)); ((fh < 4)) && fh=4 || true
w=$((col + 52)); ((w < 80)) && w=80 || true; ((w > cols)) && w=$cols || true
while true; do
args=("Use Caddy (yes/no):" 1 1 "$uc" 1 "$col" 6 6 0
"Base domain:" 2 1 "$dom" 2 "$col" 30 100 0)
for ((i = 0; i < n; i++)); do
IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}"
y=$((i + 4))
args+=("$label:" "$y" 1 "${net_sub[i]}" "$y" "$col" 24 63 0
"" "$y" "$((col + 26))" "${net_port[i]}" "$y" "$((col + 26))" 7 5 0)
done
out="$(dlg --title "Network" --ok-label "Next" --cancel-label "$BACK" \
--mixedform "yes = install Caddy: every service is served as https://<subdomain>.<domain> (internal TLS).
no = you already run a reverse proxy: services are published on the host ports below for it
to forward to; <subdomain>.<domain> is the public name used in links between services.
Columns: service | subdomain | host port
Reserved (cannot be used): 53, 80, 443, 2947, 8089, 8446, 51820" "$h" "$w" "$fh" "${args[@]}" 3>&1 1>&2 2>&3)" || return 1
mapfile -t vals <<<"$out"
uc="${vals[0]-}"; dom="${vals[1]-}"
for ((i = 0; i < n; i++)); do
net_sub[i]="${vals[2 + 2*i]-}"; net_port[i]="${vals[3 + 2*i]-}"
done
err=""
uc="$(yesno_norm "$uc")" || { err+="Caddy must be yes or no.\n"; uc="yes"; }
dom="${dom,,}"
valid_sub "$dom" || err+="Invalid base domain: '$dom'\n"
local -A seen_s=() seen_p=()
for ((i = 0; i < n; i++)); do
IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}"
net_sub[i]="${net_sub[i],,}"
valid_sub "${net_sub[i]}" || err+="$label: invalid subdomain '${net_sub[i]}'\n"
if valid_port "${net_port[i]}"; then
if r="$(reserved_port "$((10#${net_port[i]}))")"; then
err+="$label: port ${net_port[i]} is reserved for $r\n"
fi
else
err+="$label: invalid port '${net_port[i]}'\n"
fi
[[ -n "${seen_s[${net_sub[i]}]:-}" ]] && err+="$label: subdomain '${net_sub[i]}' is used twice\n" || true
[[ -n "${seen_p[${net_port[i]}]:-}" ]] && err+="$label: port '${net_port[i]}' is used twice\n" || true
seen_s[${net_sub[i]}]=1; seen_p[${net_port[i]}]=1
done
unset seen_s seen_p
[[ -z "$err" ]] && break
msg "$err"
done
USE_CADDY="$uc"; OPSBOX_DOMAIN="$dom"
for ((i = 0; i < n; i++)); do
IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}"
printf -v "OPSBOX_SUB_$key" '%s' "${net_sub[i]}"
printf -v "$portv" '%s' "$((10#${net_port[i]}))"
if [[ "$bindv" != "-" ]]; then
if [[ "$USE_CADDY" == yes ]]; then
printf -v "$bindv" '%s' "127.0.0.1"
printf -v "OPSBOX_HOST_$key" '%s' ""
else
printf -v "$bindv" '%s' "0.0.0.0"
if [[ "$need" == yes ]]; then printf -v "OPSBOX_HOST_$key" '%s' "${net_sub[i]}.$OPSBOX_DOMAIN"
else printf -v "OPSBOX_HOST_$key" '%s' ""; fi
fi
fi
done
return 0
}
# ---- Step 5: per-service configuration screens ---------------------------------------
# Services that need a first account all take it from the shared OPSBOX_ADMIN_* values.
cfg_bettercap() {
BETTERCAP_USER="$OPSBOX_ADMIN_USERNAME"
BETTERCAP_PASSWORD="$OPSBOX_ADMIN_PASSWORD"
if [[ "$USE_CADDY" == yes ]]; then
BETTERCAP_UI_ADDR=""; BETTERCAP_ALLOW_ORIGIN=""
else
BETTERCAP_UI_ADDR="${BETTERCAP_UI_ADDR:-0.0.0.0}"
BETTERCAP_ALLOW_ORIGIN="${BETTERCAP_ALLOW_ORIGIN:-https://${OPSBOX_SUB_BETTERCAP:-bettercap}.$OPSBOX_DOMAIN}"
fi
}
# No form: the shared admin account and the UI port (Network step) are all it needs.
cfg_wireguard() {
WG_PORTAL_ADMIN_USER="$OPSBOX_ADMIN_EMAIL"
WG_PORTAL_ADMIN_PASSWORD="$OPSBOX_ADMIN_PASSWORD"
WG_PORTAL_UI_PORT="${WG_PORTAL_UI_PORT:-8050}"
WG_PORTAL_EXTERNAL_URL="https://${OPSBOX_SUB_WGPORTAL:-vpn}.$OPSBOX_DOMAIN"
WG_PORTAL_WEB_SESSION_SECRET="${WG_PORTAL_WEB_SESSION_SECRET:-$(openssl rand -hex 32)}"
WG_PORTAL_WEB_CSRF_SECRET="${WG_PORTAL_WEB_CSRF_SECRET:-$(openssl rand -hex 32)}"
return 0
}
cfg_openwebrx() {
OPENWEBRX_ADMIN_USER="$OPSBOX_ADMIN_USERNAME"
OPENWEBRX_ADMIN_PASSWORD="$OPSBOX_ADMIN_PASSWORD"
OPENWEBRX_IMAGE="${OPENWEBRX_IMAGE:-slechev/openwebrxplus-softmbe:latest}"
form_run "OpenWebRX+" "Uses the shared OpsBox administrator username and password." \
"OPENWEBRX_IMAGE|Docker image|t" || return 1
[[ -n "$OPENWEBRX_IMAGE" ]] || { msg "Docker image is required."; return 1; }
}
cfg_fallback_ap() {
local err iface
if [[ -f /etc/fallback-ap.conf ]]; then
# shellcheck disable=SC1091
source /etc/fallback-ap.conf || true
# fallback-ap itself rewrites this file with SAVED_* names; map them back.
FALLBACK_AP_SSID="${FALLBACK_AP_SSID:-${SAVED_SSID:-}}"
FALLBACK_AP_PASSWORD="${FALLBACK_AP_PASSWORD:-${SAVED_PASSWORD:-}}"
FALLBACK_AP_IFACE="${FALLBACK_AP_IFACE:-${SAVED_IFACE:-}}"
FALLBACK_AP_CIDR="${FALLBACK_AP_CIDR:-${SAVED_CIDR:-}}"
FALLBACK_AP_DHCP_START_OCTET="${FALLBACK_AP_DHCP_START_OCTET:-${SAVED_DHCP_START_OCTET:-}}"
FALLBACK_AP_DHCP_END_OCTET="${FALLBACK_AP_DHCP_END_OCTET:-${SAVED_DHCP_END_OCTET:-}}"
FALLBACK_AP_MONITOR_IFACE="${FALLBACK_AP_MONITOR_IFACE-${SAVED_MONITOR_IFACE-}}"
FALLBACK_AP_IGNORE_IFACE="${FALLBACK_AP_IGNORE_IFACE-${SAVED_IGNORE_IFACE-}}"
FALLBACK_AP_CHECK_MODE="${FALLBACK_AP_CHECK_MODE:-${SAVED_CHECK_MODE:-}}"
FALLBACK_AP_CHECK_TARGETS="${FALLBACK_AP_CHECK_TARGETS:-${SAVED_CHECK_TARGETS:-}}"
fi
iface="$(iw dev 2>/dev/null | awk '$1=="Interface"{print $2;exit}' || true)"
FALLBACK_AP_SSID="${FALLBACK_AP_SSID:-$(hostname)}"
FALLBACK_AP_PASSWORD="${FALLBACK_AP_PASSWORD:-}"
FALLBACK_AP_IFACE="${FALLBACK_AP_IFACE:-${iface:-wlan0}}"
FALLBACK_AP_CIDR="${FALLBACK_AP_CIDR:-10.10.10.1/24}"
FALLBACK_AP_DHCP_START_OCTET="${FALLBACK_AP_DHCP_START_OCTET:-100}"
FALLBACK_AP_DHCP_END_OCTET="${FALLBACK_AP_DHCP_END_OCTET:-250}"
FALLBACK_AP_MONITOR_IFACE="${FALLBACK_AP_MONITOR_IFACE:-}"
FALLBACK_AP_IGNORE_IFACE="${FALLBACK_AP_IGNORE_IFACE:-}"
FALLBACK_AP_CHECK_MODE="${FALLBACK_AP_CHECK_MODE:-link}"
FALLBACK_AP_CHECK_TARGETS="${FALLBACK_AP_CHECK_TARGETS:-1.1.1.1 8.8.8.8}"
while true; do
form_run "Fallback access point" "Brought up automatically when the monitored uplink goes away.\nCheck mode: 'link' = link state, 'internet' = ping the targets." \
"FALLBACK_AP_SSID|Wi-Fi SSID|t" \
"FALLBACK_AP_PASSWORD|Wi-Fi password|p" \
"FALLBACK_AP_IFACE|Wireless interface|t" \
"FALLBACK_AP_CIDR|AP address/CIDR|t" \
"FALLBACK_AP_DHCP_START_OCTET|DHCP start octet|t" \
"FALLBACK_AP_DHCP_END_OCTET|DHCP end octet|t" \
"FALLBACK_AP_MONITOR_IFACE|Monitor iface (blank = all)|t" \
"FALLBACK_AP_IGNORE_IFACE|Ignore iface (blank = none)|t" \
"FALLBACK_AP_CHECK_MODE|Check mode (link/internet)|t" \
"FALLBACK_AP_CHECK_TARGETS|Internet check targets|t" || return 1
err=""
[[ -n "$FALLBACK_AP_SSID" ]] || err+="SSID is required.\n"
[[ -n "$FALLBACK_AP_IFACE" ]] || err+="Wireless interface is required.\n"
[[ "$FALLBACK_AP_CIDR" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$ ]] || err+="AP address must look like 10.10.10.1/24.\n"
[[ "$FALLBACK_AP_DHCP_START_OCTET" =~ ^[0-9]+$ && "$FALLBACK_AP_DHCP_END_OCTET" =~ ^[0-9]+$ ]] || err+="DHCP octets must be numbers.\n"
[[ "$FALLBACK_AP_CHECK_MODE" == link || "$FALLBACK_AP_CHECK_MODE" == internet ]] || err+="Check mode must be 'link' or 'internet'.\n"
[[ -z "$err" ]] && break
msg "$err"
done
}
cfg_ai() {
local err
AI_DIR="${AI_DIR:-$DATA_ROOT/ai}"
AI_REPO="${AI_REPO:-litert-community/gemma-4-E2B-it-litert-lm}"
AI_IMPORT="${AI_IMPORT:-no}"
while true; do
form_run "Local AI (LiteRT)" "Model downloads can be several GB." \
"AI_DIR|Install directory|t" \
"AI_REPO|Hugging Face model repository|t" \
"AI_IMPORT|Download model now (yes/no)|t" || return 1
err=""
[[ "$AI_DIR" == /* ]] || err+="Install directory must be absolute.\n"
[[ -n "$AI_REPO" ]] || err+="Model repository is required.\n"
AI_IMPORT="$(yesno_norm "$AI_IMPORT")" || { err+="Download must be yes or no.\n"; AI_IMPORT=no; }
[[ -z "$err" ]] && break
msg "$err"
done
}
cfg_hat() {
local out t
HAT_GPS="${HAT_GPS:-yes}"; HAT_LORA="${HAT_LORA:-yes}"; HAT_RTC="${HAT_RTC:-no}"; HAT_PPS="${HAT_PPS:-no}"
local -a sel=()
out="$(dlg --title "Wireless HAT" --ok-label "Next" --cancel-label "$BACK" --separate-output --checklist \
"Hardware to enable (a reboot is required afterwards).\nGPS is served by a shared gpsd; LoRa installs and configures Meshtastic." 17 92 4 \
gps "GPS UART + shared gpsd (also removes the Linux serial console)" "$([[ $HAT_GPS == yes ]] && echo on || echo off)" \
lora "LoRa SX1262 on SPI1 + Meshtastic (spi1-1cs overlay)" "$([[ $HAT_LORA == yes ]] && echo on || echo off)" \
rtc "HAT PCF85063A RTC (skip if a Pi/PiSugar RTC is in use)" "$([[ $HAT_RTC == yes ]] && echo on || echo off)" \
pps "GPS PPS input on GPIO6 (needs HAT switch SW1-2 ON)" "$([[ $HAT_PPS == yes ]] && echo on || echo off)" \
3>&1 1>&2 2>&3)" || return 1
HAT_GPS=no; HAT_LORA=no; HAT_RTC=no; HAT_PPS=no
mapfile -t sel <<<"$out"
for t in "${sel[@]}"; do
case "$t" in gps) HAT_GPS=yes;; lora) HAT_LORA=yes;; rtc) HAT_RTC=yes;; pps) HAT_PPS=yes;; esac
done
}
cfg_maps() {
local err
local -a specs=()
[[ "$MAP_SATELLITE" == yes ]] && specs+=("MAP_URL_SATELLITE|MapTiler Satellite URL|t") || true
[[ "$MAP_VECTOR" == yes ]] && specs+=("MAP_URL_VECTOR|MapTiler Vector URL|t") || true
[[ "$MAP_CONTOURS" == yes ]] && specs+=("MAP_URL_CONTOURS|Contours URL (your host)|t") || true
while true; do
form_run "Map dataset downloads" "Paste the real download URL for each tile set.\nLeave one blank to skip that dataset." "${specs[@]}" || return 1
err=""
[[ -z "${MAP_URL_SATELLITE:-}" ]] || valid_url "$MAP_URL_SATELLITE" || err+="Satellite URL must start with http(s)://\n"
[[ -z "${MAP_URL_VECTOR:-}" ]] || valid_url "$MAP_URL_VECTOR" || err+="Vector URL must start with http(s)://\n"
[[ -z "${MAP_URL_CONTOURS:-}" ]] || valid_url "$MAP_URL_CONTOURS" || err+="Contours URL must start with http(s)://\n"
[[ -z "$err" ]] && break
msg "$err"
done
}
cfg_zims() {
local err slug v
local -a specs=()
for slug in "${ZIM_ORDER[@]}"; do
if dl_has "z_$slug" && [[ "${ZIM_MANUAL[$slug]}" == yes ]]; then specs+=("MZIM_$slug|${ZIM_NAME[$slug]}|t"); fi
done
while true; do
form_run "ZIM archives - manual URLs" "These archives were not found in the live Kiwix catalogue.\nPaste the official .zim URL, or leave blank to skip." "${specs[@]}" || return 1
err=""
for slug in "${ZIM_ORDER[@]}"; do
v="MZIM_$slug"
if [[ -n "${!v:-}" ]] && ! valid_url "${!v}"; then err+="${ZIM_NAME[$slug]}: URL must start with http(s)://\n"; fi
done
[[ -z "$err" ]] && break
msg "$err"
done
}
step_services() {
local -a list=() n
local slug
contains pentest && list+=(cfg_bettercap) || true
contains sdr-tools && list+=(cfg_openwebrx) || true
contains wireguard && list+=(cfg_wireguard) || true
contains fallback-ap && list+=(cfg_fallback_ap) || true
contains ai && list+=(cfg_ai) || true
contains wireless-hat && list+=(cfg_hat) || true
if [[ "$MAP_SATELLITE" == yes || "$MAP_VECTOR" == yes || "$MAP_CONTOURS" == yes ]]; then list+=(cfg_maps); fi
if contains zims; then
for slug in "${ZIM_ORDER[@]}"; do
if dl_has "z_$slug" && [[ "${ZIM_MANUAL[$slug]}" == yes ]]; then list+=(cfg_zims); break; fi
done
fi
((${#list[@]})) || return 10
run_steps "${list[@]}"
}
# ---- Step 6: summary -----------------------------------------------------------------
sum_add() { SUM+="$1"$'\n'; }
step_summary() {
local x key label dsub dport bindv portv need sv slug req avail i
SUM=""
sum_add "COMPONENTS"
sum_add " * Docker Engine + $DOCKER_REGISTRY registry login (always)"
for x in "${SELECTED[@]}"; do sum_add " * ${COMP_LABEL[$x]:-$x}"; done
sum_add ""
sum_add "SYSTEM"
sum_add " Data root: $DATA_ROOT"
sum_add " Docker group user: $ADMIN_USER"
sum_add " Shared admin: $OPSBOX_ADMIN_USERNAME <$OPSBOX_ADMIN_EMAIL> (used by every service below)"
sum_add " apt upgrade: $APT_UPGRADE"
sum_add " Registry login: $DOCKER_USER @ $DOCKER_REGISTRY"
if ((${#NET_ROWS[@]})); then
sum_add ""
if [[ "$USE_CADDY" == yes ]]; then sum_add "NETWORK: Caddy with internal HTTPS, domain *.$OPSBOX_DOMAIN"
else sum_add "NETWORK: your own reverse proxy (services published on host ports)"; fi
for ((i = 0; i < ${#NET_ROWS[@]}; i++)); do
IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}"
sv="OPSBOX_SUB_$key"
if [[ "$USE_CADDY" == yes ]]; then
if [[ "$key" == WGPORTAL ]]; then sum_add " $(printf '%-24s' "$label") https://${!sv}.$OPSBOX_DOMAIN (container:8888)"
elif [[ "$bindv" == "-" ]]; then sum_add " $(printf '%-24s' "$label") https://${!sv}.$OPSBOX_DOMAIN (host service :${!portv})"
else sum_add " $(printf '%-24s' "$label") https://${!sv}.$OPSBOX_DOMAIN (127.0.0.1:${!portv})"; fi
else sum_add " $(printf '%-24s' "$label") ${!sv}.$OPSBOX_DOMAIN (host port ${!portv})"; fi
done
fi
# Fixed ports other than the web UIs above.
local fixed=""
[[ "$USE_CADDY" == yes ]] && fixed+=" 80, 443/tcp Caddy"$'\n' || true
contains tak && fixed+=" 8089, 8446/tcp TAK streaming / certificate enrollment"$'\n' || true
contains wireguard && fixed+=" 51820/udp WireGuard VPN clients"$'\n' || true
if contains wireless-hat && [[ "${HAT_GPS:-no}" == yes ]]; then
fixed+=" 2947/tcp gpsd (localhost + Docker gateway only)"$'\n'
fi
if [[ "$USE_CADDY" == yes ]] && { contains fallback-ap || contains wireguard; }; then
fixed+=" 53/tcp+udp DNS for *.$OPSBOX_DOMAIN"$'\n'
fi
if [[ -n "$fixed" ]]; then
sum_add ""
sum_add "FIXED PORTS (not configurable)"
SUM+="$fixed"
fi
if [[ "$USE_CADDY" == yes ]] && { contains fallback-ap || contains wireguard; }; then
sum_add ""
sum_add "DNS: *.$OPSBOX_DOMAIN resolves to this machine for connected clients"
contains fallback-ap && sum_add " Fallback AP clients: via NetworkManager's dnsmasq -> ${FALLBACK_AP_CIDR%%/*}" || true
contains wireguard && sum_add " WireGuard clients: via opsbox-dns on the Docker gateway (split DNS; set it in WG Portal)" || true
fi
if ((${#SEL_DL[@]})); then
sum_add ""
sum_add "DOWNLOADS"
for x in m_photon m_tiles m_sat m_vec m_cont; do dl_has "$x" && sum_add " Map: ${MAP_LABEL[$x]}" || true; done
for slug in "${ZIM_ORDER[@]}"; do
if dl_has "z_$slug"; then
if [[ "${ZIM_MANUAL[$slug]}" == yes ]]; then sum_add " ZIM: ${ZIM_NAME[$slug]} (manual URL)"
else sum_add " ZIM: ${ZIM_TITLE[$slug]} ($(zim_size_gb "${ZIM_BYTES[$slug]}"))"; fi
fi
done
req="$(dl_required)"; avail="$(free_bytes "$DATA_ROOT")"
sum_add " Total: $(zim_size_gb "$req") Available on $DATA_ROOT: $(zim_size_gb "$avail")"
fi
sum_add ""
sum_add "SERVICE SETTINGS"
contains pentest && sum_add " Bettercap: user '$BETTERCAP_USER'${BETTERCAP_UI_ADDR:+, listen $BETTERCAP_UI_ADDR}" || true
contains sdr-tools && sum_add " OpenWebRX+: admin '$OPENWEBRX_ADMIN_USER'" || true
contains fallback-ap && sum_add " Fallback AP: SSID '$FALLBACK_AP_SSID' on $FALLBACK_AP_IFACE ($FALLBACK_AP_CIDR), check=$FALLBACK_AP_CHECK_MODE" || true
contains ai && sum_add " Local AI: $AI_REPO in $AI_DIR (download now: $AI_IMPORT)" || true
contains wireless-hat && sum_add " Wireless HAT: GPS=$HAT_GPS LoRa=$HAT_LORA RTC=$HAT_RTC PPS=$HAT_PPS (Meshtastic Beta repo)" || true
contains wireguard && sum_add " WireGuard: WireGuard Portal admin '$WG_PORTAL_ADMIN_USER'" || true
if contains tak; then
sum_add " OpenTAKServer: Upstream creates its own initial administrator; change its default password on first login."
fi
if contains wireless-hat && [[ "${HAT_GPS:-no}" == yes ]]; then
sum_add ""
sum_add "NOTE: gpsd owns the GPS UART. Clients connect to gpsd (port 2947); software that"
sum_add " needs a serial device gets its own PTY: /run/gps/<name> (Meshtastic: /run/gps/meshtastic)."
fi
sum_add ""
sum_add "A reboot is recommended afterwards if hardware overlays or kernel modules change."
req="$(dl_required)"; avail="$(free_bytes "$DATA_ROOT")"
if ((req > avail)); then
msg "The selected downloads need $(zim_size_gb "$req") but only $(zim_size_gb "$avail") is free on $DATA_ROOT.\n\nGo back and pick a different data root or fewer downloads."
return 1
fi
printf '%s' "$SUM" > "$TMP_DIR/summary.txt"
dlg --title "Review - scroll with arrow keys" --exit-label "Continue" --textbox "$TMP_DIR/summary.txt" 0 0 || true
ask_yes "Begin installation?\n\nExisting data is preserved; a failing component will not stop the others." || return 1
return 0
}
wizard() {
run_steps step_components step_downloads step_global step_network step_services step_summary || exit 0
}
persist_config() {
local i key label dsub dport bindv portv need
save_env OPSBOX_DATA_ROOT OPSBOX_ADMIN_USER OPSBOX_DOMAIN USE_CADDY
DOCKER_REGISTRY_USER="$DOCKER_USER"; OPSBOX_ADMIN_USER="$ADMIN_USER"
save_env OPSBOX_ADMIN_USER DOCKER_REGISTRY_USER
save_env OPSBOX_ADMIN_USERNAME OPSBOX_ADMIN_EMAIL OPSBOX_ADMIN_PASSWORD
for ((i = 0; i < ${#NET_ROWS[@]}; i++)); do
IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}"
save_env "OPSBOX_SUB_$key" "$portv"
if [[ "$bindv" != "-" ]]; then save_env "OPSBOX_HOST_$key" "$bindv"; fi
done
if contains pentest; then
save_env BETTERCAP_USER BETTERCAP_PASSWORD BETTERCAP_UI_ADDR BETTERCAP_UI_PORT BETTERCAP_API_PORT BETTERCAP_ALLOW_ORIGIN
fi
if contains sdr-tools; then
OPENWEBRX_IMAGE="${OPENWEBRX_IMAGE:-slechev/openwebrxplus-softmbe:latest}"
save_env OPENWEBRX_ADMIN_USER OPENWEBRX_ADMIN_PASSWORD OPENWEBRX_IMAGE
fi
if contains wireguard; then
WG_PORTAL_EXTERNAL_URL="https://${OPSBOX_SUB_WGPORTAL:-vpn}.$OPSBOX_DOMAIN"
WG_PORTAL_WEB_SESSION_SECRET="${WG_PORTAL_WEB_SESSION_SECRET:-$(openssl rand -hex 32)}"
WG_PORTAL_WEB_CSRF_SECRET="${WG_PORTAL_WEB_CSRF_SECRET:-$(openssl rand -hex 32)}"
save_env WG_PORTAL_ADMIN_USER WG_PORTAL_ADMIN_PASSWORD WG_PORTAL_UI_PORT WG_PORTAL_BIND
save_env WG_PORTAL_EXTERNAL_URL WG_PORTAL_WEB_SESSION_SECRET WG_PORTAL_WEB_CSRF_SECRET
fi
save_env MAP_PHOTON MAP_TILESERVER MAP_SATELLITE MAP_VECTOR MAP_CONTOURS
if contains personal-cloud; then
OFFICE_JWT_SECRET="${OFFICE_JWT_SECRET:-$(openssl rand -hex 32)}"
save_env OFFICE_JWT_SECRET
fi
if contains ai; then save_env AI_DIR AI_REPO; fi
if contains wireless-hat; then save_env HAT_GPS HAT_LORA HAT_RTC HAT_PPS; fi
}
# ======================================================================================
# INSTALLERS
# ======================================================================================
install_tools() { apt_install btop jq tmux; }
install_theme() {
local motd="/etc/motd" marker_start="# >>> OPSBOX BANNER >>>" marker_end="# <<< OPSBOX BANNER <<<"
local tmp="$TMP_DIR/motd" name uid home shell
# Clean the old static banner out of /etc/motd if present
if [ -f "$motd" ]; then
awk -v s="$marker_start" -v e="$marker_end" 'BEGIN{skip=0} $0==s{skip=1;next} $0==e{skip=0;next} !skip{print}' "$motd" > "$tmp"
cp -a "$motd" "$motd.opsbox-backup.$(date +%s)"
install -m 0644 "$tmp" "$motd"
fi
mkdir -p "$THEME_DIR"
rm -f /etc/motd /etc/update-motd.d/*
# ------------------------------------------------------------------
# Disable sshd's own "Last login:" line (our banner shows it instead)
# ------------------------------------------------------------------
if [ -d /etc/ssh ]; then
mkdir -p /etc/ssh/sshd_config.d
echo 'PrintLastLog no' > /etc/ssh/sshd_config.d/00-opsbox.conf
if sshd -t 2>/dev/null; then
systemctl reload ssh 2>/dev/null || systemctl reload sshd 2>/dev/null || true
else
rm -f /etc/ssh/sshd_config.d/00-opsbox.conf
log "sshd config test failed; left PrintLastLog unchanged."
fi
fi
cat > /usr/local/sbin/opsbox-updates <<'UPD'
#!/bin/sh
out=/var/cache/opsbox/updates
mkdir -p "${out%/*}"
n=0; s=0
if command -v apt-get >/dev/null 2>&1; then
list=$(apt-get -s -o Debug::NoLocking=1 upgrade 2>/dev/null | grep '^Inst ')
n=$(printf '%s\n' "$list" | grep -c .)
s=$(printf '%s\n' "$list" | grep -ci security)
elif command -v dnf >/dev/null 2>&1; then
n=$(dnf -q check-update 2>/dev/null | awk 'NF==3' | wc -l)
s=$(dnf -q updateinfo list security 2>/dev/null | awk 'NF==3' | wc -l)
fi
echo "$n $s" > "$out.tmp" && mv "$out.tmp" "$out" && chmod 0644 "$out"
UPD
chmod 0755 /usr/local/sbin/opsbox-updates
if command -v apt-get >/dev/null 2>&1; then
cat > /etc/apt/apt.conf.d/99opsbox-updates <<'APTHOOK'
APT::Update::Post-Invoke-Success { "/usr/local/sbin/opsbox-updates >/dev/null 2>&1 || true"; };
DPkg::Post-Invoke { "/usr/local/sbin/opsbox-updates >/dev/null 2>&1 || true"; };
APTHOOK
fi
/usr/local/sbin/opsbox-updates || true
cat > "$THEME_DIR/theme.sh" <<'THEME'
# OpsBox login banner + prompt.
[ -n "${BASH_VERSION:-}" ] || return 0
case $- in *i*) ;; *) return 0 ;; esac
__opsbox_rep() {
local n=$1 c=$2 s
[ "$n" -gt 0 ] || return 0
printf -v s '%*s' "$n" ''
printf '%s' "${s// /$c}"
}
__opsbox_row() {
printf '| %-*s |\n' "$((W - 4))" "$(printf '%s' "$1" | cut -c1-$((W - 4)))"
}
__opsbox_ifaces() {
local p n
for p in /sys/class/net/*; do
n=${p##*/}
case $n in
lo|docker*|br-*|veth*|virbr*|bond*|dummy*|ifb*|sit*|tunl*|ip6tnl*|gre*|erspan*) continue ;;
esac
# WireGuard is reported in the VPN row instead.
if grep -qx 'DEVTYPE=wireguard' "$p/uevent" 2>/dev/null; then continue; fi
if [ -e "$p/device" ] || [ -d "$p/wireless" ]; then
printf '%s\n' "$n"
else
case $n in tun*|tailscale*) printf '%s\n' "$n" ;; esac
fi
done
}
__opsbox_vpn() {
local p n ip ts age hs now
now=$(date +%s)
for p in /sys/class/net/*; do
n=${p##*/}
grep -qx 'DEVTYPE=wireguard' "$p/uevent" 2>/dev/null || continue
ip=$(ip -4 -o addr show dev "$n" 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n1)
[ -n "$ip" ] && ip="// $ip"
if hs=$(wg show "$n" latest-handshakes 2>/dev/null); then
ts=$(printf '%s\n' "$hs" | awk '$2>m{m=$2} END{print m+0}')
if [ "$ts" -eq 0 ]; then
printf '%-10s %-14s %s\n' "$n" "NO HANDSHAKE" "$ip"
else
age=$((now - ts))
if [ "$age" -le 180 ]; then
printf '%-10s %-14s %s (hs %ss)\n' "$n" "CONNECTED" "$ip" "$age"
else
printf '%-10s %-14s %s (hs %sm)\n' "$n" "STALE" "$ip" "$((age / 60))"
fi
fi
else
printf '%-10s %-14s %s\n' "$n" "UP" "$ip"
fi
done
}
__opsbox_banner() {
local W=68 user host now src prev lastf ifc ip status row
local any=0 os kern upd n s reboot line
user=$(id -un 2>/dev/null || echo "${USER:-unknown}")
host=$(hostname -s 2>/dev/null || hostname)
host="${host:0:32}"
now=$(date '+%a %d %b %H:%M')
if [ -n "${SSH_CONNECTION:-}" ]; then
src="ssh ${SSH_CONNECTION%% *}"
else
src=$(tty 2>/dev/null || true)
case $src in
""|"not a tty") src="local" ;;
*) src=${src#/dev/} ;;
esac
fi
lastf="${HOME:-/tmp}/.opsbox_last_login"
prev="first session"
[ -r "$lastf" ] && prev=$(head -n1 "$lastf" 2>/dev/null)
printf '%s (%s)\n' "$now" "$src" > "$lastf" 2>/dev/null || true
os=$(. /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-$NAME}")
[ -n "$os" ] || os=$(uname -s)
kern=$(uname -r)
upd="UNKNOWN"
if [ -r /var/cache/opsbox/updates ]; then
read -r n s < /var/cache/opsbox/updates
if [ "${n:-0}" -eq 0 ]; then
upd="up to date"
elif [ "${s:-0}" -gt 0 ]; then
upd="$n pending ($s security)"
else
upd="$n pending"
fi
fi
[ -e /run/reboot-required ] && upd="$upd // REBOOT REQUIRED"
# Header.
printf '+==[ %s ]' "$host"
printf '%s+\n' "$(__opsbox_rep "$((W - ${#host} - 8))" '=')"
__opsbox_row "$(printf 'ACCESS: %s // LAST: %s' "${user^^}" "$prev")"
__opsbox_row "$(printf 'OS: %s // %s' "$os" "$kern")"
__opsbox_row "$(printf 'UPDATES: %s' "$upd")"
printf '|%s|\n' "$(__opsbox_rep "$((W - 2))" '-')"
# Network interfaces.
for ifc in $(__opsbox_ifaces); do
any=1
ip=$(ip -4 -o addr show dev "$ifc" scope global 2>/dev/null |
awk '{print $4}' | cut -d/ -f1 | head -n1)
if [ -n "$ip" ]; then
status="CONNECTED"
ip="// $ip"
else
status="DISCONNECTED"
ip=""
fi
row=$(printf '%-10s %-14s %s' "$ifc" "$status" "$ip")
__opsbox_row "$row"
done
# VPN interfaces (WireGuard), same column layout.
while IFS= read -r line; do
[ -n "$line" ] || continue
any=1
__opsbox_row "$line"
done < <(__opsbox_vpn)
[ "$any" = 1 ] || __opsbox_row "NO NETWORK ADAPTERS FOUND"
# Footer.
printf '+%s+\n' "$(__opsbox_rep "$((W - 2))" '=')"
}
__opsbox_prompt() {
local c='\[\e[36m\]' u='\[\e[33m\]' d='\[\e[97m\]' r='\[\e[m\]'
if [ "$(id -u)" -eq 0 ]; then c='\[\e[91m\]'; fi
PS1="${c}╭──(${u}\u${c}@${u}\h${c})-[${d}\w${c}]${r}\n${c}╰─${r}\\$ "
}
if [ -z "${OPSBOX_BANNER_SHOWN:-}" ]; then
export OPSBOX_BANNER_SHOWN=1
__opsbox_banner
fi
__opsbox_prompt
unset -f __opsbox_banner __opsbox_prompt __opsbox_ifaces __opsbox_rep __opsbox_row __opsbox_vpn
THEME
chmod 0755 "$THEME_DIR"
chmod 0644 "$THEME_DIR/theme.sh"
# Login shells.
cat > /etc/profile.d/opsbox.sh <<'PROFILE'
if [ -r /usr/local/share/opsbox/theme.sh ]; then . /usr/local/share/opsbox/theme.sh; fi
PROFILE
chmod 0644 /etc/profile.d/opsbox.sh
# Hook bashrc files.
while IFS=: read -r name _ uid _ _ home shell; do
if [[ "$name" == root || "$name" == "$ADMIN_USER" ]] || ((uid >= 1000 && uid < 60000)); then
[[ "$shell" == *nologin || "$shell" == */false ]] && continue
[[ -d "$home" ]] && hook_bashrc "$home/.bashrc"
fi
done < <(getent passwd)
hook_bashrc /root/.bashrc
hook_bashrc /etc/skel/.bashrc
log "Theme installed. Open a new shell (or run: source ~/.bashrc) to see it."
}
hook_bashrc() {
local rc="$1" new=no
[[ -d "$(dirname "$rc")" ]] || return 0
[[ -e "$rc" ]] || new=yes
touch "$rc"
sed -i '\|# >>> opsbox theme >>>|,\|# <<< opsbox theme <<<|d' "$rc"
cat >> "$rc" <<'HOOK'
# >>> opsbox theme >>>
if [ -r /usr/local/share/opsbox/theme.sh ]; then . /usr/local/share/opsbox/theme.sh; fi
# <<< opsbox theme <<<
HOOK
if [[ "$new" == yes ]]; then chown --reference="$(dirname "$rc")" "$rc" || true; fi
return 0
}
install_wireguard() {
local url="${WG_PORTAL_EXTERNAL_URL:-https://${OPSBOX_SUB_WGPORTAL:-vpn}.$OPSBOX_DOMAIN}"
WG_PORTAL_BIND="${WG_PORTAL_BIND:-$([[ "$USE_CADDY" == yes ]] && echo 127.0.0.1 || echo 0.0.0.0)}"
mkdir -p "$DATA_ROOT/wg-portal/data" "$DATA_ROOT/wg-portal/config"
chmod 0700 "$DATA_ROOT/wg-portal" "$DATA_ROOT/wg-portal/config" "$DATA_ROOT/wg-portal/data"
save_env WG_PORTAL_BIND
compose_stack wg-portal docker/wireguard.yml "$ENV_FILE" || return 1
log "WireGuard Portal is running."
if [[ "$USE_CADDY" == yes ]]; then
log "Web UI: $url (Caddy internal HTTPS)"
else
log "Web UI: http://$(hostname -I | awk '{print $1}'):${WG_PORTAL_UI_PORT:-8050}"
fi
log "WireGuard UDP: port 51820"
log "Initial administrator: $WG_PORTAL_ADMIN_USER"
}
install_fallback_ap() {
apt_install curl || return 1
local conf=/etc/fallback-ap.conf
cat > "$conf" <<CONF
FALLBACK_AP_SSID=$(printf '%q' "$FALLBACK_AP_SSID")
FALLBACK_AP_PASSWORD=$(printf '%q' "$FALLBACK_AP_PASSWORD")
FALLBACK_AP_IFACE=$(printf '%q' "$FALLBACK_AP_IFACE")
FALLBACK_AP_CIDR=$(printf '%q' "$FALLBACK_AP_CIDR")
FALLBACK_AP_DHCP_START_OCTET=$(printf '%q' "$FALLBACK_AP_DHCP_START_OCTET")
FALLBACK_AP_DHCP_END_OCTET=$(printf '%q' "$FALLBACK_AP_DHCP_END_OCTET")
FALLBACK_AP_MONITOR_IFACE=$(printf '%q' "$FALLBACK_AP_MONITOR_IFACE")
FALLBACK_AP_IGNORE_IFACE=$(printf '%q' "$FALLBACK_AP_IGNORE_IFACE")
FALLBACK_AP_CHECK_MODE=$(printf '%q' "$FALLBACK_AP_CHECK_MODE")
FALLBACK_AP_CHECK_TARGETS=$(printf '%q' "$FALLBACK_AP_CHECK_TARGETS")
CONF
chmod 0600 "$conf"
export FALLBACK_AP_SSID FALLBACK_AP_PASSWORD FALLBACK_AP_IFACE FALLBACK_AP_CIDR
export FALLBACK_AP_DHCP_START_OCTET FALLBACK_AP_DHCP_END_OCTET FALLBACK_AP_MONITOR_IFACE
export FALLBACK_AP_IGNORE_IFACE FALLBACK_AP_CHECK_MODE FALLBACK_AP_CHECK_TARGETS
curl -fsSL https://git.zakscode.com/ztimson/fallback-ap/raw/branch/master/install.sh -o "$TMP_DIR/fallback-ap.sh" || return 1
bash "$TMP_DIR/fallback-ap.sh"
}
force_headless_display() {
local res="${VNC_RESOLUTION:-1920x1080}" cmd=/boot/firmware/cmdline.txt
[[ -f "$cmd" ]] || cmd=/boot/cmdline.txt
if [[ ! -f "$cmd" ]]; then
warn "No cmdline.txt found; could not force a virtual display."
return 0
fi
if grep -q 'video=HDMI-A-1' "$cmd"; then
log "A video=HDMI-A-1 override already exists in $cmd; leaving it alone."
return 0
fi
cp -an "$cmd" "$cmd.opsbox-backup"
sed -i "1 s/[[:space:]]*\$/ video=HDMI-A-1:${res}@60D/" "$cmd"
log "Forced HDMI-A-1 to ${res} even when disconnected (reboot required)."
}
install_vnc() {
apt_install wayvnc || return 1
mkdir -p /etc/wayvnc
if [[ ! -f /etc/wayvnc/config ]]; then
cat > /etc/wayvnc/config <<'VNC'
use_relative_paths=true
address=127.0.0.1
enable_auth=false
enable_pam=false
relax_encryption=true
VNC
chmod 0600 /etc/wayvnc/config
fi
if has_cmd raspi-config; then
raspi-config nonint do_vnc 0 || warn "raspi-config could not enable VNC."
fi
force_headless_display
systemctl enable wayvnc 2>/dev/null || true
systemctl restart wayvnc 2>/dev/null || warn "WayVNC installed; it will start with the desktop session after a reboot."
return 0
}
# ---- Docker (mandatory) ---------------------------------------------------------------
register_docker_binfmt() {
# Register foreign CPU handlers so explicitly requested non-native images
# (for example linux/amd64 on ARM64) can execute through QEMU.
local unit=/etc/systemd/system/opsbox-binfmt.service
log "Registering Docker QEMU/binfmt handlers (amd64)..."
docker run --privileged --rm tonistiigi/binfmt:latest --install amd64 || return 1
[[ -e /proc/sys/fs/binfmt_misc/qemu-x86_64 ]] || {
err "QEMU amd64 handler was not registered by binfmt_misc."
return 1
}
grep -q '^enabled' /proc/sys/fs/binfmt_misc/qemu-x86_64 || {
err "QEMU amd64 binfmt handler exists but is not enabled."
return 1
}
# Kernel binfmt registrations are lost on reboot; restore them after Docker starts.
cat > "$unit" <<'UNIT'
[Unit]
Description=Register QEMU binfmt handlers for Docker
Requires=docker.service
After=docker.service
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/docker run --privileged --rm tonistiigi/binfmt:latest --install amd64
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload || return 1
systemctl enable opsbox-binfmt.service || return 1
log "QEMU amd64 emulation is enabled and configured to return after reboot."
}
install_docker_engine() {
apt_install ca-certificates curl gnupg qemu-user-static binfmt-support rsync || return 1
local existing_root=""
if has_cmd docker; then existing_root="$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || true)"; fi
if ! has_cmd docker; then
curl -fsSL https://get.docker.com -o "$TMP_DIR/get-docker.sh" || return 1
sh "$TMP_DIR/get-docker.sh" || return 1
fi
mkdir -p /etc/docker "$DATA_ROOT/engine"
if [[ -n "$existing_root" && "$existing_root" != "$DATA_ROOT/engine" && -d "$existing_root" ]]; then
if [[ -z "$(find "$DATA_ROOT/engine" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then
systemctl stop docker || true
rsync -aHAX --numeric-ids "$existing_root/" "$DATA_ROOT/engine/" || return 1
else
err "Docker already has data at $existing_root and the selected destination is non-empty."
err "Refusing to switch roots automatically; migrate Docker data manually first."
return 1
fi
fi
local daemon=/etc/docker/daemon.json
python3 - "$daemon" "$DATA_ROOT/engine" <<'PY' || return 1
import json, os, sys, tempfile
path, root = sys.argv[1:]
data = {}
if os.path.exists(path):
with open(path) as f: data = json.load(f)
data['data-root'] = root
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.daemon.')
with os.fdopen(fd, 'w') as f: json.dump(data, f, indent=2); f.write('\n')
os.chmod(tmp, 0o644); os.replace(tmp, path)
PY
systemctl enable --now docker || return 1
systemctl restart docker || return 1
register_docker_binfmt || return 1
docker network inspect opsbox_proxy >/dev/null 2>&1 || docker network create opsbox_proxy >/dev/null
if id "$ADMIN_USER" >/dev/null 2>&1; then usermod -aG docker "$ADMIN_USER"; fi
}
docker_logged_in() { grep -qs "\"$DOCKER_REGISTRY\"" /root/.docker/config.json; }
docker_login() {
local attempt=0
if [[ -z "$DOCKER_PASS" ]] && docker_logged_in; then
log "Already logged in to $DOCKER_REGISTRY."
return 0
fi
while ((attempt < 3)); do
if [[ -n "$DOCKER_USER" && -n "$DOCKER_PASS" ]] \
&& printf '%s' "$DOCKER_PASS" | docker login "$DOCKER_REGISTRY" -u "$DOCKER_USER" --password-stdin >/dev/null; then
log "Logged in to $DOCKER_REGISTRY as $DOCKER_USER."
return 0
fi
attempt=$((attempt + 1))
err "Docker login to $DOCKER_REGISTRY failed (attempt $attempt/3)."
form_run "Docker registry login" "Login to $DOCKER_REGISTRY failed. Check the username and password/token." \
"DOCKER_USER|Username|t" "DOCKER_PASS|Password / token|p" || return 1
done
return 1
}
install_caddy() {
mkdir -p "$DATA_ROOT/caddy/data" "$DATA_ROOT/caddy/config"
docker network inspect opsbox_proxy >/dev/null 2>&1 || docker network create opsbox_proxy >/dev/null
local compose="$OPSBOX_DIR/docker/caddy.yml"
OPSBOX_DATA_ROOT="$DATA_ROOT" docker compose --env-file "$ENV_FILE" -f "$compose" up -d
}
install_docker_stack() {
install_docker_engine || return 1
docker_login || return 1
if [[ "$USE_CADDY" == yes ]]; then install_caddy || return 1; fi
DOCKER_PASS=""
}
export_caddy_ca() {
[[ "$USE_CADDY" == yes ]] || return 0
for _ in {1..20}; do
docker cp opsbox-caddy:/data/caddy/pki/authorities/local/root.crt "$CONFIG_DIR/caddy-root.crt" 2>/dev/null && break
sleep 2
done
if [[ -f "$CONFIG_DIR/caddy-root.crt" ]]; then
chmod 0644 "$CONFIG_DIR/caddy-root.crt"
log "Caddy root certificate exported to $CONFIG_DIR/caddy-root.crt. Import it on client devices."
else warn "Caddy's local root CA is not available yet; export it after the first HTTPS route is active."; fi
}
compose_stack() {
local name="$1" file="$2" envfile=""
shift 2
if (($#)) && [[ "$1" != --profile* ]]; then envfile="$1"; shift; fi
local target="$OPSBOX_DIR/$file"
local -a args=(docker compose -f "$target")
mkdir -p "$DATA_ROOT/$name"
[[ -n "$envfile" ]] && args+=(--env-file "$envfile")
OPSBOX_DATA_ROOT="$DATA_ROOT" "${args[@]}" "$@" up -d
}
# Gateway of the default Docker bridge (what host.docker.internal resolves to).
docker_gateway() {
local gw
gw="$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}' 2>/dev/null || true)"
printf '%s' "${gw:-172.17.0.1}"
}
# ---- Local DNS: *.<domain> -> this machine ---------------------------------------------
# Fallback AP clients: NetworkManager's shared-mode dnsmasq already hands out the AP
# address as DNS and forwards everything else upstream. It reads drop-ins from
# /etc/NetworkManager/dnsmasq-shared.d, so we only add a wildcard there.
# WireGuard clients: a tiny dnsmasq (opsbox-dns) on the Docker gateway that answers only
# our domain (split DNS: clients send nothing else to it).
install_dns() {
local domain="$OPSBOX_DOMAIN" ap_ip gw
apt_install dnsmasq-base || return 1
if contains fallback-ap; then
ap_ip="${FALLBACK_AP_CIDR%%/*}"
mkdir -p /etc/NetworkManager/dnsmasq-shared.d
cat > /etc/NetworkManager/dnsmasq-shared.d/opsbox.conf <<EOF
# Managed by opsbox: $domain and every *.$domain name resolve to this machine.
address=/$domain/$ap_ip
EOF
# Read when the AP comes up; bounce it if it is up now (fallback-ap restarts it if still needed).
if nmcli -t -f NAME connection show --active 2>/dev/null | grep -Fxq "Fallback AP"; then
nmcli connection down "Fallback AP" >/dev/null 2>&1 || true
fi
log "Fallback AP clients: *.$domain -> $ap_ip"
fi
if contains wireguard; then
if [[ "$DOCKER_OK" != yes ]]; then
warn "Docker is not ready; skipped the WireGuard DNS resolver."
else
gw="$(docker_gateway)"
cat > "$CONFIG_DIR/dns.conf" <<EOF
# Managed by opsbox: split-DNS resolver for WireGuard clients (answers only $domain).
listen-address=$gw
bind-interfaces
port=53
no-resolv
no-hosts
no-poll
pid-file=
address=/$domain/$gw
EOF
cat > /etc/systemd/system/opsbox-dns.service <<'UNIT'
[Unit]
Description=OpsBox DNS for *.domain (WireGuard clients)
After=docker.service network-online.target
Requires=docker.service
[Service]
ExecStart=/usr/sbin/dnsmasq --keep-in-foreground --conf-file=/etc/opsbox/dns.conf
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload || return 1
systemctl enable opsbox-dns.service || return 1
systemctl restart opsbox-dns.service || return 1
log "WireGuard DNS: $gw:53 answers *.$domain -> $gw"
log "In WG Portal set: DNS server $gw, search domain $domain (~$domain on systemd-resolved clients), AllowedIPs $gw/32."
fi
fi
}
# ---- container services ---------------------------------------------------------------
install_speedtest() { compose_stack librespeed docker/librespeed.yml "$ENV_FILE"; }
install_opentak() {
apt_install curl openssl || return 1
local dir="$DATA_ROOT/opentak" svc
mkdir -p "$dir"
# Upstream installer: fetch compose + generate .env under ./data/opentak; don't start yet.
fetch "https://raw.githubusercontent.com/9M2PJU/9M2PJU-OpenTAKServer-Docker/main/scripts/install.sh" "$TMP_DIR/ots-install.sh" || return 1
bash "$TMP_DIR/ots-install.sh" --prefix "$dir" --no-start || return 1
svc="$(cd "$dir" && docker compose config --services | grep -iE 'ots|opentak' | grep -viE 'postgres|rabbit|db|mq' | head -n1 || true)"
[[ -n "$svc" ]] || { err "Could not detect the OpenTAKServer service in $dir/docker-compose.yml"; return 1; }
log "Detected OpenTAKServer service: $svc"
env_put "$dir/.env" OTS_WEB_BIND "$OTS_WEB_BIND"
env_put "$dir/.env" OTS_WEB_PORT "$OTS_WEB_PORT"
env_put "$dir/.env" OPSBOX_DOMAIN "$OPSBOX_DOMAIN"
env_put "$dir/.env" OPSBOX_SUB_OPENTAK "${OPSBOX_SUB_OPENTAK:-tak}"
# 8089 (TAK streaming) and 8446 (certificate enrollment) are fixed host ports;
# they are reserved in the Network step so nothing else can be given them.
cat > "$dir/docker-compose.override.yml" <<OVERRIDE
services:
${svc}:
ports: !override
- "\${OTS_WEB_BIND:-127.0.0.1}:\${OTS_WEB_PORT:-8090}:8080"
- "8089:8089"
- "8446:8446"
networks:
- default
- proxy
labels:
caddy: \${OPSBOX_SUB_OPENTAK:-tak}.\${OPSBOX_DOMAIN:-opsbox.internal}
caddy.reverse_proxy: "{{upstreams 8080}}"
caddy.tls: internal
networks:
proxy:
external: true
name: opsbox_proxy
OVERRIDE
(cd "$dir" && docker compose config -q) || { err "Compose validation failed in $dir"; return 1; }
(cd "$dir" && docker compose up -d)
}
install_maps() {
local dataset url archive target expected available urlvar ext
apt_install unzip || return 1
for dataset in satellite vector contours; do
case "$dataset" in
satellite) [[ "$MAP_SATELLITE" == yes ]] || continue; expected=$((186*GB));;
vector) [[ "$MAP_VECTOR" == yes ]] || continue; expected=$((70*GB));;
contours) [[ "$MAP_CONTOURS" == yes ]] || continue; expected=$((18*GB));;
esac
urlvar="MAP_URL_${dataset^^}"; url="${!urlvar:-}"
[[ "$url" =~ ^https?:// ]] || { warn "Skipped $dataset: no valid HTTP(S) URL was given."; continue; }
available="$(free_bytes "$DATA_ROOT")"
if ((available < expected)); then
warn "Not enough free space for $dataset; need approximately $(zim_size_gb "$expected")."
continue
fi
mkdir -p "$DATA_ROOT/maps/tiles/$dataset" "$DATA_ROOT/maps/.downloads"
archive="$DATA_ROOT/maps/.downloads/$dataset.download"
if ! curl -fL --retry 3 -C - "$url" -o "$archive"; then rm -f "$archive"; return 1; fi
target="$DATA_ROOT/maps/tiles/$dataset"
if unzip -tq "$archive" >/dev/null 2>&1; then
if ! unzip -oq "$archive" -d "$target"; then rm -f "$archive"; return 1; fi
rm -f "$archive"
else
ext="${url%%\?*}"; ext="${ext##*.}"
if [[ "$ext" == mbtiles ]]; then mv "$archive" "$target/$dataset.mbtiles"
else mv "$archive" "$target/$(basename "${url%%\?*}")"; fi
fi
done
mkdir -p "$DATA_ROOT/maps/tileserver"
if [[ ! -f "$DATA_ROOT/maps/tileserver/config.json" ]]; then
install -m 0644 "$OPSBOX_DIR/data/maps/tileserver/config.json" \
"$DATA_ROOT/maps/tileserver/config.json"
fi
if [[ "$DATA_ROOT" != "$OPSBOX_DIR/data" ]]; then
mkdir -p "$DATA_ROOT/maps/tileserver/styles"
cp -an "$OPSBOX_DIR/data/maps/tileserver/styles/." \
"$DATA_ROOT/maps/tileserver/styles/"
fi
local -a profiles=()
[[ "$MAP_PHOTON" == yes ]] && profiles+=(--profile photon)
[[ "$MAP_TILESERVER" == yes ]] && profiles+=(--profile tiles)
compose_stack maps docker/maps.yml "$ENV_FILE" "${profiles[@]}"
}
install_personal_cloud() { compose_stack personal-cloud docker/cloud.yml "$ENV_FILE"; }
install_pentest() {
apt_install arp-scan aircrack-ng gobuster hashcat hcxtools hydra john netcat-openbsd nikto \
nmap masscan reaver sqlmap tcpdump wireshark || return 1
OPSBOX_DOCKER_GATEWAY="$(docker_gateway)"
save_env OPSBOX_DOCKER_GATEWAY
curl -fL --retry 3 --retry-delay 2 \
https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfinstall \
-o "$TMP_DIR/msfinstall" || return 1
chmod 0700 "$TMP_DIR/msfinstall"
"$TMP_DIR/msfinstall" || return 1
rm -f "$TMP_DIR/msfinstall"
BETTERCAP_USER="$OPSBOX_ADMIN_USERNAME"
BETTERCAP_PASSWORD="$OPSBOX_ADMIN_PASSWORD"
save_env BETTERCAP_USER BETTERCAP_PASSWORD BETTERCAP_UI_ADDR BETTERCAP_UI_PORT BETTERCAP_API_PORT BETTERCAP_ALLOW_ORIGIN
compose_stack bettercap docker/bettercap.yml "$ENV_FILE"
}
# Keep the kernel DVB-T driver away from RTL-SDR dongles (it grabs them before SDR apps can),
# and sanity-check that the HAT's SDR is visible on USB.
prepare_rtlsdr_host() {
apt_install rtl-sdr usbutils || return 1
cat > /etc/modprobe.d/opsbox-rtlsdr.conf <<'BLACKLIST'
# Managed by opsbox: keep the kernel DVB driver off RTL-SDR dongles so SDR apps can claim them.
blacklist dvb_usb_rtl28xxu
blacklist rtl2832
blacklist rtl2832_sdr
blacklist rtl2830
blacklist r820t
BLACKLIST
local m usb
for m in rtl2832_sdr dvb_usb_rtl28xxu rtl2832 rtl2830 r820t; do modprobe -r "$m" 2>/dev/null || true; done
usb="$(lsusb 2>/dev/null || true)"
if grep -qiE '0bda:(2832|2838)' <<<"$usb"; then
log "RTL-SDR detected on USB."
else
warn "No RTL-SDR (0bda:2832/2838) found on USB. OpenWebRX+ will start but has no device until the HAT's SDR is visible (check 'lsusb'; a reboot may be needed after the module blacklist)."
fi
}
install_sdr_tools() {
prepare_rtlsdr_host || return 1
mkdir -p "$DATA_ROOT/sdr/openwebrx/etc" "$DATA_ROOT/sdr/openwebrx/var"
# The image's runtime uid isn't documented; keep state dirs writable until it's confirmed.
chmod 0777 "$DATA_ROOT/sdr/openwebrx/etc" "$DATA_ROOT/sdr/openwebrx/var"
compose_stack sdr docker/sdr.yml "$ENV_FILE"
}
install_ai() {
apt_install curl ca-certificates || return 1
local dir="$AI_DIR" repo="$AI_REPO" user=opsbox-ai
id "$user" >/dev/null 2>&1 || useradd --system --home "$dir" --create-home --shell /usr/sbin/nologin "$user"
mkdir -p "$dir"
chown -R "$user:$user" "$dir"
if ! has_cmd uv; then
curl -LsSf https://astral.sh/uv/install.sh -o "$TMP_DIR/uv-install.sh" || return 1
env UV_INSTALL_DIR=/usr/local/bin sh "$TMP_DIR/uv-install.sh" || return 1
fi
runuser -u "$user" -- bash -lc "cd '$dir' && /usr/local/bin/uv venv --python=3.13 --seed && /usr/local/bin/uv pip install --python .venv/bin/python litert-cli-nightly litert-lm-nightly" || return 1
if [[ "$AI_IMPORT" == yes ]]; then
runuser -u "$user" -- bash -lc "cd '$dir' && .venv/bin/litert-lm import --from-huggingface-repo '$repo'" || return 1
fi
warn "LiteRT serving flags/API differ by release. The model runtime is installed, but no unverified systemd API command was generated."
}
# ---- Wireless HAT: shared gpsd + Meshtastic ------------------------------------------
# gpsd is the single owner of the GPS UART. Everything else is a client:
# * network clients (Bettercap, scripts, containers) connect to gpsd on port 2947;
# * software that insists on a serial device gets its own PTY at /run/gps/<name>,
# fed with gpsd's NMEA stream by a socat service (one PTY per consumer, because
# a PTY can only be read by one process). Add another with:
# systemctl enable --now opsbox-gps-pty@<name>
install_gpsd() {
local dev="$1" devices gw
apt_install gpsd gpsd-clients socat || return 1
devices="$dev"
if [[ "$HAT_PPS" == yes ]]; then devices+=" /dev/pps0"; fi
gw="$(docker_gateway)"
cat > /etc/default/gpsd <<EOF
# Managed by opsbox: gpsd is the single owner of the GPS UART.
START_DAEMON="true"
USBAUTO="false"
DEVICES="$devices"
GPSD_OPTIONS="-n"
EOF
# Listen on localhost and the Docker gateway only (never on the LAN).
mkdir -p /etc/systemd/system/gpsd.socket.d
cat > /etc/systemd/system/gpsd.socket.d/opsbox.conf <<EOF
[Socket]
ListenStream=
ListenStream=/run/gpsd.sock
ListenStream=127.0.0.1:2947
ListenStream=[::1]:2947
ListenStream=$gw:2947
FreeBind=true
EOF
cat > /etc/systemd/system/opsbox-gps-pty@.service <<'UNIT'
[Unit]
Description=OpsBox gpsd NMEA pseudo-terminal (/run/gps/%i)
After=gpsd.socket
Wants=gpsd.socket
[Service]
ExecStartPre=/bin/mkdir -p /run/gps
ExecStartPre=-/bin/rm -f /run/gps/%i
ExecStart=/usr/bin/socat -d PTY,link=/run/gps/%i,raw,echo=0,mode=0666 "EXEC:/usr/bin/gpspipe -r"
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload || return 1
systemctl enable gpsd.socket gpsd.service 2>/dev/null || true
systemctl restart gpsd.socket || return 1
systemctl restart gpsd.service || warn "gpsd did not start yet; it will after the reboot (UART overlay needs it)."
log "Shared gpsd ready on 127.0.0.1:2947 and $gw:2947 (device: $devices)."
}
# Meshtastic per the HackerGadgets HAT guide (Debian 12/13 Beta repo, SX1262 on SPI1).
install_meshtastic() {
local ver conf=/etc/meshtasticd/config.yaml port="${MESHTASTIC_PORT:-8070}" gps_link=""
local keyring=/etc/apt/trusted.gpg.d/network_Meshtastic_beta.gpg
[[ "$(dpkg --print-architecture)" == arm64 ]] || { err "Meshtastic's Debian repo needs a 64-bit OS; on 32-bit use Meshtastic's Raspbian instructions."; return 1; }
ver="$(. /etc/os-release && echo "${VERSION_ID:-}")"
[[ "$ver" == 12 || "$ver" == 13 ]] || { err "Meshtastic supports Debian 12/13 only (found '${ver:-unknown}')."; return 1; }
apt_install curl gnupg || return 1
echo "deb http://download.opensuse.org/repositories/network:/Meshtastic:/beta/Debian_${ver}/ /" \
> /etc/apt/sources.list.d/network:Meshtastic:beta.list
curl -fsSL "https://download.opensuse.org/repositories/network:Meshtastic:beta/Debian_${ver}/Release.key" \
-o "$TMP_DIR/meshtastic.key" || return 1
gpg --dearmor < "$TMP_DIR/meshtastic.key" > "$TMP_DIR/meshtastic.gpg" || return 1
install -m 0644 "$TMP_DIR/meshtastic.gpg" "$keyring"
apt-get update || return 1
apt_install meshtasticd || return 1
if [[ "$HAT_GPS" == yes ]]; then gps_link=/run/gps/meshtastic; fi
mkdir -p /etc/meshtasticd
if [[ -f "$conf" ]]; then
[[ -e "$conf.bak" ]] || cp -a "$conf" "$conf.bak"
else
touch "$conf"
fi
# Remove any existing top-level Lora/GPS/Webserver blocks (a duplicate YAML key stops
# meshtasticd from starting), then append ours.
python3 - "$conf" "$HAT_LORA" "$gps_link" "$port" <<'PY' || return 1
import re, sys
path, lora, gps, port = sys.argv[1:5]
managed = ['Webserver'] + (['Lora'] if lora == 'yes' else []) + (['GPS'] if gps else [])
pat = re.compile(r'^(%s):' % '|'.join(managed))
out, skip = [], False
for line in open(path).read().splitlines():
if pat.match(line):
skip = True
continue
if skip and (not line.strip() or line[0] in ' \t'):
continue
skip = False
out.append(line)
while out and not out[-1].strip():
out.pop()
blocks = []
if lora == 'yes':
blocks.append("Lora:\n Module: sx1262\n DIO2_AS_RF_SWITCH: true\n DIO3_TCXO_VOLTAGE: true\n"
" IRQ: 26\n Busy: 24\n Reset: 25\n spidev: spidev1.0")
if gps:
blocks.append("GPS:\n SerialPath: %s" % gps)
blocks.append("Webserver:\n Port: %s\n RootPath: /usr/share/meshtasticd/web" % port)
open(path, 'w').write('\n'.join(out) + '\n\n' + '\n\n'.join(blocks) + '\n')
PY
# GPS comes from the shared gpsd through its own PTY; start it before meshtasticd.
if [[ -n "$gps_link" ]]; then
mkdir -p /etc/systemd/system/meshtasticd.service.d
cat > /etc/systemd/system/meshtasticd.service.d/opsbox-gps.conf <<'DROPIN'
[Unit]
Wants=opsbox-gps-pty@meshtastic.service
After=opsbox-gps-pty@meshtastic.service
DROPIN
systemctl daemon-reload
systemctl enable --now opsbox-gps-pty@meshtastic.service || warn "Could not start the Meshtastic GPS PTY service."
fi
systemctl daemon-reload
if [[ "$HAT_LORA" == yes ]]; then
systemctl enable meshtasticd || return 1
if [[ -e /dev/spidev1.0 ]]; then
systemctl restart meshtasticd || return 1
else
warn "/dev/spidev1.0 does not exist yet; meshtasticd will start after the reboot."
fi
else
systemctl disable --now meshtasticd 2>/dev/null || true
log "LoRa not selected: meshtasticd installed but left disabled."
fi
if [[ "$USE_CADDY" == yes ]]; then
log "Meshtastic web UI: https://${OPSBOX_SUB_MESH:-mesh}.$OPSBOX_DOMAIN (via Caddy; direct: https://localhost:$port)"
else
log "Meshtastic web UI: https://localhost:$port (self-signed certificate)"
fi
log "Set Config -> LoRa -> Region in the web UI before transmitting."
}
install_hat() {
apt_install git i2c-tools minicom util-linux-extra gpsd gpsd-clients chrony pps-tools rtl-sdr || return 1
local model pi5=no gps_path=/dev/ttyS0
model="$(tr -d '\0' </proc/device-tree/model 2>/dev/null || true)"
if [[ "$model" == *"Raspberry Pi 5"* || "$model" == *"Compute Module 5"* ]]; then pi5=yes; gps_path=/dev/ttyAMA0; fi
local boot=/boot/firmware/config.txt cmd=/boot/firmware/cmdline.txt
[[ -f "$boot" ]] || boot=/boot/config.txt
[[ -f "$cmd" ]] || cmd=/boot/cmdline.txt
if [[ "$HAT_GPS" == yes ]]; then
if [[ "$pi5" == yes ]]; then grep -q '^dtparam=uart0=on' "$boot" || echo 'dtparam=uart0=on' >> "$boot"
else grep -q '^enable_uart=1' "$boot" || echo 'enable_uart=1' >> "$boot"; fi
if [[ -f "$cmd" ]]; then sed -i 's/\(^\| \)console=serial0,[^ ]*//g; s/\(^\| \)console=ttyAMA0,[^ ]*//g' "$cmd"; fi
fi
if [[ "$HAT_LORA" == yes ]]; then
grep -q '^dtoverlay=spi1-1cs' "$boot" || echo 'dtoverlay=spi1-1cs' >> "$boot"
grep -q '^dtparam=spi=on' "$boot" || echo 'dtparam=spi=on' >> "$boot"
fi
if [[ "$HAT_RTC" == yes ]]; then
grep -q '^dtparam=i2c_arm=on' "$boot" || echo 'dtparam=i2c_arm=on' >> "$boot"
grep -q '^dtoverlay=i2c-rtc,pcf85063a' "$boot" || echo 'dtoverlay=i2c-rtc,pcf85063a' >> "$boot"
fi
if [[ "$HAT_PPS" == yes ]]; then
grep -q '^dtoverlay=pps-gpio,gpiopin=6' "$boot" || echo 'dtoverlay=pps-gpio,gpiopin=6' >> "$boot"
fi
if [[ "$HAT_GPS" == yes ]]; then install_gpsd "$gps_path" || return 1; fi
if [[ "$HAT_LORA" == yes || "$HAT_GPS" == yes ]]; then install_meshtastic || return 1; fi
warn "Hardware overlays were written. Reboot is required."
}
install_zims() {
local slug title bytes url filename part v
mkdir -p "$DATA_ROOT/zims"
for slug in "${ZIM_ORDER[@]}"; do
dl_has "z_$slug" || continue
title="${ZIM_TITLE[$slug]}"; bytes="${ZIM_BYTES[$slug]}"; url="${ZIM_URL[$slug]}"
if [[ "${ZIM_MANUAL[$slug]}" == yes ]]; then
v="MZIM_$slug"; url="${!v:-}"
[[ "$url" =~ ^https?:// ]] || { warn "No URL given for ${ZIM_NAME[$slug]}; skipping."; continue; }
fi
filename="$(basename "${url%%\?*}")"
[[ "$filename" == *.zim ]] || filename="$slug.zim"
if [[ -e "$DATA_ROOT/zims/$filename" ]]; then warn "$filename already exists; skipped."; continue; fi
log "Downloading $title ($(zim_size_gb "$bytes"))..."
part="$DATA_ROOT/zims/$filename.part"
if curl -fL --retry 3 -C - "$url" -o "$part"; then mv "$part" "$DATA_ROOT/zims/$filename"
else rm -f "$part"; FAILED+=("ZIM: $title"); fi
done
}
# ======================================================================================
main() {
bootstrap "$@"
init
ensure_prereqs
wizard
persist_config
mkdir -p "$DATA_ROOT"
if [[ "$APT_UPGRADE" == yes ]]; then
log "Applying system upgrades..."
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y
fi
clear
# Docker is mandatory: engine, registry login, proxy network and (optionally) Caddy.
if run_component "Docker" install_docker_stack; then DOCKER_OK=yes; fi
contains tools && run_component "Tools" install_tools || true
contains theme && run_component "Theme" install_theme || true
contains wireguard && run_docker_component "WireGuard Portal" install_wireguard || true
contains fallback-ap && run_component "Fallback AP" install_fallback_ap || true
if [[ "$USE_CADDY" == yes ]] && { contains fallback-ap || contains wireguard; }; then run_component "Local DNS" install_dns; fi
contains vnc && run_component "VNC" install_vnc || true
contains ai && run_component "Local AI" install_ai || true
contains wireless-hat && run_component "Wireless HAT" install_hat || true
contains pentest && run_docker_component "Pen Test Suite" install_pentest || true
contains speedtest && run_docker_component "LibreSpeed" install_speedtest || true
contains tak && run_docker_component "TAK Server" install_opentak || true
contains maps && run_docker_component "Maps" install_maps || true
contains personal-cloud && run_docker_component "Personal Cloud" install_personal_cloud || true
contains sdr-tools && run_docker_component "SDR tools" install_sdr_tools || true
contains zims && run_component "ZIM Archives" install_zims || true
[[ "$DOCKER_OK" == yes ]] && export_caddy_ca || true
local x report=$'Installation finished.\n\nSucceeded:\n'
for x in "${SUCCEEDED[@]}"; do report+=" * $x"$'\n'; done
report+=$'\nFailed:\n'
if ((${#FAILED[@]})); then for x in "${FAILED[@]}"; do report+=" * $x"$'\n'; done; else report+=$' (none)\n'; fi
report+=$'\nReboot is recommended if hardware overlays or kernel modules changed.'
msg "$report"
printf '%s\n' "Succeeded: ${SUCCEEDED[*]:-(none)}" "Failed: ${FAILED[*]:-(none)}" | tee "/var/log/opsbox/install-$(date +%F-%H%M%S).log"
}
main "$@"