diff --git a/install.sh b/install.sh index c19d72d..e3df0d3 100644 --- a/install.sh +++ b/install.sh @@ -3,22 +3,34 @@ set -Eeuo pipefail # Viator bootstrap + installer. Keep the Git URL in one place. VIATOR_GIT_REPO="${VIATOR_GIT_REPO:-https://git.zakscode.com/ztimson/viator.git}" -VIATOR_VERSION="1.0.0" +VIATOR_VERSION="1.1.0" VIATOR_DIR="${VIATOR_DIR:-}" CONFIG_DIR="/etc/viator" STATE_FILE="$CONFIG_DIR/selections" +DL_FILE="$CONFIG_DIR/downloads" ENV_FILE="$CONFIG_DIR/viator.env" +THEME_DIR="/usr/local/share/viator" DATA_ROOT="" INSTALL_ROOT="" TMP_DIR="" LOCK_FILE="/run/lock/viator-install.lock" APT_UPGRADE="no" -USE_CADDY="no" +USE_CADDY="" VIATOR_DOMAIN="${VIATOR_DOMAIN:-viator.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' @@ -35,6 +47,64 @@ trap 'rc=$?; err "Unexpected failure on line $LINENO (exit $rc)"; exit "$rc"' ER require_root() { [[ $EUID -eq 0 ]] || die "Run as root: curl ... | sudo bash"; } +# -------------------------------------------------------------------------------------- +# Catalogue of components (alphabetical by tag) +# -------------------------------------------------------------------------------------- +COMPONENTS=( + "adsb|ADS-B aircraft tracking (tar1090)" + "ai|Local AI (LiteRT)" + "atak|Tactical awareness kit (OpenTAK Server)" + "fallback-ap|Fallback wireless access point" + "hat|Wireless HAT (GPS, LoRa, RTC, SDR)" + "maps|Maps (Cartomake web UI)" + "openwebrx|OpenWebRX+ SDR receiver" + "pentest|Pen test suite (host tools + Bettercap)" + "personal-cloud|Personal cloud (AI, file editing, notes, ZIM reader)" + "rtl433|RTL_433 sensor decoder" + "speedtest|LibreSpeed speed test" + "theme|Terminal prompt theme and login banner" + "tools|Tools (btop, jq, tmux)" + "vnc|VNC remote desktop" + "wireguard|WireGuard VPN" + "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 VIATOR_DIR="$(realpath -e -- "$VIATOR_DIR")" @@ -46,40 +116,26 @@ init() { TMP_DIR="$(mktemp -d /tmp/viator.XXXXXX)" exec 9>"$LOCK_FILE" flock -n 9 || die "Another Viator installer is already running." - touch "$STATE_FILE" "$ENV_FILE" + touch "$STATE_FILE" "$DL_FILE" "$ENV_FILE" chmod 0600 "$ENV_FILE" - if [[ -f "$ENV_FILE" ]]; then - # This file is root-owned and generated by this installer. - set -a - # shellcheck disable=SC1090 - source "$ENV_FILE" - set +a - fi + # This file is root-owned and generated by this installer. + set -a + # shellcheck disable=SC1090 + source "$ENV_FILE" + set +a DATA_ROOT="${VIATOR_DATA_ROOT:-$DATA_ROOT}" VIATOR_DATA_ROOT="$DATA_ROOT" ADMIN_USER="${VIATOR_ADMIN_USER:-$ADMIN_USER}" + 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; } -ui() { - if has_cmd whiptail; then return 0; fi - DEBIAN_FRONTEND=noninteractive apt-get install -y whiptail >/dev/null -} - -msg() { whiptail --title "Viator" --msgbox "$1" 12 76; } -ask_yes() { - whiptail --title "Viator" --yesno "$1" 12 76 -} -ask_input() { - local title="$1" prompt="$2" default="${3:-}" result - result="$(whiptail --title "$title" --inputbox "$prompt" 10 76 "$default" 3>&1 1>&2 2>&3)" || return 1 - printf '%s' "$result" -} -ask_password() { - local title="$1" prompt="$2" default="${3:-}" result - result="$(whiptail --title "$title" --passwordbox "$prompt" 10 76 "$default" 3>&1 1>&2 2>&3)" || return 1 - printf '%s' "$result" +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() { @@ -88,6 +144,8 @@ save_env() { value="${!key-}" value="${value//\\/\\\\}" value="${value//\"/\\\"}" + value="${value//\$/\\\$}" + value="${value//\`/\\\`}" line="${key}=\"${value}\"" if grep -q "^${key}=" "$ENV_FILE"; then sed_line="${line//\\/\\\\}" @@ -114,41 +172,10 @@ env_put() { } valid_sub() { [[ "$1" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$ ]]; } -valid_port() { [[ "$1" =~ ^[0-9]+$ ]] && (( $1 >= 1 && $1 <= 65535 )); } - -# expose KEY "Label" default_subdomain default_port BIND_VAR PORT_VAR [need_host] -# -# Network model (decided once in configure_docker via USE_CADDY): -# Caddy mode -> ask for a subdomain; container ports stay on 127.0.0.1; -# Caddy routes . with internal TLS. -# Own-proxy mode -> ask for a host port; bind 0.0.0.0 so the user's reverse proxy -# can reach it. If need_host=yes, also ask for the public -# hostname (used in links between services). -# Writes VIATOR_SUB_, VIATOR_HOST_, , to viator.env. -expose() { - local key="$1" label="$2" dsub="$3" dport="$4" bindvar="$5" portvar="$6" need_host="${7:-no}" - local subvar="VIATOR_SUB_$key" hostvar="VIATOR_HOST_$key" sub port host - if [[ "$USE_CADDY" == yes ]]; then - sub="$(ask_input "$label" "Subdomain (served as .$VIATOR_DOMAIN):" "${!subvar:-$dsub}")" || return 1 - sub="${sub,,}" - valid_sub "$sub" || { msg "Invalid subdomain: '$sub'"; return 1; } - printf -v "$subvar" '%s' "$sub" - printf -v "$hostvar" '%s' "" - printf -v "$bindvar" '%s' "127.0.0.1" - printf -v "$portvar" '%s' "${!portvar:-$dport}" - else - port="$(ask_input "$label" "Host port (your reverse proxy should forward to this):" "${!portvar:-$dport}")" || return 1 - valid_port "$port" || { msg "Invalid port: '$port'"; return 1; } - printf -v "$bindvar" '%s' "0.0.0.0" - printf -v "$portvar" '%s' "$port" - host="${!hostvar:-}" - if [[ "$need_host" == yes ]]; then - host="$(ask_input "$label" "Public hostname your reverse proxy serves this on (no scheme, e.g. maps.example.com):" "$host")" || return 1 - fi - printf -v "$hostvar" '%s' "$host" - fi - save_env "$subvar" "$hostvar" "$bindvar" "$portvar" -} +valid_port() { [[ "$1" =~ ^[0-9]+$ ]] && (( 10#$1 >= 1 && 10#$1 <= 65535 )); } +valid_pw() { [[ "$1" =~ ^[A-Za-z0-9._-]{12,}$ ]]; } +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=("$@") @@ -156,21 +183,84 @@ apt_install() { apt-get install -y --no-install-recommends "${packages[@]}" } -apt_setup() { - log "Updating APT package indexes..." - apt-get update - if [[ "$APT_UPGRADE" == yes ]]; then - log "Applying system upgrades..." - DEBIAN_FRONTEND=noninteractive apt-get upgrade -y - fi -} - 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 "Viator installer v$VIATOR_VERSION" --cr-wrap --no-collapse "$@"; } +msg() { dlg --title "Viator" --msgbox "$1" 0 0 || true; } +ask_yes() { dlg --title "Viator" --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 ]] && { VIATOR_DIR="${2:?Missing install directory}"; return 0; } [[ $EUID -eq 0 ]] || die "Run as root: curl ... | sudo bash" @@ -205,7 +295,8 @@ bootstrap() { fi [[ -f "$target/install.sh" ]] || die "The repository checkout does not contain install.sh." - exec bash "$target/install.sh" --installed "$target" + # stdin is the curl pipe when bootstrapped; the TUI needs the real terminal. + exec bash "$target/install.sh" --installed "$target" 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 "Viator - 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 - local selected - selected="$(whiptail --title "Viator — Components" --checklist \ - "Select the components to install. Existing data and configuration are preserved." \ - 22 82 15 "${choices[@]}" 3>&1 1>&2 2>&3)" || exit 0 - SELECTED=() - read -r -a SELECTED <<< "${selected//\"/}" - printf '%s\n' "${SELECTED[@]}" > "$STATE_FILE" } -contains() { local needle="$1" x; for x in "${SELECTED[@]}"; do [[ "$x" == "$needle" ]] && return 0; done; return 1; } - -needs_docker() { - contains docker || contains pentest || contains speedtest || contains opentak \ - || contains maps || contains personal-cloud || contains sdr +# ---- 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" } -configure_global() { - local root user upgrade - root="$(ask_input "Storage" "Docker/application data root:" "$DATA_ROOT")" || exit 0 - [[ "$root" == /* ]] || { msg "Storage path must be absolute."; exit 1; } - DATA_ROOT="${root%/}" - mkdir -p "$DATA_ROOT" - user="$(ask_input "Administrator" "Linux user to add to the docker group:" "$ADMIN_USER")" || exit 0 - id "$user" >/dev/null 2>&1 || { msg "User '$user' does not exist."; exit 1; } - ADMIN_USER="$user" - if ask_yes "Run apt upgrade -y after apt update? This can take time and may update the whole OS."; then - APT_UPGRADE=yes - else APT_UPGRADE=no; fi +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 administrator is added to the docker group. +Docker is always installed; images are pulled from $DOCKER_REGISTRY. +(Leave the password blank only if this host is already logged in.)" \ + "DATA_ROOT|Data root (absolute path)|t" \ + "ADMIN_USER|Linux user for docker group|t" \ + "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" + id "$ADMIN_USER" >/dev/null 2>&1 || err+="User '$ADMIN_USER' does not exist.\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 VIATOR_DATA_ROOT="$DATA_ROOT" - VIATOR_ADMIN_USER="$ADMIN_USER" - save_env VIATOR_DATA_ROOT VIATOR_ADMIN_USER + return 0 } +# ---- Step 4: network (Caddy + every service, one screen) ----------------------------- +build_net_rows() { + NET_ROWS=() + local add='NET_ROWS+=("$1|$2|$3|$4|$5|$6|$7")' + net_add() { NET_ROWS+=("$1|$2|$3|$4|$5|$6|$7"); } + contains speedtest && net_add SPEEDTEST "LibreSpeed" speedtest 1900 LIBRESPEED_BIND LIBRESPEED_PORT no || true + contains atak && net_add OPENTAK "OpenTAK Server (web UI)" tak 8090 OTS_WEB_BIND OTS_WEB_PORT no || true + contains maps && net_add MAPS "Cartomake (maps UI)" maps 8020 CARTOMAKE_BIND CARTOMAKE_PORT no || true + [[ "${MAP_PHOTON:-no}" == yes ]] && net_add GEOCODE "Photon geocoder" geocode 8022 PHOTON_BIND PHOTON_PORT yes || true + [[ "${MAP_TILESERVER:-no}" == yes ]] && net_add TILES "TileServer GL" tiles 8021 TILESERVER_BIND TILESERVER_PORT yes || true + if contains personal-cloud; then + net_add HARNESS "AI harness" home 8082 WEB_BIND HARNESS_PORT yes + net_add OFFICE "OnlyOffice" office 8083 WEB_BIND OFFICE_PORT yes + fi + contains openwebrx && net_add SDR "OpenWebRX+" sdr 8073 OPENWEBRX_BIND OPENWEBRX_PORT no || true + if contains pentest; then + net_add BETTERCAP "Bettercap UI" bettercap 1600 - BETTERCAP_UI_PORT no + net_add BETTERCAP_API "Bettercap API" api.bettercap 8081 - BETTERCAP_API_PORT no + fi + unset -f net_add + : "$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="$VIATOR_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 + for ((i = 0; i < n; i++)); do + IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}" + sv="VIATOR_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 + 14)); ((h > lines)) && h=$lines || true + fh=$((h - 12)); ((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://. (internal TLS). +no = you already run a reverse proxy: services are published on the host ports below for it + to forward to; . is the public name used in links between services. + +Columns: service | subdomain | host port" "$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" + valid_port "${net_port[i]}" || err+="$label: invalid port '${net_port[i]}'\n" + [[ -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"; VIATOR_DOMAIN="$dom" + for ((i = 0; i < n; i++)); do + IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}" + printf -v "VIATOR_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 "VIATOR_HOST_$key" '%s' "" + else + printf -v "$bindv" '%s' "0.0.0.0" + if [[ "$need" == yes ]]; then printf -v "VIATOR_HOST_$key" '%s' "${net_sub[i]}.$VIATOR_DOMAIN" + else printf -v "VIATOR_HOST_$key" '%s' ""; fi + fi + fi + done + return 0 +} + +# ---- Step 5: per-service configuration screens --------------------------------------- +cfg_bettercap() { + local err + BETTERCAP_USER="${BETTERCAP_USER:-viator}" + local -a specs=("BETTERCAP_USER|Web UI username|t" "BETTERCAP_PASSWORD|Web UI password (12+ chars)|p") + 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://${VIATOR_SUB_BETTERCAP:-bettercap}.$VIATOR_DOMAIN}" + specs+=("BETTERCAP_UI_ADDR|Listen address (0.0.0.0 = all)|t" "BETTERCAP_ALLOW_ORIGIN|Public UI URL (CORS origin)|t") + fi + while true; do + form_run "Bettercap" "Bettercap web UI login (separate from your Linux login).\nPassword: letters, numbers, dot, dash or underscore." "${specs[@]}" || return 1 + err="" + [[ "$BETTERCAP_USER" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]] || err+="Invalid username.\n" + valid_pw "$BETTERCAP_PASSWORD" || err+="Password needs 12+ characters: letters, numbers, dot, dash or underscore.\n" + if [[ "$USE_CADDY" != yes ]]; then + [[ -n "$BETTERCAP_UI_ADDR" ]] || err+="Listen address is required.\n" + valid_url "$BETTERCAP_ALLOW_ORIGIN" || err+="Public URL must start with http:// or https://\n" + fi + [[ -z "$err" ]] && break + msg "$err" + done +} + +cfg_openwebrx() { + local err + OPENWEBRX_ADMIN_USER="${OPENWEBRX_ADMIN_USER:-admin}" + OPENWEBRX_IMAGE="${OPENWEBRX_IMAGE:-slechev/openwebrxplus-softmbe:latest}" + while true; do + form_run "OpenWebRX+" "OpenWebRX+ administrator login.\nPassword: letters, numbers, dot, dash or underscore." \ + "OPENWEBRX_ADMIN_USER|Admin username|t" \ + "OPENWEBRX_ADMIN_PASSWORD|Admin password (12+ chars)|p" \ + "OPENWEBRX_IMAGE|Docker image|t" || return 1 + err="" + [[ "$OPENWEBRX_ADMIN_USER" =~ ^[a-z][a-z0-9_-]*$ ]] || err+="Username: lowercase letters, numbers, dash or underscore.\n" + valid_pw "$OPENWEBRX_ADMIN_PASSWORD" || err+="Password needs 12+ characters: letters, numbers, dot, dash or underscore.\n" + [[ -n "$OPENWEBRX_IMAGE" ]] || err+="Image is required.\n" + [[ -z "$err" ]] && break + msg "$err" + done +} + +cfg_fallback_ap() { + local err iface + if [[ -f /etc/fallback-ap.conf ]]; then + # shellcheck disable=SC1091 + source /etc/fallback-ap.conf || true + 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 (8+ chars)|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" + ((${#FALLBACK_AP_PASSWORD} >= 8)) || err+="Wi-Fi password must be at least 8 characters.\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 overlays to enable (a reboot is required afterwards)." 16 92 4 \ + gps "GPS UART (also removes the Linux serial console)" "$([[ $HAT_GPS == yes ]] && echo on || echo off)" \ + lora "LoRa SX1262 on SPI1 (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 openwebrx && list+=(cfg_openwebrx) || true + contains fallback-ap && list+=(cfg_fallback_ap) || true + contains ai && list+=(cfg_ai) || true + contains 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 " 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 *.$VIATOR_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="VIATOR_SUB_$key" + if [[ "$USE_CADDY" == yes ]]; then sum_add " $(printf '%-24s' "$label") https://${!sv}.$VIATOR_DOMAIN (127.0.0.1:${!portv})" + else sum_add " $(printf '%-24s' "$label") ${!sv}.$VIATOR_DOMAIN (host port ${!portv})"; fi + done + 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 openwebrx && sum_add " OpenWebRX+: admin '$OPENWEBRX_ADMIN_USER', image $OPENWEBRX_IMAGE" || 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 hat && sum_add " HAT overlays: GPS=$HAT_GPS LoRa=$HAT_LORA RTC=$HAT_RTC PPS=$HAT_PPS" || true + contains wireguard && sum_add " WireGuard: you will be offered an editor for wg0.conf if none exists" || true + local sdrn=0 + contains openwebrx && sdrn=$((sdrn + 1)) || true + contains adsb && sdrn=$((sdrn + 1)) || true + contains rtl433 && sdrn=$((sdrn + 1)) || true + if ((sdrn > 1)); then + sum_add "" + sum_add "NOTE: one RTL-SDR can only serve one SDR service at a time. You selected $sdrn;" + sum_add " use separate receivers or point only one at the HAT tuner." + 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 VIATOR_DATA_ROOT VIATOR_ADMIN_USER VIATOR_DOMAIN USE_CADDY + DOCKER_REGISTRY_USER="$DOCKER_USER"; VIATOR_ADMIN_USER="$ADMIN_USER" + save_env VIATOR_ADMIN_USER DOCKER_REGISTRY_USER + for ((i = 0; i < ${#NET_ROWS[@]}; i++)); do + IFS='|' read -r key label dsub dport bindv portv need <<<"${NET_ROWS[i]}" + save_env "VIATOR_SUB_$key" "$portv" + if [[ "$bindv" != "-" ]]; then save_env "VIATOR_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 openwebrx; then save_env OPENWEBRX_ADMIN_USER OPENWEBRX_ADMIN_PASSWORD OPENWEBRX_IMAGE; fi + SDR_OPENWEBRX="$(contains openwebrx && echo yes || echo no)" + SDR_ADSB="$(contains adsb && echo yes || echo no)" + SDR_RTL433="$(contains rtl433 && echo yes || echo no)" + save_env SDR_OPENWEBRX SDR_ADSB SDR_RTL433 + 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 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="# >>> VIATOR BANNER >>>" marker_end="# <<< VIATOR BANNER <<<" - local tmp="$TMP_DIR/motd" + local tmp="$TMP_DIR/motd" name uid home shell - # Clean old static banner from /etc/motd if present + # 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.viator-backup.$(date +%s)" install -m 0644 "$tmp" "$motd" fi - cat > /etc/profile.d/viator.sh <<'PROMPT' -# Viator / OpsBox system-wide interactive Bash banner & prompt. -case $- in *i*) ;; *) return ;; esac + # World-readable location (the config dir is root-only, so users could not source it). + mkdir -p "$THEME_DIR" + cat > "$THEME_DIR/theme.sh" <<'THEME' +# Viator login banner + prompt. Sourced from ~/.bashrc and /etc/profile.d/viator.sh. +[ -n "${BASH_VERSION:-}" ] || return 0 +case $- in *i*) ;; *) return 0 ;; esac -_opsbox_iface() { - local iface="$1" - if [ -d "/sys/class/net/$iface" ]; then - local state ip - state=$(tr '[:lower:]' '[:upper:]' < "/sys/class/net/$iface/operstate" 2>/dev/null) - ip=$(ip -4 -o addr show "$iface" 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n1) - if [ "$state" = "UP" ]; then - echo "UP${ip:+ ($ip)}" - else - echo "${state:-DOWN}" +__viator_rep() { + local n=$1 c=$2 s + [ "$n" -gt 0 ] || return 0 + printf -v s '%*s' "$n" '' + printf '%s' "${s// /$c}" +} + +__viator_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 + if [ -e "$p/device" ] || [ -d "$p/wireless" ]; then printf '%s\n' "$n" + else case $n in wg*|tun*|tailscale*) printf '%s\n' "$n" ;; esac fi + done +} + +__viator_banner() { + local W=64 user now src prev lastf ifc ip status row + user=$(id -un 2>/dev/null || echo "${USER:-unknown}") + now=$(date '+%a %d %b %H:%M') + if [ -n "${SSH_CONNECTION:-}" ]; then + src="ssh ${SSH_CONNECTION%% *}" else - echo "N/A" + src=$(tty 2>/dev/null || true) + case $src in ""|"not a tty") src="local" ;; *) src=${src#/dev/} ;; esac fi + # Own bookkeeping: works whether or not wtmp/lastlog exist on this distro. + lastf="${HOME:-/tmp}/.viator_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 + + printf '.-[ VIATOR ]%s.\n' "$(__viator_rep $((W - 13)) -)" + printf '| %-*s |\n' $((W - 4)) "$(printf 'ACCESS: %s // LAST: %s' "${user^^}" "$prev" | cut -c1-$((W - 4)))" + printf '| %-*s |\n' $((W - 4)) "" + local any=0 + for ifc in $(__viator_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"; else status="DISCONNECTED"; ip=""; fi + row=$(printf '%-10s %-14s %s' "$ifc" "$status" "$ip") + printf '| %-*s |\n' $((W - 4)) "$(printf '%s' "$row" | cut -c1-$((W - 4)))" + done + [ "$any" = 1 ] || printf '| %-*s |\n' $((W - 4)) "no network adapters found" + printf '`%s[░▒▓█]------'"'"'\n' "$(__viator_rep $((W - 14)) -)" } -_opsbox_banner() { - local host_node curr_user primary_ip eth0_stat wifi0_stat wifi1_stat last_log - host_node=$(hostname -s 2>/dev/null || echo "LOCALHOST") - curr_user=$(whoami) - primary_ip=$(hostname -I 2>/dev/null | awk '{print $1}') - primary_ip=${primary_ip:-"127.0.0.1"} - - eth0_stat=$(_opsbox_iface "eth0") - wifi0_stat=$(_opsbox_iface "wifi0") - wifi1_stat=$(_opsbox_iface "wifi1") - - [ "$wifi0_stat" = "N/A" ] && [ -d "/sys/class/net/wlan0" ] && wifi0_stat=$(_opsbox_iface "wlan0") - [ "$wifi1_stat" = "N/A" ] && [ -d "/sys/class/net/wlan1" ] && wifi1_stat=$(_opsbox_iface "wlan1") - - last_log=$(last -n 2 -w "$curr_user" 2>/dev/null | awk 'NR==2 {print $4" "$5" "$6" "$7" ("$3")"}') - last_log=${last_log:-"FIRST_SESSION // TTY"} - - printf ".-[ 0PSB0X ]--------------------------------------------------.\n" - printf "|:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::|\n" - printf "| >> SYSTEM : %-16s // [STATUS: 0NL1N3] |\n" "$host_node" - printf "| >> ACCESS : %-16s // IP: %-21s |\n" "${curr_user^^}" "$primary_ip" - printf "| >> ETH0 : %-44s |\n" "$eth0_stat" - printf "| >> WIFI0 : %-44s |\n" "$wifi0_stat" - printf "| >> WIFI1 : %-44s |\n" "$wifi1_stat" - printf "| >> LAST : %-44s |\n" "$last_log" - printf "\`-------------------------------------------------[░▒▓█]------'\n" +__viator_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}\\$ " } -_opsbox_banner -unset -f _opsbox_banner _opsbox_iface +if [ -z "${VIATOR_BANNER_SHOWN:-}" ]; then + export VIATOR_BANNER_SHOWN=1 + __viator_banner +fi +__viator_prompt +unset -f __viator_banner __viator_prompt __viator_ifaces __viator_rep +THEME + chmod 0755 "$THEME_DIR" + chmod 0644 "$THEME_DIR/theme.sh" -LINES="\[\e[36m\]" -[ "$EUID" -eq 0 ] && LINES="\[\e[91m\]" -USERHOST="\[\e[33m\]" -DIRECTORY="\[\e[97m\]" -ENDCOLOR="\[\e[m\]" -PS1="${LINES}╭──(${USERHOST}\u${LINES}@${USERHOST}\h${LINES})-[${DIRECTORY}\w${LINES}]${ENDCOLOR}\n${LINES}╰─${ENDCOLOR}\$ " -PROMPT + # Login shells (ssh, console): banner + prompt. + cat > /etc/profile.d/viator.sh <<'PROFILE' +# Viator theme for login shells (the prompt is also applied from ~/.bashrc). +if [ -r /usr/local/share/viator/theme.sh ]; then . /usr/local/share/viator/theme.sh; fi +PROFILE chmod 0644 /etc/profile.d/viator.sh + + # ~/.bashrc normally redefines PS1 AFTER /etc/profile.d, which is why a profile.d-only + # theme never showed up for existing users or root. Hook the end of every bashrc. + 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 '\|# >>> viator theme >>>|,\|# <<< viator theme <<<|d' "$rc" + cat >> "$rc" <<'HOOK' + +# >>> viator theme >>> +if [ -r /usr/local/share/viator/theme.sh ]; then . /usr/local/share/viator/theme.sh; fi +# <<< viator theme <<< +HOOK + if [[ "$new" == yes ]]; then chown --reference="$(dirname "$rc")" "$rc" || true; fi + return 0 } install_wireguard() { - apt_install wireguard + apt_install wireguard || return 1 mkdir -p /etc/wireguard chmod 0700 /etc/wireguard if [[ ! -s /etc/wireguard/wg0.conf ]]; then if ask_yes "No /etc/wireguard/wg0.conf exists. Open an editor to create it now?"; then local editor="${EDITOR:-nano}" - has_cmd "$editor" || apt_install nano + has_cmd "$editor" || apt_install nano || return 1 "$editor" /etc/wireguard/wg0.conf fi fi @@ -372,52 +1057,37 @@ install_wireguard() { } install_fallback_ap() { - apt_install curl - local conf=/etc/fallback-ap.conf ssid password iface cidr start end monitor ignore mode targets - [[ -f "$conf" ]] && source "$conf" - ssid="$(ask_input "Fallback AP" "Wi-Fi SSID:" "${FALLBACK_AP_SSID:-$(hostname)}")" || return 1 - password="$(ask_password "Fallback AP" "Wi-Fi password (8+ characters):" "${FALLBACK_AP_PASSWORD:-}")" || return 1 - ((${#password} >= 8)) || { msg "Wi-Fi password must be at least 8 characters."; return 1; } - iface="$(iw dev 2>/dev/null | awk '$1=="Interface"{print $2;exit}')" - iface="$(ask_input "Fallback AP" "Wireless interface:" "${FALLBACK_AP_IFACE:-${iface:-wlan0}}")" || return 1 - cidr="$(ask_input "Fallback AP" "AP address/CIDR:" "${FALLBACK_AP_CIDR:-10.10.10.1/24}")" || return 1 - start="$(ask_input "Fallback AP" "DHCP start octet:" "${FALLBACK_AP_DHCP_START_OCTET:-100}")" || return 1 - end="$(ask_input "Fallback AP" "DHCP end octet:" "${FALLBACK_AP_DHCP_END_OCTET:-250}")" || return 1 - monitor="$(ask_input "Fallback AP" "Monitor interface (blank = all):" "${FALLBACK_AP_MONITOR_IFACE:-}")" || return 1 - ignore="$(ask_input "Fallback AP" "Ignore interface (blank = none):" "${FALLBACK_AP_IGNORE_IFACE:-}")" || return 1 - mode="$(whiptail --title "Fallback AP" --radiolist "Connectivity check mode:" 12 70 2 link "Check link state" ON internet "Check internet access" OFF 3>&1 1>&2 2>&3)" || return 1 - targets="${FALLBACK_AP_CHECK_TARGETS:-1.1.1.1 8.8.8.8}" - [[ "$mode" == internet ]] && targets="$(ask_input "Fallback AP" "Internet check targets:" "$targets")" || true + apt_install curl || return 1 + local conf=/etc/fallback-ap.conf cat > "$conf" </dev/null; then - apt_install wayvnc + apt_install wayvnc || return 1 mkdir -p /etc/wayvnc if [[ ! -f /etc/wayvnc/config ]]; then cat > /etc/wayvnc/config <<'VNC' @@ -433,7 +1103,7 @@ VNC systemctl enable wayvnc 2>/dev/null || true systemctl restart wayvnc 2>/dev/null || warn "WayVNC package installed, but no system service was found. Configure it for the active desktop session." elif [[ "$session" == x11 ]]; then - apt_install tigervnc-standalone-server + apt_install tigervnc-standalone-server || return 1 warn "TigerVNC installed. Configure a per-user VNC session; no desktop login password was changed." else warn "No active graphical session detected. VNC requires a desktop (Wayland/labwc or X11); nothing was exposed." @@ -441,19 +1111,20 @@ VNC fi } +# ---- Docker (mandatory) --------------------------------------------------------------- install_docker_engine() { - apt_install ca-certificates curl gnupg qemu-user-static rsync + apt_install ca-certificates curl gnupg qemu-user-static 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" - sh "$TMP_DIR/get-docker.sh" + 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/" + 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." @@ -461,7 +1132,7 @@ install_docker_engine() { fi fi local daemon=/etc/docker/daemon.json - python3 - "$daemon" "$DATA_ROOT/engine" <<'PY' + python3 - "$daemon" "$DATA_ROOT/engine" <<'PY' || return 1 import json, os, sys, tempfile path, root = sys.argv[1:] data = {} @@ -472,11 +1143,34 @@ 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 + systemctl enable --now docker || return 1 + systemctl restart docker || return 1 docker network inspect viator_proxy >/dev/null 2>&1 || docker network create viator_proxy >/dev/null usermod -aG docker "$ADMIN_USER" } +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 viator_proxy >/dev/null 2>&1 || docker network create viator_proxy >/dev/null @@ -484,6 +1178,13 @@ install_caddy() { VIATOR_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 @@ -496,53 +1197,6 @@ export_caddy_ca() { else warn "Caddy's local root CA is not available yet; export it after the first HTTPS route is active."; fi } -# Bettercap runs with host networking, so it needs its own listen-address/port -# settings. Caddy's routes for it live in docker/caddy.yml, which is why this is -# asked before Caddy is (re)started. -configure_bettercap_net() { - local sub api addr ui api_port origin - BETTERCAP_UI_PORT="${BETTERCAP_UI_PORT:-1600}" - BETTERCAP_API_PORT="${BETTERCAP_API_PORT:-8081}" - if [[ "$USE_CADDY" == yes ]]; then - sub="$(ask_input "Bettercap UI" "Subdomain (served as .$VIATOR_DOMAIN):" "${VIATOR_SUB_BETTERCAP:-bettercap}")" || return 1 - api="$(ask_input "Bettercap API" "API subdomain (served as .$VIATOR_DOMAIN):" "${VIATOR_SUB_BETTERCAP_API:-api.bettercap}")" || return 1 - sub="${sub,,}"; api="${api,,}" - valid_sub "$sub" && valid_sub "$api" || { msg "Invalid subdomain."; return 1; } - VIATOR_SUB_BETTERCAP="$sub"; VIATOR_SUB_BETTERCAP_API="$api" - BETTERCAP_UI_ADDR="" # empty -> Docker gateway (only reachable through Caddy) - BETTERCAP_ALLOW_ORIGIN="" # empty -> https://. - else - addr="$(ask_input "Bettercap" "Address for the UI/API to listen on (0.0.0.0 = all interfaces):" "${BETTERCAP_UI_ADDR:-0.0.0.0}")" || return 1 - ui="$(ask_input "Bettercap" "UI port:" "$BETTERCAP_UI_PORT")" || return 1 - api_port="$(ask_input "Bettercap" "API port:" "$BETTERCAP_API_PORT")" || return 1 - valid_port "$ui" && valid_port "$api_port" || { msg "Invalid port."; return 1; } - origin="$(ask_input "Bettercap" "Public URL of the UI (CORS origin for the API, e.g. https://bettercap.example.com):" "${BETTERCAP_ALLOW_ORIGIN:-http://$(hostname):$ui}")" || return 1 - BETTERCAP_UI_ADDR="$addr"; BETTERCAP_UI_PORT="$ui"; BETTERCAP_API_PORT="$api_port" - BETTERCAP_ALLOW_ORIGIN="$origin" - fi - save_env VIATOR_SUB_BETTERCAP VIATOR_SUB_BETTERCAP_API BETTERCAP_UI_ADDR BETTERCAP_UI_PORT BETTERCAP_API_PORT BETTERCAP_ALLOW_ORIGIN -} - -configure_docker() { - local engine=no caddy=no domain - if ask_yes "Install or configure Docker Engine? (Required for container packages)"; then engine=yes; fi - if ask_yes "Networking mode\n\nYES = Install Caddy: services get . names with internal HTTPS certificates (no existing reverse proxy).\n\nNO = I already have a reverse proxy: services are published on host ports for it to forward to."; then caddy=yes; fi - USE_CADDY="$caddy" - if [[ "$USE_CADDY" == yes ]]; then - domain="$(ask_input "Domain" "Base domain for local HTTPS hostnames (services become .):" "$VIATOR_DOMAIN")" || return 1 - domain="${domain,,}" - valid_sub "$domain" || { msg "Invalid domain: '$domain'"; return 1; } - VIATOR_DOMAIN="$domain" - save_env VIATOR_DOMAIN - fi - save_env USE_CADDY - if contains pentest; then configure_bettercap_net || return 1; fi - if [[ "$engine" == yes || "$caddy" == yes ]] || needs_docker; then - install_docker_engine || return 1 - fi - if [[ "$USE_CADDY" == yes ]]; then install_caddy || return 1; fi -} - compose_stack() { local name="$1" file="$2" envfile="" shift 2 @@ -554,15 +1208,12 @@ compose_stack() { VIATOR_DATA_ROOT="$DATA_ROOT" "${args[@]}" "$@" up -d } -install_speedtest() { - expose SPEEDTEST "LibreSpeed" speedtest 1900 LIBRESPEED_BIND LIBRESPEED_PORT no || return 1 - compose_stack librespeed docker/librespeed.yml "$ENV_FILE" -} +# ---- container services --------------------------------------------------------------- +install_speedtest() { compose_stack librespeed docker/librespeed.yml "$ENV_FILE"; } install_opentak() { - apt_install curl openssl - local dir="$DATA_ROOT/opentak" svc k - expose OPENTAK "OpenTAK Server (web UI)" tak 8090 OTS_WEB_BIND OTS_WEB_PORT no || return 1 + apt_install curl openssl || return 1 + local dir="$DATA_ROOT/opentak" svc mkdir -p "$dir" # Retire the old GoATAK stack if present (its data in $DATA_ROOT/atak is left untouched). @@ -578,8 +1229,6 @@ install_opentak() { [[ -n "$svc" ]] || { err "Could not detect the OpenTAKServer service in $dir/docker-compose.yml"; return 1; } log "Detected OpenTAKServer service: $svc" - # Mirror the settings the override needs into the project's own .env so a manual - # `docker compose up` in $dir behaves the same as the installer. env_put "$dir/.env" OTS_WEB_BIND "$OTS_WEB_BIND" env_put "$dir/.env" OTS_WEB_PORT "$OTS_WEB_PORT" env_put "$dir/.env" VIATOR_DOMAIN "$VIATOR_DOMAIN" @@ -614,50 +1263,17 @@ OVERRIDE } install_maps() { - local photon tiles satellite vector contours url - apt_install unzip - photon=no; tiles=no; satellite=no; vector=no; contours=no - ask_yes "Install Photon geocoder? (~69 GB)" && photon=yes || true - ask_yes "Install TileServer GL?" && tiles=yes || true - - # Networking first, so a bad answer fails before any multi-GB download starts. - expose MAPS "Cartomake (map UI)" maps 8020 CARTOMAKE_BIND CARTOMAKE_PORT no || return 1 - if [[ "$photon" == yes ]]; then - expose GEOCODE "Photon geocoder" geocode 8022 PHOTON_BIND PHOTON_PORT yes || return 1 - fi - if [[ "$tiles" == yes ]]; then - expose TILES "TileServer GL" tiles 8021 TILESERVER_BIND TILESERVER_PORT yes || return 1 - fi - - if [[ "$tiles" == yes ]]; then - ask_yes "Download MapTiler Satellite dataset? (~186 GB; paste the download URL when prompted)" && satellite=yes || true - ask_yes "Download MapTiler Vector dataset? (~70 GB; paste the download URL when prompted)" && vector=yes || true - ask_yes "Download Contours dataset? (~18 GB; requires your hosted URL)" && contours=yes || true - fi - MAP_PHOTON="$photon"; MAP_TILESERVER="$tiles"; MAP_SATELLITE="$satellite"; MAP_VECTOR="$vector"; MAP_CONTOURS="$contours" - save_env MAP_PHOTON MAP_TILESERVER MAP_SATELLITE MAP_VECTOR MAP_CONTOURS - local map_required=0 map_available - [[ "$photon" == yes ]] && map_required=$((map_required + 69*1024*1024*1024)) - [[ "$satellite" == yes ]] && map_required=$((map_required + 186*1024*1024*1024)) - [[ "$vector" == yes ]] && map_required=$((map_required + 70*1024*1024*1024)) - [[ "$contours" == yes ]] && map_required=$((map_required + 18*1024*1024*1024)) - map_available="$(df -PB1 "$DATA_ROOT" | awk 'NR==2{print $4}')" - if ((map_required > 0)); then - msg "Selected map components need approximately $(zim_size_gb "$map_required") of storage, plus temporary download space. Available: $(zim_size_gb "$map_available")." - ((map_available >= map_required)) || return 1 - ask_yes "Continue with the selected map storage requirements?" || return 0 - fi + 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) [[ "$satellite" == yes ]] || continue;; vector) [[ "$vector" == yes ]] || continue;; contours) [[ "$contours" == yes ]] || continue;; esac case "$dataset" in - satellite) url="$(ask_input "MapTiler Satellite" "Paste the actual MapTiler download URL:" "")" || return 1;; - vector) url="$(ask_input "MapTiler Vector" "Paste the actual MapTiler download URL:" "")" || return 1;; - contours) url="$(ask_input "Contours" "Paste your hosted dataset URL:" "")" || return 1;; + 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 - [[ "$url" =~ ^https?:// ]] || { warn "Skipped $dataset: a valid HTTP(S) URL is required."; continue; } - local expected=0 available archive target - case "$dataset" in satellite) expected=$((186*1024*1024*1024));; vector) expected=$((70*1024*1024*1024));; contours) expected=$((18*1024*1024*1024));; esac - available="$(df -PB1 "$DATA_ROOT" | awk 'NR==2{print $4}')" + 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 @@ -670,9 +1286,9 @@ install_maps() { if ! unzip -oq "$archive" -d "$target"; then rm -f "$archive"; return 1; fi rm -f "$archive" else - local ext="${url%%\?*}"; ext="${ext##*.}" + ext="${url%%\?*}"; ext="${ext##*.}" if [[ "$ext" == mbtiles ]]; then mv "$archive" "$target/$dataset.mbtiles" - else mv "$archive" "$target/$(basename "$url")"; fi + else mv "$archive" "$target/$(basename "${url%%\?*}")"; fi fi done mkdir -p "$DATA_ROOT/maps/tileserver" @@ -686,40 +1302,29 @@ install_maps() { "$DATA_ROOT/maps/tileserver/styles/" fi local -a profiles=() - [[ "$photon" == yes ]] && profiles+=(--profile photon) - [[ "$tiles" == yes ]] && profiles+=(--profile tiles) + [[ "$MAP_PHOTON" == yes ]] && profiles+=(--profile photon) + [[ "$MAP_TILESERVER" == yes ]] && profiles+=(--profile tiles) compose_stack maps docker/maps.yml "$ENV_FILE" "${profiles[@]}" } -install_personal_cloud() { - expose HARNESS "AI Harness" home 8082 WEB_BIND HARNESS_PORT yes || return 1 - expose OFFICE "OnlyOffice" office 8083 WEB_BIND OFFICE_PORT yes || return 1 - local secret="${OFFICE_JWT_SECRET:-}" - [[ -n "$secret" ]] || secret="$(openssl rand -hex 32)" - OFFICE_JWT_SECRET="$secret" - save_env OFFICE_JWT_SECRET - compose_stack personal-cloud docker/cloud.yml "$ENV_FILE" -} +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 - BETTERCAP_USER="$(ask_input "Bettercap" "Web UI username (separate from Linux login):" "${BETTERCAP_USER:-viator}")" || return 1 - BETTERCAP_PASSWORD="$(ask_password "Bettercap" "Set a strong Bettercap UI password (letters/numbers/dot/dash/underscore):" "")" || return 1 - [[ "$BETTERCAP_PASSWORD" =~ ^[A-Za-z0-9._-]{12,}$ ]] || { msg "Use 12+ characters: letters, numbers, dot, dash or underscore."; return 1; } + nmap masscan reaver sqlmap tcpdump wireshark || return 1 VIATOR_DOCKER_GATEWAY="$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}' 2>/dev/null || true)" VIATOR_DOCKER_GATEWAY="${VIATOR_DOCKER_GATEWAY:-172.17.0.1}" - save_env BETTERCAP_USER BETTERCAP_PASSWORD VIATOR_DOCKER_GATEWAY - curl -fsSL https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfinstall.erb -o "$TMP_DIR/msfinstall" + save_env VIATOR_DOCKER_GATEWAY + curl -fsSL https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfinstall.erb -o "$TMP_DIR/msfinstall" || return 1 chmod 0700 "$TMP_DIR/msfinstall" - "$TMP_DIR/msfinstall" + "$TMP_DIR/msfinstall" || return 1 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 + apt_install rtl-sdr usbutils || return 1 cat > /etc/modprobe.d/viator-rtlsdr.conf <<'BLACKLIST' # Managed by Viator: keep the kernel DVB driver off RTL-SDR dongles so SDR apps can claim them. blacklist dvb_usb_rtl28xxu @@ -739,261 +1344,101 @@ BLACKLIST } install_openwebrx() { - prepare_rtlsdr_host - expose SDR "OpenWebRX+ (SDR receiver)" sdr 8073 OPENWEBRX_BIND OPENWEBRX_PORT no || return 1 - OPENWEBRX_ADMIN_USER="$(ask_input "OpenWebRX+" "Admin username:" "${OPENWEBRX_ADMIN_USER:-admin}")" || return 1 - [[ "$OPENWEBRX_ADMIN_USER" =~ ^[a-z][a-z0-9_-]*$ ]] || { msg "Username must be lowercase letters, numbers, dash or underscore."; return 1; } - OPENWEBRX_ADMIN_PASSWORD="$(ask_password "OpenWebRX+" "Admin password (12+ chars: letters/numbers/dot/dash/underscore):" "${OPENWEBRX_ADMIN_PASSWORD:-}")" || return 1 - [[ "$OPENWEBRX_ADMIN_PASSWORD" =~ ^[A-Za-z0-9._-]{12,}$ ]] || { msg "Use 12+ characters: letters, numbers, dot, dash or underscore."; return 1; } - OPENWEBRX_IMAGE="${OPENWEBRX_IMAGE:-slechev/openwebrxplus-softmbe:latest}" - save_env OPENWEBRX_ADMIN_USER OPENWEBRX_ADMIN_PASSWORD OPENWEBRX_IMAGE + 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/openwebrx docker/sdr.yml "$ENV_FILE" } -install_sdr() { - local owx=no noads=no rtl=no - ask_yes "Install OpenWebRX+ (general SDR receiver with extra digital decoders)?" && owx=yes || true - ask_yes "Install ADS-B receiver and tar1090?" && noads=yes || true - ask_yes "Install RTL_433 sensor decoder?" && rtl=yes || true - if [[ "$owx" == yes && "$noads" == yes ]] || [[ "$owx" == yes && "$rtl" == yes ]] || [[ "$noads" == yes && "$rtl" == yes ]]; then - if ! ask_yes "One RTL-SDR cannot be used by multiple services simultaneously. Continue anyway? You will need separate receivers or configure only one service to use the HAT tuner."; then return 1; fi - fi - SDR_OPENWEBRX="$owx" SDR_ADSB="$noads" SDR_RTL433="$rtl" - save_env SDR_OPENWEBRX SDR_ADSB SDR_RTL433 - local rc=0 - if [[ "$owx" == yes ]]; then install_openwebrx || rc=1; fi - if [[ "$noads" == yes || "$rtl" == yes ]]; then - local -a profiles=() - [[ "$noads" == yes ]] && profiles+=(--profile adsb) - [[ "$rtl" == yes ]] && profiles+=(--profile rtl433) - compose_stack sdr docker/sdr.yml "$ENV_FILE" "${profiles[@]}" || rc=1 - fi - return "$rc" +install_sdr_decoders() { + prepare_rtlsdr_host || return 1 + local -a profiles=() + contains adsb && profiles+=(--profile adsb) || true + contains rtl433 && profiles+=(--profile rtl433) || true + compose_stack sdr docker/sdr.yml "$ENV_FILE" "${profiles[@]}" } install_ai() { - apt_install curl ca-certificates - local dir="$DATA_ROOT/ai" repo user - dir="$(ask_input "Local AI" "Install directory:" "$dir")" || return 1 - repo="$(ask_input "Local AI" "Hugging Face model repository:" "litert-community/gemma-4-E2B-it-litert-lm")" || return 1 - user=viator-ai + apt_install curl ca-certificates || return 1 + local dir="$AI_DIR" repo="$AI_REPO" user=viator-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" - env UV_INSTALL_DIR=/usr/local/bin sh "$TMP_DIR/uv-install.sh" + 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" - if ask_yes "Download/import $repo now? Model downloads can be several GB."; then - runuser -u "$user" -- bash -lc "cd '$dir' && .venv/bin/litert-lm import --from-huggingface-repo '$repo'" + 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." } install_hat() { - apt_install git i2c-tools minicom util-linux-extra gpsd gpsd-clients chrony pps-tools rtl-sdr - local model="$(tr -d '\0' /dev/null || true)" - local pi5=no + apt_install git i2c-tools minicom util-linux-extra gpsd gpsd-clients chrony pps-tools rtl-sdr || return 1 + local model pi5=no + model="$(tr -d '\0' /dev/null || true)" [[ "$model" == *"Raspberry Pi 5"* ]] && pi5=yes local boot=/boot/firmware/config.txt cmd=/boot/firmware/cmdline.txt [[ -f "$boot" ]] || boot=/boot/config.txt [[ -f "$cmd" ]] || cmd=/boot/cmdline.txt - if ask_yes "Enable GPS UART and remove the Linux serial console from the kernel command line?"; then + 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 ask_yes "Enable LoRa SX1262 SPI1 overlay (SPI1-1CS)?"; then + 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 ask_yes "Enable HAT PCF85063A RTC? Do not select if a Pi/PiSugar RTC is already in use."; then + 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 ask_yes "Enable GPS PPS input on GPIO6? (Requires HAT switch SW1-2 ON.)"; then + if [[ "$HAT_PPS" == yes ]]; then grep -q '^dtoverlay=pps-gpio,gpiopin=6' "$boot" || echo 'dtoverlay=pps-gpio,gpiopin=6' >> "$boot" fi warn "Hardware overlays were written. Reboot is required. Meshtasticd radio-region and GPSD-to-Meshtastic PTY sharing are not configured automatically by this release." } -# Kiwix OPDS catalogue -> TSV: title, approximate bytes, acquisition URL. -fetch_zim_catalogue() { - local xml="$TMP_DIR/kiwix-opds.xml" tsv="$TMP_DIR/zims.tsv" - log "Fetching the live Kiwix OPDS catalogue..." >&2 - curl -fsSL --compressed --retry 3 'https://opds.library.kiwix.org/catalog/v2/entries?count=-1' -o "$xml" || return 1 - python3 - "$xml" "$tsv" <<'PY' -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='' - 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 href.lower().endswith('.zim')): - links.append(urljoin('https://opds.library.kiwix.org/', href)) - if not links: - for link in e.findall('a:link', ns): - href=link.get('href') or '' - if href and '.zim' in href.lower(): links.append(urljoin('https://opds.library.kiwix.org/', href)) - if links: - items.append((title, size or 0, links[0])) -with open(dst,'w',encoding='utf-8') as f: - for title,size,url in sorted(items,key=lambda x:x[0].casefold()): - clean=lambda s:str(s).replace('\t',' ').replace('\n',' ') - f.write(f'{clean(title)}\t{size}\t{clean(url)}\n') -PY - printf '%s' "$tsv" -} - -zim_size_gb() { - awk -v b="$1" 'BEGIN { if (b<=0) printf "unknown GB"; else printf "%.2f GB", b/1073741824 }' -} - install_zims() { - local catalog - catalog="$(fetch_zim_catalogue)" || { warn "Kiwix catalogue could not be downloaded."; return 1; } - local -a 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" - ) - local -a options=() selected=() - local spec name reason match line title bytes url gb id - for spec in "${wanted[@]}"; do - name="${spec%%|*}"; reason="${spec#*|}"; match="" - # Match title with a tolerant, case-insensitive substring search. - while IFS=$'\t' read -r title bytes url; do - if [[ "${title,,}" == *"${name,,}"* ]]; then match="$title"$'\t'"$bytes"$'\t'"$url"; break; fi - done < "$catalog" - if [[ -n "$match" ]]; then - IFS=$'\t' read -r title bytes url <<< "$match" - gb="$(zim_size_gb "$bytes")" - id="$(printf '%s' "$title" | tr -cs '[:alnum:]_-' '_' | cut -c1-40)" - options+=("$id" "$title ($gb): $reason" OFF) - else - id="manual_$(printf '%s' "$name" | tr -cs '[:alnum:]' '_')" - options+=("$id" "$name (size unknown): $reason [manual URL]" OFF) - fi - done - local chosen - chosen="$(whiptail --title "ZIM Archives" --checklist "Select archives to download. Entries are alphabetical. Existing files are skipped." 24 100 18 "${options[@]}" 3>&1 1>&2 2>&3)" || return 0 - read -r -a selected <<< "${chosen//\"/}" - ((${#selected[@]})) || return 0 - mkdir -p "$DATA_ROOT" - local required=0 - for id in "${selected[@]}"; do - while IFS=$'\t' read -r title bytes url; do - local safe="$(printf '%s' "$title" | tr -cs '[:alnum:]_-' '_')" - [[ "$safe" == "$id" ]] && required=$((required + bytes)) - done < "$catalog" - done - local available - available="$(df -PB1 "$DATA_ROOT" | awk 'NR==2{print $4}')" - if ((required > available)); then - msg "Not enough free space for the selected ZIMs. Required: $(zim_size_gb "$required"); available: $(zim_size_gb "$available")." - return 1 - fi - if ((required > 0)) && ! ask_yes "Selected ZIM downloads require about $(zim_size_gb "$required"). Continue?"; then return 0; fi + local slug title bytes url filename part v mkdir -p "$DATA_ROOT/zims" - local total=0 count=0 - for id in "${selected[@]}"; do - local found=no - for spec in "${wanted[@]}"; do - name="${spec%%|*}" - local key="$(printf '%s' "$name" | tr -cs '[:alnum:]' '_')" - if [[ "$id" == "manual_$key" ]]; then - url="$(ask_input "Manual ZIM URL" "Paste the official .zim download URL for $name:" "")" || continue - [[ "$url" =~ ^https?:// ]] || { warn "Invalid URL; skipping $name."; continue; } - local filename="$(basename "${url%%\?*}")" - [[ "$filename" == *.zim ]] || filename="$key.zim" - [[ -e "$DATA_ROOT/zims/$filename" ]] && { warn "$filename already exists; skipped."; continue; } - local 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: $name"); fi - found=yes; break - fi - done - [[ "$found" == yes ]] && continue - while IFS=$'\t' read -r title bytes url; do - local safe="$(printf '%s' "$title" | tr -cs '[:alnum:]_-' '_')" - if [[ "$safe" == "$id" ]]; then - local filename="$(basename "${url%%\?*}")" - [[ "$filename" == *.zim ]] || filename="$safe.zim" - if [[ -e "$DATA_ROOT/zims/$filename" ]]; then warn "$filename already exists; skipped."; else - log "Downloading $title ($(zim_size_gb "$bytes"))..." - local 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 - fi - break - fi - done < "$catalog" + 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 } -summary() { - local text=$'Selected components:\n' - if ((${#SELECTED[@]})); then - for x in "${SELECTED[@]}"; do text+=" • $x"$'\n'; done - else text+=$' (none)\n'; fi - text+=$'\n'"Data root: $DATA_ROOT"$'\n'"APT upgrade: $APT_UPGRADE"$'\n\n' - text+=$'Shared prerequisites: APT indexes, curl, Python 3, and Docker Engine for container stacks.\n\n' - text+="Review storage requirements before starting large map/ZIM downloads." - msg "$text" -} - +# ====================================================================================== main() { bootstrap "$@" init - ui - choose_components - configure_global - if [[ "$APT_UPGRADE" == yes ]]; then DEBIAN_FRONTEND=noninteractive apt-get upgrade -y; fi - summary - ask_yes "Begin installation? Existing data will be preserved; individual failures won't stop other components." || exit 0 - - # Docker + networking mode (Caddy vs. own reverse proxy) is decided once for all container apps. - if needs_docker; then - run_component "Docker" configure_docker + 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 @@ -1002,19 +1447,20 @@ main() { contains vnc && run_component "VNC" install_vnc || true contains ai && run_component "Local AI" install_ai || true contains hat && run_component "Wireless HAT" install_hat || true - contains pentest && run_component "Pen Test Suite" install_pentest || true - contains speedtest && run_component "LibreSpeed" install_speedtest || true - contains opentak && run_component "OpenTAK Server" install_opentak || true - contains maps && run_component "Maps" install_maps || true - contains personal-cloud && run_component "Personal Cloud" install_personal_cloud || true - contains sdr && run_component "SDR" install_sdr || true + contains pentest && run_docker_component "Pen Test Suite" install_pentest || true + contains speedtest && run_docker_component "LibreSpeed" install_speedtest || true + contains atak && run_docker_component "OpenTAK 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 openwebrx && run_docker_component "OpenWebRX+" install_openwebrx || true + if contains adsb || contains rtl433; then run_docker_component "SDR decoders" install_sdr_decoders; fi contains zims && run_component "ZIM Archives" install_zims || true - export_caddy_ca + [[ "$DOCKER_OK" == yes ]] && export_caddy_ca || true - local report=$'Installation finished.\n\nSucceeded:\n' - for x in "${SUCCEEDED[@]}"; do report+=" • $x"$'\n'; done + local x report=$'Installation finished.\n\nSucceeded:\n' + for x in "${SUCCEEDED[@]}"; do report+=" * $x"$'\n'; done report+=$'\nFailed:\n' - for x in "${FAILED[@]}"; do report+=" • $x"$'\n'; done + 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/viator/install-$(date +%F-%H%M%S).log"