diff --git a/.env.example b/.env.example index 1a0cd20..b3e2611 100644 --- a/.env.example +++ b/.env.example @@ -8,7 +8,7 @@ PGID=${PGID} MEDIA_DIRECTORY=${MEDIA_DIRECTORY} INSTALL_DIRECTORY=${INSTALL_DIRECTORY} -# jellyfin | emby | plex +# Supported core media server: jellyfin MEDIA_SERVICE=${MEDIA_SERVICE} # IANA timezone (e.g. Europe/Athens) @@ -28,13 +28,23 @@ WIREGUARD_ADDRESSES=${WIREGUARD_ADDRESSES} PORT_FORWARD_ONLY=${PORT_FORWARD_ONLY} VPN_PORT_FORWARDING=${VPN_PORT_FORWARDING} -# configure.sh API host +# Optional feature overlays +# y/n — VueTorrent alternate WebUI mod for qBittorrent +VUETORRENT_ENABLED=${VUETORRENT_ENABLED} +# none | intel | nvidia — hardware transcoding passthrough for Jellyfin +GPU_TRANSCODING=${GPU_TRANSCODING} +# y/n — Byparr Cloudflare solver wired into Prowlarr +BYPARR_ENABLED=${BYPARR_ENABLED} +# y/n — SABnzbd Usenet downloader wired into Sonarr/Radarr/Prowlarr +USENET_ENABLED=${USENET_ENABLED} + +# config.sh API host (127.0.0.1 locally or LAN IP) API_HOST=${API_HOST} # seerr-gateway: 1 = DELETE /request cancels in-flight *arr/qB grabs (not library files). # Set to 0 for stock Seerr (request row only). See docs/seerr-delete-request.md SEERR_DELETE_REQUEST_PURGE=1 -# media-purge-watch: 1 = inotify on library deletes (Jellyfin/*arr file remove → qB). +# media-purge-watch: 1 = inotify on library deletes (Jellyfin/*arr file remove -> qB/SABnzbd). # Set to 0 to disable the watcher (CustomScript + seerr-gateway purge still run). MEDIA_PURGE_WATCH=1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c647d0e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +on: + push: + branches: [main, dev] + pull_request: + branches: [main, dev] + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install lint and test dependencies + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends jq gettext-base shellcheck python3 + + - name: Check bash syntax & shellcheck & Python compile + env: + CI: "true" + run: bash tests/run.sh lint + + - name: Run unit tests (shell + Python unittest) + run: make test-unit + + - name: Validate Docker Compose overlays + run: make test-compose diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5c86be8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +## [Unreleased] — Stack Revival & Modular Hardening + +### Added +- **Four opt-in service overlays** (`compose/*.yaml`, selectable during manual setup or `assemblrr config edit`): + - `vuetorrent.yaml`: VueTorrent (`v2.37.0`) WebUI mod for qBittorrent (`VUETORRENT_ENABLED=y`). + - `gpu-intel.yaml` / `gpu-nvidia.yaml`: Intel/AMD VAAPI (`/dev/dri`) and NVIDIA NVENC hardware transcoding for Jellyfin (`GPU_TRANSCODING=intel|nvidia`). + - `byparr.yaml`: Byparr (`3.1.1`) Cloudflare challenge solver wired as a Prowlarr `FlareSolverr` proxy tagged `byparr` (`BYPARR_ENABLED=y`). + - `usenet.yaml`: SABnzbd (`5.1.3`) Usenet downloader wired automatically into Sonarr, Radarr, and Prowlarr via `lib/usenet.sh` (`USENET_ENABLED=y`). +- **Offline Usenet CI test harness**: `tests/fixtures/mock_nntp.py`, `tests/fixtures/mock_newznab.py`, and `tests/integration/usenet_mock_e2e.sh` (zero paid subscriptions required). +- **Komodo deployment documentation**: `docs/komodo.md`. +- **Legal & community docs**: `NOTICE`, `SECURITY.md`, `CONTRIBUTING.md`, `CHANGELOG.md`, SPDX license headers across scripts. +- **GitHub Actions CI**: `.github/workflows/ci.yml` (`bash -n`, `shellcheck`, `py_compile`, unit & compose validation). +- **Migration 004** (`migrations/004_jellyfin_12_and_stack_revival.sh`): prepares `config/sabnzbd`, backfills new feature flags, and prints upgrade notes for Jellyfin 12.4. + +### Changed +- **Upgraded core container image pins**: + - Jellyfin `10.11.11` -> `12.4ubu2604-ls60` (removed `--profile jellyfin` gate; migrated API auth headers from legacy `X-Emby-Token` to `Authorization: MediaBrowser`). + - qBittorrent `5.2.3` -> `5.3.0` + - Sonarr `4.0.19.2979-ls321` -> `4.0.20.3014-ls6` + - Radarr `6.3.0.10514-ls313` -> `7.0.3.10918-ls328` + - Prowlarr `2.5.2.5491-ls156` -> `3.0.2.5780-ls169` + - Bazarr `1.6.0` -> `1.6.2` + - Seerr `v3.4.1` -> `v3.5.2` + - Recyclarr `8.7.1` -> `8.8.1` + - Deunhealth pinned by immutable SHA-256 digest; Gateway Python bumped to `3.12.16-alpine`; sidecar base images bumped to `alpine:3.24.4`. +- **Core architecture modularized**: + - Split `lib/core.sh` into `log.sh`, `tty.sh`, `paths.sh`, `fs.sh`, `docker.sh`, `languages.sh` (keeping `lib/core.sh` as a backward-compatible facade). + - Split `lib/arr.sh` into `qbit.sh`, `arr_common.sh`, `arr_quality.sh`, `prowlarr.sh`, `arr_import.sh`, and extracted `lib/recyclarr.sh` (keeping `lib/arr.sh` as a facade). + - Removed broken Emby/Plex stubs from `compose/base.yaml` and core setup (moved reference examples into `compose/examples/custom.yaml.example` with non-colliding `.30+` IPs). + - Standardized multi-select `fzf` TUI controls (`Tab=toggle`, `Enter=confirm`), added `--preview` for Prowlarr indexers, and added version compatibility checks for older `fzf` releases (`0.29+`). +- **Upgrade engine**: added atomic pre-apply staging & rollback on Compose validation failure, self-re-exec after copying managed files, `.assemblrr-channel` persistence, and migration function isolation (`unset -f` before `source`). + +### Security & Bug Fixes +- **P0 — `scripts/seerr-gateway.py`**: fixed confused-deputy authorization bypass by verifying caller permissions via `GET /api/v1/auth/me` before invoking Radarr/Sonarr deletions; refused upstream 5xx fail-open behavior; added `GatewayConfig` DI and body size cap; extracted mock tests out of production script into `tests/unit/test_seerr_gateway_suite.py`. +- **P0 — `lib/config_edit.sh`**: fixed `_config_edit_all` missing `--reconfigure`, non-`fzf` picker menu output corrupting stdout capture, and quote escaping / `0600` permission preservation in `config_set_kv`. +- **P0 — `scripts/media-purge.sh`**: fixed `--tmdb`/`--tvdb` re-exec dropping `--dry-run`/`--qb-only`, tightened `qb_match_season_jq` lookahead boundaries so audio codecs (`DTS5.1`) no longer trigger bogus seasons, switched to `Authorization: MediaBrowser` + `/ScheduledTasks` check, and added SABnzbd cleanup support. +- **P1 — `lib/paths.sh`, `lib/bazarr.sh`, `lib/prompts.sh`**: removed unsafe `eval`/`source` in `safe_source`, fixed `curl -F` injection risk via `--form-string`, removed borrowed OpenSubtitles API key, fixed Gluetun VPN slugs (`private internet access`, `ivpn`), and replaced Windows `wmic` with PowerShell `Get-PSDrive`. +- **P1 — Sidecars (`vpn-watchdog.sh`, `media-purge-watch.sh`, `jellyfin-refresh.sh`)**: added restart cooldown & active-swarm guard in `vpn-watchdog.sh`, upgrade-history recency window & whole-TV-show Sonarr hold checks in `media-purge-watch.sh`, and atomic lock reclamation in `jellyfin-refresh.sh`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e7e5f37 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# Contributing to assemblrr + +Thank you for contributing to assemblrr! + +## Repository Guidelines + +1. **Shell script conventions** + - Entrypoints (`bin/*.sh`, `scripts/*.sh`, `platform/linux/*.sh`) use `#!/usr/bin/env bash` or `#!/bin/bash` with `set -euo pipefail`. + - Sourced libraries (`lib/*.sh`) must **not** call `set -euo pipefail` globally, and every `lib/*.sh` module must include a `_ASSEMBLRR_*_SOURCED` idempotency guard and `# SPDX-License-Identifier: GPL-3.0-or-later`. + - Read interactive input with `read_prompt` / `read_masked` (`lib/tty.sh`), never raw `read -p` inside prompts/menus. + - Load config files via `safe_source` (`lib/paths.sh`). + - Do not modify Docker Compose pinned image tags without verifying upstream manifests and running full test validation. + +2. **Legal & Content Neutrality** + - Do **not** include real copyrighted titles, release group names, piracy domains, or third-party proprietary API keys in code, comments, documentation, or tests. + - Use clearly synthetic titles (`Alpha Film (2016)`, `Sample Show`) or public-domain/CC fixtures (`Big Buck Bunny`, Ubuntu ISO). + +3. **Running Checks Locally** + ```bash + make test-unit + make test-compose + python3 -m unittest discover -s tests/unit -p 'test_*.py' -v + bash tests/run.sh --lint + ``` + All tests must pass offline without external paid services or live piracy indexers. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..8599089 --- /dev/null +++ b/NOTICE @@ -0,0 +1,32 @@ +assemblrr — Third-Party Upstream Projects & Legal Notice +========================================================== + +assemblrr is licensed under the GNU General Public License v3.0 or later +(GPL-3.0-or-later). See LICENSE for the full license text. + +assemblrr is an orchestration and configuration tool only. It does NOT include, +host, distribute, index, or endorse copyrighted media content or unauthorized +sources. Users are solely responsible for configuring lawful indexers, media, +and subscriptions in their own deployments. + +This project automates and integrates with independent upstream open-source +applications and container images maintained by their respective authors: + + - Jellyfin https://jellyfin.org/ + - LinuxServer.io Images https://www.linuxserver.io/ + - Sonarr https://sonarr.tv/ + - Radarr https://radarr.video/ + - Prowlarr https://prowlarr.com/ + - Bazarr https://www.bazarr.dev/ + - Seerr https://github.com/seerr-team/seerr + - Recyclarr https://recyclarr.dev/ + - TRaSH Guides https://trash-guides.info/ + - qBittorrent https://www.qbittorrent.org/ + - VueTorrent https://github.com/VueTorrent/VueTorrent + - Gluetun https://github.com/qdm12/gluetun + - Deunhealth https://github.com/qdm12/deunhealth + - Byparr https://github.com/ThePhaseless/Byparr + - SABnzbd https://sabnzbd.org/ + +All trademarks, service names, and container images remain the property of +their respective owners. diff --git a/README.md b/README.md index ef933a4..83be7d0 100644 --- a/README.md +++ b/README.md @@ -4,45 +4,57 @@ [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE) [![Platform](https://img.shields.io/badge/Platform-Linux%20%7C%20WSL2-orange.svg)](#installation) -[![Stack](https://img.shields.io/badge/Stack-Jellyfin%20%2B%20*arr-green.svg)](#the-stack) +[![Stack](https://img.shields.io/badge/Stack-Jellyfin%2012.4%20%2B%20*arr-green.svg)](#the-stack) [![Discussions](https://img.shields.io/github/discussions/soulis-1256/assemblrr)](https://github.com/soulis-1256/assemblrr/discussions) -assemblrr is an automated setup and management suite for self-hosted media stacks. It provisions, wires, and maintains a complete ecosystem (media server, torrent client, indexers, request management, subtitles, and quality profiles) with zero manual work. +assemblrr is an automated setup and management suite for self-hosted media stacks. It provisions, wires, and maintains a complete ecosystem (media server, download clients, indexers, request portal, subtitles, quality profiles, and optional overlays) with minimal friction. -[Features](#features) • [The Stack](#the-stack) • [Installation](#installation) • [CLI Usage](#cli-usage) • [Default Ports](#service-ports) • [Documentation](#documentation) • [Development](#development) +[Features](#features) • [The Stack](#the-stack) • [Optional Overlays](#optional-overlays) • [Installation](#installation) • [CLI Usage](#cli-usage) • [Service Ports](#service-ports) • [Documentation](#documentation) • [Development](#development) --- ## Features -- **Guided Multi-Platform Setup:** Interactive installer for bare-metal Linux and Windows (via automated WSL2 bridging). -- **Automated Service Wiring:** Auto-configures and interconnects Radarr, Sonarr, Prowlarr, qBittorrent, Bazarr, Seerr, Recyclarr, and Jellyfin out of the box. -- **VPN-First Networking:** Built-in Gluetun integration routes download traffic through your VPN, complete with start-up validation and a stalled-routing watchdog. -- **Unified Operator CLI:** Manage the stack (`start`, `stop`, `restart`, `status`), change settings, take backups, and run updates directly from your terminal. -- **Hardlink-Optimized Storage:** Atomic moves and hardlink-friendly directory layout with automated TRaSH Guides quality profile sync via Recyclarr. -- **Granular Media Purge:** Single-command cleanup (`assemblrr purge`) that cleanly removes titles across *arr apps, the disk, and matching torrents simultaneously. -- **Disaster Recovery & Migration:** Rebuild your entire stack on a clean host directly from a backup archive via the setup wizard (`Restore` mode) or `assemblrr restore`. +- **Guided Multi-Platform Setup:** Interactive installer for bare-metal Linux and Windows (via automated WSL2 bridging), with Express, Manual, Reconfigure (`--reconfigure`), and Restore modes. +- **Automated Service Wiring:** Auto-configures and interconnects Radarr, Sonarr, Prowlarr, qBittorrent, Bazarr, Seerr, Recyclarr, and Jellyfin (`12.4+` with `Authorization: MediaBrowser` auth) — plus optional SABnzbd and Byparr. +- **VPN-First Networking:** Built-in Gluetun integration routes torrent traffic through your VPN with start-up validation and a cooldown-guarded routing watchdog (`vpn-watchdog`). +- **Unified Operator CLI:** Manage the stack (`start`, `stop`, `restart`, `status`, `health`, `config edit`, `config apply`, `upgrade`, `backup`, `restore`, `purge`, `uninstall`) from your terminal. +- **Safe Rollback Upgrades:** `assemblrr upgrade` backs up managed files, applies atomic staged updates + migrations, validates resolved Docker Compose config before stamping, and rolls back automatically if validation fails. +- **Hardlink-Optimized Storage:** Atomic moves and hardlink-friendly layout across `/data/torrents`, `/data/usenet`, and `/data/media`, plus TRaSH Guides profile sync via Recyclarr. +- **Authenticated Request-Delete Gateway:** `seerr-gateway` verifies caller permissions (`GET /api/v1/auth/me`) before draining in-flight downloads and cleaning library/season files safely. --- ## The Stack -assemblrr provides an officially supported, fully-automated **express stack**: +assemblrr provides an officially supported core stack with pinned container versions: | Service | Category | Default Port | Description | |---|---|---|---| -| **[Jellyfin](https://jellyfin.org/)** | Media Server | `8096` | Open-source media streaming platform | -| **[qBittorrent](https://www.qbittorrent.org/)** | Download Client | `8081` | Torrent client isolated behind VPN (or direct access) | +| **[Jellyfin](https://jellyfin.org/)** (`12.4`) | Media Server | `8096` | Open-source media streaming platform | +| **[qBittorrent](https://www.qbittorrent.org/)** (`5.3.0`) | Torrent Client | `8081` | Torrent client isolated behind VPN (or direct access) | | **[Sonarr](https://sonarr.tv/)** | TV Management | `8989` | Smart PVR & series download automation | | **[Radarr](https://radarr.video/)** | Movie Management | `7878` | Movie collection manager and automation | -| **[Prowlarr](https://prowlarr.com/)** | Indexer Sync | `9696` | Centralized indexer proxy syncing to *arr apps | -| **[Seerr](https://github.com/seerr-team/seerr)** | Request Management | `5055` | Media discovery and user request gateway | -| **[Bazarr](https://www.bazarr.media/)** | Subtitles | `6767` | Automatic subtitle downloader for Sonarr and Radarr | +| **[Prowlarr](https://prowlarr.com/)** | Indexer Sync | `9696` | Centralized indexer manager syncing to *arr apps | +| **[Seerr](https://github.com/seerr-team/seerr)** | Request Portal | `5055` | Media discovery & requests behind authenticating `seerr-gateway` | +| **[Bazarr](https://www.bazarr.media/)** | Subtitles | `6767` | Automatic subtitle manager for Sonarr and Radarr | | **[Recyclarr](https://recyclarr.dev/)** | Quality Profiles | — | Syncs recommended TRaSH Guides quality profiles & custom formats | -| **[Gluetun](https://github.com/qdm12/gluetun)** *(Optional)* | VPN & Killswitch | — | Secure VPN tunnel with health watchdog for download traffic | +| **[Gluetun](https://github.com/qdm12/gluetun)** *(Optional)* | VPN & Killswitch | — | Secure VPN tunnel with `deunhealth` & `vpn-watchdog` | + +### Optional Overlays + +Enable during `Manual` setup or toggle anytime via `assemblrr config edit`: + +| Overlay File | Env Key | Description | +|---|---|---| +| [`compose/vuetorrent.yaml`](compose/vuetorrent.yaml) | `VUETORRENT_ENABLED=y` | Modern VueTorrent WebUI theme mod for qBittorrent *(default: enabled)* | +| [`compose/gpu-intel.yaml`](compose/gpu-intel.yaml) | `GPU_TRANSCODING=amd` / `intel` | AMD VAAPI / Intel QSV (`/dev/dri`) hardware transcoding + Jellyfin auto-wiring | +| [`compose/gpu-nvidia.yaml`](compose/gpu-nvidia.yaml) | `GPU_TRANSCODING=nvidia` | NVIDIA NVENC/NVDEC GPU reservation + Jellyfin auto-wiring *(auto-enabled when detected)* | +| [`compose/byparr.yaml`](compose/byparr.yaml) | `BYPARR_ENABLED=y` | Byparr Cloudflare solver wired into Prowlarr (`byparr` tag) | +| [`compose/usenet.yaml`](compose/usenet.yaml) | `USENET_ENABLED=y` | SABnzbd (`8085`) wired into Sonarr, Radarr, and Prowlarr (requires your own NNTP account) | > [!TIP] -> **Custom & Extended Services:** You can easily add custom containers (e.g. Plex, Emby, SABnzbd, Portainer) via `compose/custom.yaml` or optional compose profiles. Official automated wiring and CLI maintenance workflows target the core stack above. +> Need self-managed extras (Plex, Emby, Lidarr, Komodo Periphery)? Copy [`compose/examples/custom.yaml.example`](compose/examples/custom.yaml.example) to `compose/custom.yaml`. Custom services use `.30+` IPs on `assemblrr_network` and are left untouched by upgrades. --- @@ -50,202 +62,151 @@ assemblrr provides an officially supported, fully-automated **express stack**: ### Linux / WSL2 -Run the one-line bootstrap installer in your terminal (requires `bash` and `curl`): - ```bash bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh) ``` ### Windows (PowerShell) -Ensure Docker Desktop is running, then launch PowerShell as Administrator and run: +Ensure Docker Desktop is running with WSL2 integration enabled, then run PowerShell and execute: ```powershell irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex ``` -> [!NOTE] -> The Windows installer automatically bridges the stack into your default WSL2 Linux distribution. - ### Advanced Options -#### Fish Shell - -```fish -bash (curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh | psub) -``` - -#### Custom Branch or Tag - -**Linux / WSL2:** +**Custom branch, tag, or commit SHA:** ```bash bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh) --ref dev -# or: -ASSEMBLRR_REF=dev bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh) ``` - -**Windows (PowerShell):** ```powershell $env:ASSEMBLRR_REF = "dev"; irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex ``` -#### Restore on a Clean Host from Backup - -To rebuild your entire stack on a fresh host from an existing backup archive, run the bootstrap installer and select `3) Restore`, or pass the `--restore` flag: - -**Linux / WSL2:** +**Restore on a clean host from backup:** ```bash bash <(curl -fsSL https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/linux/bootstrap.sh) --restore /path/to/assemblrr-backup.tar.gz ``` -**Windows (PowerShell):** -```powershell -irm https://raw.githubusercontent.com/soulis-1256/assemblrr/main/platform/windows/bootstrap.ps1 | iex -ArgumentList "--restore", "C:\path\to\assemblrr-backup.tar.gz" -``` - > [!IMPORTANT] -> **Already installed?** Use `assemblrr upgrade` to update or `assemblrr uninstall` to remove. Do not re-run the bootstrap script on an existing installation. +> **Already installed?** Use `assemblrr upgrade` to update, `assemblrr config edit` to change settings/overlays, or `assemblrr uninstall` to remove. --- ## CLI Usage -Once installed, the `assemblrr` command-line interface is available on your system `PATH`: - ```bash assemblrr [options] ``` ### Stack Control - | Command | Description | |---|---| -| `assemblrr start [service]` | Start all services (or a specific service) with VPN verification | -| `assemblrr stop [service]` | Stop all running services (or a specific service) | -| `assemblrr restart [service]` | Restart all services (or a specific service) | -| `assemblrr destroy [service]` | Teardown and reset container state | +| `assemblrr start [service]` | Start all (or named) services and wait for readiness | +| `assemblrr stop [service]` | Stop running services | +| `assemblrr restart [service]` | Restart running services | +| `assemblrr destroy [service]` | Stop and remove containers/network (keeps config & media) | ### Status & Inspection - | Command | Description | |---|---| -| `assemblrr status` | Operator dashboard displaying service states, health, and access URLs | -| `assemblrr status --docker` | Raw `docker compose ps` output | -| `assemblrr health` | Compact health check pass/fail summary for all containers | -| `assemblrr logs [service]` | Tail and follow logs for all containers or a specific service | -| `assemblrr check-vpn` | Verify VPN connectivity, assigned IP, and tunnel health | - -### Configuration & Wiring +| `assemblrr status` | Operator dashboard displaying service states, health, and URLs | +| `assemblrr status --docker` | Raw `docker compose ps` table | +| `assemblrr health` | Compact health pass/fail check across catalog services | +| `assemblrr logs [service]` | Tail container logs | +| `assemblrr check-vpn` | Compare host exit IP against Gluetun tunnel IP | +### Configuration & Maintenance | Command | Description | |---|---| -| `assemblrr config` | List all available configuration options | -| `assemblrr config show` | Display active environment configuration | -| `assemblrr config edit` | Interactive wizard to update settings (VPN, indexers, credentials, etc.) | -| `assemblrr config apply` | Re-run automated service wiring (alias: `config wire`) | - -### Maintenance, Backups & Cleanup - -| Command | Description | -|---|---| -| `assemblrr backup ` | Create a timestamped configuration backup archive | -| `assemblrr restore ` | Restore configuration from a backup archive | -| `assemblrr update-containers` | Pull the latest Docker images and restart the stack (prompts for backup first) | -| `assemblrr upgrade` | Upgrade assemblrr core scripts, apply migrations, and update wiring | -| `assemblrr upgrade --check` | Dry-run: preview upcoming file changes and migrations | -| `assemblrr upgrade --skip-stack`| Apply CLI and script updates without restarting running containers | -| `assemblrr purge` | Delete a title across Sonarr/Radarr, filesystem, and active qBittorrent torrents | -| `assemblrr uninstall` | Cleanly remove the entire stack (preserves media unless `--media` is passed) | +| `assemblrr config show` | Show active configuration & resolved compose overlays | +| `assemblrr config edit` | Interactive picker for VPN, quality, overlays (VueTorrent/GPU/Byparr/Usenet), auth, etc. | +| `assemblrr config apply` | Re-run non-interactive service API wiring (`alias: config wire`) | +| `assemblrr upgrade` | Upgrade managed files, apply migrations, validate & rebuild stack (`--check`, `--from DIR`, `--ref REF`, `--skip-stack`) | +| `assemblrr update-containers` | Rebuild local sidecars and pull any custom overlay images | +| `assemblrr purge ...` | Remove a movie/series/season across *arr, library disk, qBittorrent, and SABnzbd | +| `assemblrr backup ` | Create a `0600` backup archive | +| `assemblrr restore ` | Validate archive and restore config/secrets | +| `assemblrr uninstall` | Clean removal (preserves media unless `--media` is passed) | --- ## Service Ports -When running the default stack, the following ports are mapped on `http://localhost:`: - -| Service | Port | Default URL | Purpose | +| Service | Host Port | Default URL | Notes | |---|---|---|---| | **Jellyfin** | `8096` | `http://localhost:8096` | Media streaming frontend | -| **qBittorrent** | `8081` | `http://localhost:8081` | Torrent Web UI | -| **Sonarr** | `8989` | `http://localhost:8989` | TV show manager | -| **Radarr** | `7878` | `http://localhost:7878` | Movie collection manager | -| **Prowlarr** | `9696` | `http://localhost:9696` | Indexer management | -| **Seerr** | `5055` | `http://localhost:5055` | Media request portal (via gateway) | +| **Seerr (Gateway)** | `5055` | `http://localhost:5055` | Media requests + delete-request purge | | **Bazarr** | `6767` | `http://localhost:6767` | Subtitle manager | +| **Sonarr** | `8989` | `http://localhost:8989` | TV show manager | +| **Radarr** | `7878` | `http://localhost:7878` | Movie manager | +| **Prowlarr** | `9696` | `http://localhost:9696` | Indexer manager | +| **qBittorrent** | `8081` | `http://localhost:8081` | Torrent Web UI (+ VueTorrent when enabled) | +| **SABnzbd** *(opt.)* | `8085` | `http://localhost:8085` | Usenet downloader (`USENET_ENABLED=y`) | --- ## Configuration & Layout -Configuration and persistent state live in your installation directory (default: `~/assemblrr`): - ```text ~/assemblrr/ -├── .env # Environment variables generated during setup (see .env.example) -├── secrets/ # Authenticated credentials and VPN keys (kept separate from .env) +├── .env # Environment variables generated by setup +├── .assemblrr-config # Install metadata + active UI/feature settings +├── .assemblrr-channel # Active upgrade git ref (default: main) +├── .assemblrr-version # Recorded upgrade version stamp +├── .assemblrr-migrations # Applied migration IDs +├── secrets/ # 0700 dir of 0600 service passwords & VPN keys ├── compose/ -│ ├── base.yaml # Core service definitions -│ ├── vpn.yaml # VPN network overlay (Gluetun) -│ ├── direct-access.yaml# Direct networking overlay (non-VPN) -│ └── custom.yaml # User-defined custom services -├── config/ # Persistent database and appdata for all services -└── scripts/ # Internal watchdog and gateway sidecar scripts +│ ├── base.yaml # Core service definitions +│ ├── vpn.yaml # Gluetun VPN network + watchdog overlay +│ ├── direct-access.yaml # Non-VPN overlay +│ ├── vuetorrent.yaml # Optional VueTorrent WebUI overlay +│ ├── gpu-intel.yaml # Optional Intel/AMD VAAPI GPU overlay +│ ├── gpu-nvidia.yaml # Optional NVIDIA NVENC GPU overlay +│ ├── byparr.yaml # Optional Byparr Cloudflare solver overlay +│ ├── usenet.yaml # Optional SABnzbd Usenet overlay +│ └── custom.yaml # User-defined custom services (untouched by upgrade) +├── config/ # Persistent service appdata +├── migrations/ # Idempotent upgrade migrations +└── scripts/ # Sidecar watchdog, purge & gateway hooks ``` --- ## Documentation -- **[TRaSH Guides & Quality Profiles](docs/trash-guides.md):** Quality profile synchronization and custom format handling. -- **[Seerr Delete Request](docs/seerr-delete-request.md):** In-flight download cancellation workflow and gateway architecture. -- **[Uninstall Guide](docs/uninstall.md):** Complete removal walkthrough and resource inventory. -- **[API Reference](docs/api-reference.md):** Upstream API endpoints and integration notes. +- **[TRaSH Guides & Quality Profiles](docs/trash-guides.md):** Quality profile sync and custom format notes. +- **[Seerr Delete Request](docs/seerr-delete-request.md):** Gateway RBAC auth, queue drain, and season-scoped purge architecture. +- **[Komodo Integration](docs/komodo.md):** Running and monitoring assemblrr stacks via Komodo. +- **[API Reference](docs/api-reference.md):** Jellyfin 12 `MediaBrowser` auth headers, *arr/SABnzbd/Byparr endpoints. +- **[Uninstall Guide](docs/uninstall.md):** Complete removal walkthrough and directory inventory. +- **[Security Policy](SECURITY.md) • [Contributing](CONTRIBUTING.md) • [Changelog](CHANGELOG.md) • [Legal Notice](NOTICE)** --- ## Development -### Setting Up a Development Environment - -**Linux / WSL2:** ```bash -git clone https://github.com/soulis-1256/assemblrr.git -cd assemblrr -bash bin/setup.sh +make test # Unit tests + compose validation + shellcheck lint +make test-unit # Offline shell + Python unit suites +make test-compose # Docker Compose validation across overlay matrix +make lint # Run shellcheck across shell scripts ``` -**Windows (PowerShell):** -```powershell -git clone https://github.com/soulis-1256/assemblrr.git -cd assemblrr -.\platform\windows\bootstrap-dev.ps1 -Full # Full setup (copies files to WSL2 and runs setup.sh) -.\platform\windows\bootstrap-dev.ps1 -Full -Clean # Clean install (uninstalls previous setup first) -.\platform\windows\bootstrap-dev.ps1 -Update # Fast sync for local script/CLI edits -``` - -### Running Tests - -```bash -make test # Run all unit tests, compose validation, and shellcheck -make test-unit # Pure shell unit tests (no Docker required) -make test-compose # Docker Compose syntax and configuration validation -make test-integration # Live integration tests (requires ASSEMBLRR_ALLOW_LIVE_TEST=1) -make lint # Run shellcheck on all scripts -``` - -See [tests/README.md](tests/README.md) for testing guidelines and environment flags. +See [tests/README.md](tests/README.md) for the test suite layout, including the offline NNTP/Newznab Usenet mock harness. --- ## Community & Legal -assemblrr is infrastructure automation tooling designed to wire together and manage self-hosted applications. It does not provide, index, host, or distribute media content. Users are solely responsible for complying with applicable laws and licensing regulations in their jurisdiction. +assemblrr is infrastructure automation tooling for self-hosted applications. It does **not** include, host, index, or distribute copyrighted media content or external subscriptions. Users are solely responsible for complying with applicable laws in their jurisdiction. See [NOTICE](NOTICE). -Join discussions, request features, and connect with the community on **[GitHub Discussions](https://github.com/soulis-1256/assemblrr/discussions)**. +Join discussions on **[GitHub Discussions](https://github.com/soulis-1256/assemblrr/discussions)**. --- -## Acknowledgments & License +## License -- Originally inspired by [YAMS](https://yams.media/) ([rogsme/yams](https://github.com/rogsme/yams)); assemblrr has since been completely re-architected and expanded into an independent platform. -- Licensed under the **[GNU General Public License v3.0](LICENSE)**. +- Inspired in early versions by [YAMS](https://yams.media/), now independently architected and modularized. +- Licensed under the **[GNU General Public License v3.0 or later](LICENSE)**. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..93735a7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,22 @@ +# Security Policy + +## Supported Versions + +Security fixes apply to the latest release on the `main` branch (`assemblrr upgrade`). + +## Reporting a Vulnerability + +Please do **not** open a public GitHub issue with exploit details for an unpatched vulnerability. + +Report security issues privately via GitHub Security Advisories or private contact with the repository maintainer (`soulis-1256`). Include: + +- Affected script, service overlay, or API endpoint +- Reproduction steps or minimal proof of concept +- Potential impact (e.g., credential exposure, privilege boundary bypass, command injection) + +## Security Architecture Highlights + +- **Secret isolation**: Service credentials and API tokens live under `secrets/` (`0700` directory, `0600` files), never embedded in `.env` or container compose YAML. +- **No `eval`/`source` on untrusted config**: Config files are loaded via `safe_source` (`lib/paths.sh`), which parses literal `KEY=VALUE` assignments line-by-line and rejects command substitution or code execution. +- **Authenticated request-delete gateway**: `scripts/seerr-gateway.py` resolves caller identity and permissions against `GET /api/v1/auth/me` before invoking privileged Sonarr/Radarr APIs and fails closed (`502`/`403`) on missing or unauthorized sessions. +- **Safe curl usage**: Secrets are passed via headers or `--form-string` rather than raw `-F` file/stdin triggers. diff --git a/bin/cli.sh b/bin/cli.sh old mode 100644 new mode 100755 index b38a5a4..35e290a --- a/bin/cli.sh +++ b/bin/cli.sh @@ -1,17 +1,17 @@ #!/bin/bash +# SPDX-License-Identifier: GPL-3.0-or-later +# assemblrr CLI — lives in the install tree (or repo bin/). PATH is a thin wrapper. set -euo pipefail -# assemblrr CLI — lives in the install tree (or repo bin/). PATH is a wrapper. - _cli_self="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# Leftover full copies in ~/.local/bin must not run; exec the install-tree CLI. +# Leftover full copies in ~/.local/bin must not run standalone; exec the install-tree CLI. if [ "$_cli_self" = "$HOME/.local/bin" ] || [ "$_cli_self" = "/usr/local/bin" ]; then _wrap_dir="${ASSEMBLRR_DIR:-}" if [ -z "$_wrap_dir" ]; then for _wrap_f in \ - /opt/assemblrr/.assemblrr-config \ "$HOME/.assemblrr-config" \ + /opt/assemblrr/.assemblrr-config \ "$HOME/assemblrr/.assemblrr-config" do if [ -f "$_wrap_f" ]; then @@ -31,7 +31,6 @@ if [ "$_cli_self" = "$HOME/.local/bin" ] || [ "$_cli_self" = "/usr/local/bin" ]; exit 1 fi -# Locate lib (repo: sibling of bin/; install: lib/ next to cli.sh) if [ -f "$_cli_self/../lib/core.sh" ]; then _lib_dir="$_cli_self/../lib" elif [ -f "$_cli_self/lib/core.sh" ]; then @@ -41,56 +40,30 @@ else exit 1 fi +# shellcheck source=/dev/null source "$_lib_dir/core.sh" +# shellcheck source=/dev/null source "$_lib_dir/branding.sh" +# shellcheck source=/dev/null source "$_lib_dir/compose.sh" -if [ -f "$_lib_dir/quality.sh" ]; then - source "$_lib_dir/quality.sh" -fi +# shellcheck source=/dev/null +[ -f "$_lib_dir/quality.sh" ] && source "$_lib_dir/quality.sh" +# shellcheck source=/dev/null source "$_lib_dir/vpn.sh" -if [ -f "$_lib_dir/services.sh" ]; then - source "$_lib_dir/services.sh" -fi -# Upgrade engine (optional on older installs until first upgrade copies these) -if [ -f "$_lib_dir/managed_files.sh" ]; then - source "$_lib_dir/managed_files.sh" -fi -if [ -f "$_lib_dir/upgrade.sh" ]; then - source "$_lib_dir/upgrade.sh" -fi +# shellcheck source=/dev/null +[ -f "$_lib_dir/services.sh" ] && source "$_lib_dir/services.sh" +# shellcheck source=/dev/null +[ -f "$_lib_dir/managed_files.sh" ] && source "$_lib_dir/managed_files.sh" +# shellcheck source=/dev/null +[ -f "$_lib_dir/upgrade.sh" ] && source "$_lib_dir/upgrade.sh" -INSTALL_DIR=$(find_install_directory) -if [ -z "$INSTALL_DIR" ]; then - log_error "Could not find ${APP_NAME:-assemblrr} installation. Run setup first." -fi - -# Pointer first — has MEDIA_DIRECTORY even when the install tree never finished -# (path picker chose /mnt/e, then copy hung). Install-dir config overrides. -load_install_pointer || true -if [ -f "$INSTALL_DIR/.assemblrr-config" ]; then - safe_source "$INSTALL_DIR/.assemblrr-config" -elif [ -f "$INSTALL_DIR/.${APP_NAME:-assemblrr}-config" ]; then - safe_source "$INSTALL_DIR/.${APP_NAME:-assemblrr}-config" -fi +# Default fallbacks (always initialized cleanly even under set -u) VPN_ENABLED="${VPN_ENABLED:-n}" VPN_TYPE="${VPN_TYPE:-openvpn}" MEDIA_SERVICE="${MEDIA_SERVICE:-jellyfin}" MEDIA_DIRECTORY="${MEDIA_DIRECTORY:-${HOME}/assemblrr-media}" TZ="${TZ:-UTC}" -# Source branding from install directory -load_branding "$INSTALL_DIR" 2>/dev/null || true - -# Build compose command dynamically (uses lib/compose.sh build_compose_args + adds profile) -if [ -f "$INSTALL_DIR/compose/base.yaml" ]; then - build_compose_args "$INSTALL_DIR" "${VPN_ENABLED:-n}" - DC=(run_docker compose "${COMPOSE_ARGS[@]}" "--profile" "${MEDIA_SERVICE:-jellyfin}") -else - # Mid-setup / incomplete tree — uninstall can still remove dirs and CLI - DC=(run_docker compose) - COMPOSE_ARGS=() -fi -# Cold start: Jellyfin/Bazarr start_period is 60s, then the first healthcheck. readonly WAIT_READY_SECONDS=180 readonly IP_ENDPOINTS=( "https://ipinfo.io/ip" @@ -98,92 +71,93 @@ readonly IP_ENDPOINTS=( "https://checkip.amazonaws.com" "https://tnedi.me" "https://api.myip.la" - "https://wtfismyip.com/text" ) -# Commands -declare -A COMMANDS=( - ["--help"]="displays this help message" - ["restart"]="restarts services (can specify service names)" - ["stop"]="stops all services (can specify service names)" - ["start"]="starts services (can specify service names)" - ["status"]="service dashboard (URLs + health); --docker for raw compose ps" - ["destroy"]="destroys services so you can start from scratch (can specify service names)" - ["uninstall"]="completely removes the stack (keeps media unless confirmed) — see docs/uninstall.md" - ["check-vpn"]="checks if the VPN is working as expected" - ["backup"]="backs up to the destination location" - ["restore"]="restores from a backup archive" - ["update-containers"]="updates all containers" - ["upgrade"]="upgrade install files from git (or --from DIR); runs migrations" - ["logs"]="shows container logs (optionally specify service name)" - ["health"]="checks health status of all services" - ["config"]="configuration: show, edit (picker), or apply (re-wire)" - ["purge"]="delete one title from *arr, disk, and qBittorrent" -) +log_error_inline() { echo -e "${RED:-}$1${NC:-}"; } -# log_error_inline — same as log_error but without exit (used by check_health) -log_error_inline() { echo -e "${RED}$1${NC}"; } +_cli_init() { + INSTALL_DIR=$(find_install_directory || true) + if [ -z "${INSTALL_DIR:-}" ]; then + log_error "Could not find ${APP_NAME:-assemblrr} installation. Run setup first." + return 1 + fi + load_install_pointer || true + if [ -f "$INSTALL_DIR/.assemblrr-config" ]; then + safe_source "$INSTALL_DIR/.assemblrr-config" + elif [ -f "$INSTALL_DIR/.${APP_NAME:-assemblrr}-config" ]; then + safe_source "$INSTALL_DIR/.${APP_NAME:-assemblrr}-config" + fi + if [ -f "$INSTALL_DIR/.env" ]; then + set -a + safe_source "$INSTALL_DIR/.env" + set +a + fi + VPN_ENABLED="${VPN_ENABLED:-n}" + VPN_TYPE="${VPN_TYPE:-openvpn}" + MEDIA_SERVICE="${MEDIA_SERVICE:-jellyfin}" + MEDIA_DIRECTORY="${MEDIA_DIRECTORY:-${HOME}/assemblrr-media}" + TZ="${TZ:-UTC}" -show_help() { - echo "${APP_DISPLAY_NAME} - ${APP_DESCRIPTION:-Your one-click media server}" - echo - echo "Usage: ${APP_CLI_NAME} [command] [options]" - echo - echo "Commands:" - for cmd in "${!COMMANDS[@]}"; do - printf "%-25s %s\n" "$cmd" "${COMMANDS[$cmd]}" - done - echo - echo "Examples:" - echo " ${APP_CLI_NAME} start # Start all services" - echo " ${APP_CLI_NAME} start jellyfin # Start the 'jellyfin' service" - echo " ${APP_CLI_NAME} stop jellyfin # Stop the 'jellyfin' service" - echo " ${APP_CLI_NAME} restart jellyfin # Restart the 'jellyfin' service" - echo " ${APP_CLI_NAME} destroy jellyfin # Destroy the 'jellyfin' service" - echo " ${APP_CLI_NAME} backup /path/to/backup # Backup to specified directory" - echo " ${APP_CLI_NAME} restore /path/to/backup.tar.gz # Restore from backup" - echo " ${APP_CLI_NAME} uninstall # Remove everything (asks before deleting data)" - echo " ${APP_CLI_NAME} uninstall --force # Remove without prompts (keeps media)" - echo " ${APP_CLI_NAME} uninstall --force --media # Remove everything including media" - echo " ${APP_CLI_NAME} logs # View all container logs" - echo " ${APP_CLI_NAME} logs jellyfin # View specific service logs" - echo " ${APP_CLI_NAME} health # Check health of all services" - echo " ${APP_CLI_NAME} upgrade # Upgrade from git main (backup first)" - echo " ${APP_CLI_NAME} upgrade --from DIR # Upgrade from a local source tree" - echo " ${APP_CLI_NAME} upgrade --check # Dry-run upgrade plan" - echo " ${APP_CLI_NAME} upgrade --skip-stack # Files + CLI only (no container restart)" - echo " ${APP_CLI_NAME} status # URLs + health for all services" - echo " ${APP_CLI_NAME} status --docker # Raw docker compose ps" - echo " ${APP_CLI_NAME} config # List config subcommands" - echo " ${APP_CLI_NAME} config show # Show current configuration" - echo " ${APP_CLI_NAME} config edit # Pick a setting to change" - echo " ${APP_CLI_NAME} purge --movie-id N # Full delete (*arr + disk + qB)" - echo " ${APP_CLI_NAME} purge --path PATH # Full delete by library path" - echo " ${APP_CLI_NAME} purge --tmdb ID # Full delete by TMDB id" + load_branding "$INSTALL_DIR" 2>/dev/null || load_branding "$_cli_self/.." 2>/dev/null || true + + if [ -f "$INSTALL_DIR/compose/base.yaml" ]; then + build_compose_args "$INSTALL_DIR" "${VPN_ENABLED:-n}" + DC=(run_docker compose "${COMPOSE_ARGS[@]}") + else + DC=(run_docker compose) + COMPOSE_ARGS=() + fi +} + +show_help() { + load_branding "$_cli_self/.." 2>/dev/null || true + echo "${APP_DISPLAY_NAME:-assemblrr} - ${APP_DESCRIPTION:-Automated media stack}" + echo + echo "Usage: ${APP_CLI_NAME:-assemblrr} [command] [options]" + echo + echo "Lifecycle:" + printf " %-26s %s\n" "start [service...]" "Start all (or named) services and wait for readiness" + printf " %-26s %s\n" "stop [service...]" "Stop all (or named) services" + printf " %-26s %s\n" "restart [service...]" "Restart all (or named) services" + printf " %-26s %s\n" "destroy [service...]" "Stop and remove containers/network (keeps config + media)" + printf " %-26s %s\n" "uninstall [--force] [--media]" "Remove containers, config, and CLI wrapper" + echo + echo "Configuration & Upgrades:" + printf " %-26s %s\n" "status [--docker]" "Operator service dashboard (URLs + health); --docker for raw compose ps" + printf " %-26s %s\n" "health" "Compact health pass/fail across expected stack services" + printf " %-26s %s\n" "config [show|edit|apply]" "Inspect config, edit settings interactively, or re-wire APIs" + printf " %-26s %s\n" "upgrade [options]" "Apply managed files, migrations, compose rebuild, and wiring (--check, --from DIR, --ref REF)" + printf " %-26s %s\n" "update-containers [-y]" "Rebuild local sidecars & pull unpinned custom overlay images" + echo + echo "Operations & Backups:" + printf " %-26s %s\n" "logs [service]" "Follow container logs" + printf " %-26s %s\n" "check-vpn" "Verify public exit IP vs VPN tunnel IP" + printf " %-26s %s\n" "purge [options]" "Remove one movie/series/season from *arr, library disk, and qB/SABnzbd" + printf " %-26s %s\n" "backup " "Create a 0600 backup archive in " + printf " %-26s %s\n" "restore " "Validate and restore stack config/secrets from " + echo + echo "Examples:" + echo " ${APP_CLI_NAME:-assemblrr} status" + echo " ${APP_CLI_NAME:-assemblrr} config edit" + echo " ${APP_CLI_NAME:-assemblrr} upgrade --check" + echo " ${APP_CLI_NAME:-assemblrr} purge --tmdb 10378 --dry-run" } -# Full media purge (*arr + qB + hardlinks). Thin wrapper around scripts/media-purge.sh purge_media() { - local install_dir script - install_dir=$(find_install_directory) + local install_dir="${INSTALL_DIR:-}" + local script + [ -n "$install_dir" ] || install_dir=$(find_install_directory || true) [ -n "$install_dir" ] || log_error "Could not find installation directory" script="$install_dir/scripts/media-purge.sh" - if [ ! -f "$script" ]; then - # Dev tree: repo scripts/ - local self_dir - self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - if [ -f "$self_dir/../scripts/media-purge.sh" ]; then - script="$self_dir/../scripts/media-purge.sh" - fi + if [ ! -f "$script" ] && [ -f "$_cli_self/../scripts/media-purge.sh" ]; then + script="$_cli_self/../scripts/media-purge.sh" fi [ -f "$script" ] || log_error "media-purge.sh not found — run upgrade or re-setup" - chmod +x "$script" 2>/dev/null || true set -a - # shellcheck disable=SC1091 - [ -f "$install_dir/.env" ] && . "$install_dir/.env" + [ -f "$install_dir/.env" ] && safe_source "$install_dir/.env" set +a export API_HOST="${API_HOST:-127.0.0.1}" export CONFIG_DIR="$install_dir/config" @@ -193,9 +167,14 @@ purge_media() { export AUTH_USERNAME_FILE="$install_dir/secrets/auth_username.txt" export AUTH_PASSWORD_FILE="$install_dir/secrets/auth_password.txt" fi - export QBITTORRENT_URL="${QBITTORRENT_URL:-http://127.0.0.1:8081}" - export RADARR_URL="${RADARR_URL:-http://127.0.0.1:7878}" - export SONARR_URL="${SONARR_URL:-http://127.0.0.1:8989}" + if [ -f "$install_dir/secrets/jellyfin_api_key.txt" ]; then + export JELLYFIN_API_KEY_FILE="$install_dir/secrets/jellyfin_api_key.txt" + fi + export QBITTORRENT_URL="${QBITTORRENT_URL:-http://${API_HOST}:8081}" + export SABNZBD_URL="${SABNZBD_URL:-http://${API_HOST}:8085}" + export RADARR_URL="${RADARR_URL:-http://${API_HOST}:7878}" + export SONARR_URL="${SONARR_URL:-http://${API_HOST}:8989}" + export JELLYFIN_URL="${JELLYFIN_URL:-http://${API_HOST}:8096}" bash "$script" "$@" } @@ -229,132 +208,147 @@ wait_for_services() { if type service_row_ready >/dev/null 2>&1 && service_row_ready "$state" "$health"; then ready=$((ready + 1)) else - waiting+=("$svc") + waiting+=("${label} (${health:-${state:-missing}})") fi done < <(list_service_catalog) - else - for svc in "${!st_state[@]}"; do - total=$((total + 1)) - if [ "$(echo "${st_state[$svc]}" | tr '[:upper:]' '[:lower:]')" = "running" ]; then - ready=$((ready + 1)) - else - waiting+=("$svc") - fi - done fi if [ "$total" -gt 0 ] && [ "$ready" -eq "$total" ]; then - printf '\r\033[K' >&2 - log_success "All $total services are ready." + [ "$wait_time" -gt 0 ] && echo >&2 + log_success "All ${total} services ready" return 0 fi - if [ "${#waiting[@]}" -gt 0 ] && [ "${#waiting[@]}" -le 6 ]; then - wait_inline "Waiting for services ($ready/$total ready: ${waiting[*]})" "$wait_time" - else - wait_inline "Waiting for services ($ready/$total ready)" "$wait_time" - fi - sleep 1 - wait_time=$((wait_time + 1)) + wait_inline "Waiting for services: ${ready}/${total} ready" "$wait_time" + sleep 3 + wait_time=$((wait_time + 3)) done - printf '\r\033[K' >&2 - log_error "Not all services became ready within ${timeout}s ($ready/$total ready${waiting[*]:+: ${waiting[*]}})" + echo >&2 + if [ "${#waiting[@]}" -gt 0 ]; then + log_warning "Timed out after ${timeout}s — still starting: ${waiting[*]}" + else + log_warning "Timed out waiting for services after ${timeout}s" + fi + return 1 } get_ip_with_retries() { - local context=$1 - local cmd_prefix="" + local is_vpn=$1 + local retry=0 + local max_retries=5 + local ip="" - if [ "$context" = "qbittorrent" ]; then - cmd_prefix="run_docker exec qbittorrent" - fi - - for endpoint in "${IP_ENDPOINTS[@]}"; do - local ip - if [ "$context" = "local" ]; then - ip=$(curl -s --connect-timeout 5 "$endpoint") - else - ip=$($cmd_prefix curl -s --connect-timeout 5 "$endpoint") - fi - - if [ -n "$ip" ] && [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "$ip" - return 0 - fi + while [ $retry -lt $max_retries ]; do + for endpoint in "${IP_ENDPOINTS[@]}"; do + if [ "$is_vpn" = "true" ]; then + ip=$(run_docker exec gluetun curl -s --max-time 5 "$endpoint" 2>/dev/null || true) + else + ip=$(curl -s --max-time 5 "$endpoint" 2>/dev/null || true) + fi + if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "$ip" + return 0 + fi + done + retry=$((retry + 1)) + sleep 2 done return 1 } check_vpn() { - echo "Getting your IP..." - local your_ip - your_ip=$(get_ip_with_retries "local") || log_error "Failed to get your IP address from any endpoint" - echo "Your IP: $your_ip" + if [ "${VPN_ENABLED:-n}" != "y" ]; then + log_error "VPN is not enabled in your configuration." + fi - local country - country=$(curl -s --connect-timeout 5 "https://am.i.mullvad.net/country") || log_warning "Couldn't determine your country" - [ -n "$country" ] && echo "Your local IP country is $country" + echo "Checking VPN connection..." + local vpn_ip public_ip + vpn_ip=$(get_ip_with_retries "true") + public_ip=$(get_ip_with_retries "false") - echo -e "\nGetting your qBittorrent IP..." - local qbit_ip - qbit_ip=$(get_ip_with_retries "qbittorrent") || log_error "Failed to get qBittorrent IP from any endpoint" - echo "qBittorrent IP: $qbit_ip" + [ -z "$vpn_ip" ] && log_error "Failed to obtain VPN IP" + [ -z "$public_ip" ] && log_error "Failed to obtain public IP" - local qbit_country - qbit_country=$(run_docker exec qbittorrent curl -s --connect-timeout 5 "https://am.i.mullvad.net/country") || log_warning "Couldn't determine qBittorrent country" - [ -n "$qbit_country" ] && echo "qBittorrent country is $qbit_country" + echo + echo "IP check:" + echo " Your real IP: $public_ip" + echo " VPN exit IP: $vpn_ip" + echo - if [ "$qbit_ip" == "$your_ip" ]; then - log_error "WARNING: Your IPs are the same! qBittorrent is exposing your IP!" + if [ "$vpn_ip" != "$public_ip" ]; then + log_success "VPN is active and routing traffic correctly!" else - log_success "Success: Your IPs are different. qBittorrent is masking your IP!" + log_warning "VPN IP matches your real IP — VPN may not be routing properly" fi } backup_app() { - local destination=$1 - local backup_date + local destination="${1:-.}" + local backup_date backup_file tmp_file backup_date=$(date '+%Y-%m-%d-%s') - local backup_file="$destination/${APP_BACKUP_PREFIX}-$backup_date.tar.gz" + backup_file="${destination%/}/${APP_BACKUP_PREFIX:-assemblrr-backup}-$backup_date.tar.gz" + tmp_file="${backup_file}.tmp" - # Verify destination exists or create it if [ ! -d "$destination" ]; then log_info "Backup destination \"$destination\" does not exist. Creating it..." mkdir -p "$destination" || log_error "Failed to create backup destination directory" fi - echo "Stopping ${APP_DISPLAY_NAME} services..." - "${DC[@]}" stop > /dev/null 2>&1 || log_error "Failed to stop services" + echo "Stopping ${APP_DISPLAY_NAME:-assemblrr} services..." + "${DC[@]}" stop >/dev/null 2>&1 || log_warning "Some services were not running cleanly before backup" - echo -e "\nBacking up ${APP_DISPLAY_NAME} to $destination..." - - # Run tar inside an alpine container bound to the INSTALL_DIR and the destination (excluding temp/cache and sockets) - if ! wait_while "Creating backup archive" run_docker run --rm \ - -v "$INSTALL_DIR:/source" \ - -v "$(dirname "$backup_file"):/backup" \ - alpine tar --exclude='./transcoding-temp' --exclude='./config/jellyfin/cache' --exclude='ipc-socket' -czf "/backup/$(basename "$backup_file")" -C /source .; then + echo -e "\nBacking up ${APP_DISPLAY_NAME:-assemblrr} to $destination..." + if ! (umask 077 && wait_while "Creating backup archive" run_docker run --rm \ + -v "$INSTALL_DIR:/source:ro" \ + -v "$(dirname "$tmp_file"):/backup" \ + "${UTILITY_ALPINE_IMAGE:-alpine:3.24.4}" \ + tar --exclude='./transcoding-temp' --exclude='./config/jellyfin/cache' --exclude='ipc-socket' \ + -czf "/backup/$(basename "$tmp_file")" -C /source .); then + rm -f "$tmp_file" log_error "Failed to create backup archive" fi + chmod 600 "$tmp_file" + mv "$tmp_file" "$backup_file" - echo -e "\nStarting ${APP_DISPLAY_NAME} services..." - "${DC[@]}" start > /dev/null 2>&1 || log_warning "Failed to restart services" + echo -e "\nStarting ${APP_DISPLAY_NAME:-assemblrr} services..." + "${DC[@]}" start >/dev/null 2>&1 || log_warning "Failed to restart services" log_success "Backup completed successfully!" echo "Backup file: $backup_file" } +validate_backup_archive() { + local archive="$1" + [ -f "$archive" ] || return 1 + gzip -t "$archive" 2>/dev/null || return 1 + + local listing has_env=0 bad_path=0 entry + listing=$(tar -tzf "$archive" 2>/dev/null) || return 1 + while IFS= read -r entry; do + [ -z "$entry" ] && continue + case "$entry" in + .env|./.env) has_env=1 ;; + esac + case "$entry" in + /*|..|../*|*/../*|*/..) bad_path=1; break ;; + esac + done <<< "$listing" + + [ "$bad_path" -eq 0 ] && [ "$has_env" -eq 1 ] +} + destroy_app() { if [ "$#" -eq 0 ]; then echo -e "\nWARNING: This will destroy all your services, containers, volumes, and the custom network!" echo "This is not recoverable!" while true; do - read -p "Are you sure you want to continue? [y/N]: " -r + read_prompt "Are you sure you want to continue? [y/N]: " local reply=${REPLY:-n} if [[ ${reply,,} =~ ^y$ ]]; then "${DC[@]}" down || log_error "Failed to destroy services" - docker network rm "$APP_NETWORK_NAME" 2>/dev/null || log_warning "Failed to remove $APP_NETWORK_NAME. It might not exist or was already removed." - echo -e "\n${APP_DISPLAY_NAME} services were destroyed. To restart, run: ${APP_CLI_NAME} start" + docker network rm "${APP_NETWORK_NAME:-assemblrr_network}" 2>/dev/null || true + echo -e "\n${APP_DISPLAY_NAME:-assemblrr} services were destroyed. To restart, run: ${APP_CLI_NAME:-assemblrr} start" break elif [[ ${reply,,} =~ ^n$ ]]; then log_info "Destroy cancelled." @@ -365,15 +359,14 @@ destroy_app() { done else local target_label="$*" - echo -e "\nWARNING: This will destroy the service(s): \"${target_label}\". This includes their associated containers and volumes!" - echo "This is not recoverable!" + echo -e "\nWARNING: This will destroy the service(s): \"${target_label}\"." while true; do - read -p "Are you sure you want to continue? [y/N]: " -r + read_prompt "Are you sure you want to continue? [y/N]: " local reply=${REPLY:-n} if [[ ${reply,,} =~ ^y$ ]]; then "${DC[@]}" stop "$@" || log_error "Failed to stop services" "${DC[@]}" rm -f -v "$@" || log_error "Failed to destroy services" - echo -e "\n${APP_DISPLAY_NAME} service was destroyed. To restart, run: ${APP_CLI_NAME} start" + echo -e "\n${APP_DISPLAY_NAME:-assemblrr} service was destroyed. To restart, run: ${APP_CLI_NAME:-assemblrr} start" break elif [[ ${reply,,} =~ ^n$ ]]; then log_info "Destroy cancelled." @@ -388,10 +381,12 @@ destroy_app() { uninstall_app() { local force=false local delete_media=false + local remove_config=true local removed_config=false local removed_media=false local -a extra_removed=() local -a extra_kept=() + local arg for arg in "$@"; do case "$arg" in -f|--force) force=true ;; @@ -401,70 +396,94 @@ uninstall_app() { poke_wsl_automounts 2>/dev/null || true - # --force already opts out of confirmation; skip the inventory and preamble. if [ "$force" = false ]; then echo print_detected_locations "Detected installation:" echo - echo "WARNING: This will COMPLETELY remove ${APP_DISPLAY_NAME}!" + echo "WARNING: This will COMPLETELY remove ${APP_DISPLAY_NAME:-assemblrr}!" echo "This includes running containers, the Docker network, the CLI, and the config path above." if [ "$delete_media" = true ]; then echo "Media at $MEDIA_DIRECTORY will also be deleted." else echo "Media at $MEDIA_DIRECTORY is kept unless you confirm below (or pass --media)." fi - echo "Tip: run '${APP_CLI_NAME} backup ' first if you want to keep your configuration." + echo "Tip: run '${APP_CLI_NAME:-assemblrr} backup ' first if you want to keep your configuration." echo echo "This is not recoverable!" - read -p "Are you ABSOLUTELY sure? Type 'yes' to confirm: " -r - if [[ "$REPLY" != "yes" ]]; then + read_prompt "Uninstall ${APP_DISPLAY_NAME:-assemblrr}? [y/N]: " + if [[ ! "${REPLY:-}" =~ ^[Yy]$ ]]; then echo "Uninstall cancelled." return 0 fi + read_prompt "Also delete config at $INSTALL_DIR? [Y/n]: " + if [[ "${REPLY:-}" =~ ^[Nn]$ ]]; then + remove_config=false + fi + if [ "$delete_media" = false ]; then + read_prompt "Also delete media at $MEDIA_DIRECTORY? [y/N]: " + if [[ "${REPLY:-}" =~ ^[Yy]$ ]]; then + read_prompt "Type 'delete media' to permanently erase $MEDIA_DIRECTORY: " + if [ "${REPLY:-}" = "delete media" ]; then + delete_media=true + else + log_info "Keeping media at $MEDIA_DIRECTORY." + fi + fi + fi fi - "${DC[@]}" down -v 2>/dev/null || log_warning "Failed to stop some services" - - if run_docker network inspect "$APP_NETWORK_NAME" &>/dev/null; then - run_docker network rm "$APP_NETWORK_NAME" 2>/dev/null || log_warning "Failed to remove Docker network $APP_NETWORK_NAME" + if [ "$force" = false ] && type wait_while >/dev/null 2>&1; then + wait_while "Stopping containers" "${DC[@]}" down -v || log_warning "Failed to stop some services" + else + "${DC[@]}" down -v 2>/dev/null || log_warning "Failed to stop some services" fi - if [ "$force" = true ]; then + if run_docker network inspect "${APP_NETWORK_NAME:-assemblrr_network}" &>/dev/null; then + run_docker network rm "${APP_NETWORK_NAME:-assemblrr_network}" 2>/dev/null || true + fi + + if [ "$force" = true ] || [ "$remove_config" = true ]; then safe_rm_rf "$INSTALL_DIR" removed_config=true - else - read -p "Also delete config at $INSTALL_DIR? Type the full path to confirm: " -r - if [[ "$REPLY" = "$INSTALL_DIR" ]]; then - safe_rm_rf "$INSTALL_DIR" - removed_config=true - fi fi if [ "$delete_media" = true ]; then safe_rm_rf "$MEDIA_DIRECTORY" removed_media=true - elif [ "$force" = false ]; then - read -p "Also delete media at $MEDIA_DIRECTORY? Type the full path to confirm: " -r - if [[ "$REPLY" = "$MEDIA_DIRECTORY" ]]; then - safe_rm_rf "$MEDIA_DIRECTORY" - removed_media=true - fi fi - # Path picker / hung setup can leave assemblrr trees on other mounts - # (e.g. /mnt/e) that the pointer never recorded. - local leftover_kind leftover_path + local leftover_kind leftover_path ans_left while IFS=$'\t' read -r leftover_kind leftover_path; do [ -n "$leftover_path" ] || continue case "$leftover_kind" in install) - safe_rm_rf "$leftover_path" - extra_removed+=("$leftover_path") + if [ "$force" = true ]; then + safe_rm_rf "$leftover_path" + extra_removed+=("$leftover_path") + else + read_prompt "Also remove leftover install dir at $leftover_path? [y/N]: " ans_left + if [[ ${ans_left:-n} =~ ^[Yy]$ ]]; then + safe_rm_rf "$leftover_path" + extra_removed+=("$leftover_path") + else + extra_kept+=("$leftover_path") + fi + fi ;; media) if [ "$delete_media" = true ]; then - safe_rm_rf "$leftover_path" - extra_removed+=("$leftover_path") + if [ "$force" = true ]; then + safe_rm_rf "$leftover_path" + extra_removed+=("$leftover_path") + else + read_prompt "Also remove leftover media dir at $leftover_path? [y/N]: " ans_left + if [[ ${ans_left:-n} =~ ^[Yy]$ ]]; then + safe_rm_rf "$leftover_path" + extra_removed+=("$leftover_path") + else + extra_kept+=("$leftover_path") + fi + fi else extra_kept+=("$leftover_path") fi @@ -482,13 +501,10 @@ uninstall_app() { rmdir "$HOME/.local/bin/lib" 2>/dev/null || true fi - # Setup writes this cheat-sheet under $HOME (outside the install dir) - # Legacy setup wrote ~/assemblrr_services.txt — remove if present rm -f "$HOME/assemblrr_services.txt" 2>/dev/null || true - # Install discovery pointer (may live outside the install dir) rm -f "$HOME/.assemblrr-config" "$HOME/.${APP_NAME:-assemblrr}-config" 2>/dev/null || true - log_success "${APP_DISPLAY_NAME} uninstalled." + log_success "${APP_DISPLAY_NAME:-assemblrr} uninstalled." if [ "$removed_config" = true ]; then echo " Config removed: $INSTALL_DIR" else @@ -512,79 +528,70 @@ uninstall_app() { fi } -# Load PUID/PGID from install .env when present (for prepare_install_dirs) _load_install_ids() { - local env_file="$INSTALL_DIR/.env" - if [ -f "$env_file" ]; then - # shellcheck disable=SC1090 - set -a - safe_source "$env_file" 2>/dev/null || true - set +a + local puid="${PUID:-$(id -u)}" + local pgid="${PGID:-$(id -g)}" + if [ -f "$INSTALL_DIR/.env" ]; then + local _ep _eg + _ep=$(grep -E '^PUID=' "$INSTALL_DIR/.env" 2>/dev/null | head -1 | cut -d= -f2 || true) + _eg=$(grep -E '^PGID=' "$INSTALL_DIR/.env" 2>/dev/null | head -1 | cut -d= -f2 || true) + [[ "$_ep" =~ ^[0-9]+$ ]] && puid="$_ep" + [[ "$_eg" =~ ^[0-9]+$ ]] && pgid="$_eg" fi - _HOST_UID="${PUID:-$(id -u)}" - _HOST_GID="${PGID:-$(id -g)}" + echo "$puid $pgid" } start_app() { - _load_install_ids - prepare_install_dirs "$INSTALL_DIR" "$_HOST_UID" "$_HOST_GID" - - # Validate VPN config before starting (if VPN is enabled) - if [ "${VPN_ENABLED:-n}" = "y" ]; then - if ! validate_vpn_secrets "$INSTALL_DIR" "${VPN_ENABLED:-n}" "${VPN_TYPE:-openvpn}"; then - log_error "Set VPN credentials in $INSTALL_DIR/secrets before starting services" - fi - - # Test VPN connection by starting Gluetun first - if ! test_vpn_connection_shared "${DC[@]}"; then - log_error "VPN startup failed. Fix credentials in $INSTALL_DIR/secrets (and .env if needed), then retry." - fi + local _ids _puid _pgid + if [ -d "$INSTALL_DIR/compose" ] && type prepare_install_dirs >/dev/null 2>&1; then + read -r _puid _pgid < <(_load_install_ids) + prepare_install_dirs "$INSTALL_DIR" "$_puid" "$_pgid" + fi + echo "Starting ${APP_DISPLAY_NAME:-assemblrr} services..." + if [ "$#" -gt 0 ]; then + "${DC[@]}" start "$@" || log_error "Failed to start $*" + log_success "Service(s) started: $*" + elif [ "${#COMPOSE_ARGS[@]}" -gt 0 ] && type compose_up_stack >/dev/null 2>&1; then + compose_up_stack "default" || log_error "Failed to start services" + wait_for_services || true + else + "${DC[@]}" up -d --remove-orphans || log_error "Failed to start services" + wait_for_services || true fi - if [ "$#" -eq 0 ]; then - compose_up_stack "${MEDIA_SERVICE:-jellyfin}" || log_error "Failed to start services" - wait_for_services echo check_status || true - else - compose_up_stack "${MEDIA_SERVICE:-jellyfin}" "$@" || log_error "Failed to start services" fi + echo "Manage anytime: ${APP_CLI_NAME:-assemblrr} status | logs | stop" } restart_app() { - _load_install_ids - prepare_install_dirs "$INSTALL_DIR" "$_HOST_UID" "$_HOST_GID" - + echo "Restarting ${APP_DISPLAY_NAME:-assemblrr} services..." + "${DC[@]}" restart "$@" || log_error "Failed to restart services" if [ "$#" -eq 0 ]; then - wait_while "Stopping services" "${DC[@]}" stop || log_warning "Some services failed to stop" - compose_up_stack "${MEDIA_SERVICE:-jellyfin}" || log_error "Failed to start services" - wait_for_services + wait_for_services || true echo check_status || true else - "${DC[@]}" stop "$@" || log_warning "Some services failed to stop" - compose_up_stack "${MEDIA_SERVICE:-jellyfin}" "$@" || log_error "Failed to start services" + log_success "${APP_DISPLAY_NAME:-assemblrr} restarted: $*" fi } stop_app() { - if [ $# -eq 0 ]; then - "${DC[@]}" stop || log_error "Failed to stop services" + echo "Stopping ${APP_DISPLAY_NAME:-assemblrr} services..." + "${DC[@]}" stop "$@" || log_error "Failed to stop services" + if [ "$#" -gt 0 ]; then + log_success "${APP_DISPLAY_NAME:-assemblrr} stopped: $*" else - "${DC[@]}" stop "$@" || log_error "Failed to stop services: $*" + log_success "${APP_DISPLAY_NAME:-assemblrr} stopped successfully" fi - log_success "Services stopped successfully" } -# Parse compose ps into associative-ish lines: service -> "state|health" -# Uses Service name (compose key), not container name. _status_compose_rows() { - # format: servicestatehealth (health may be empty) - "${DC[@]}" ps -a --format '{{.Service}}\t{{.State}}\t{{.Health}}' 2>/dev/null + "${DC[@]}" ps -a --format '{{.Service}}\t{{.State}}\t{{.Health}}' 2>/dev/null || true } _status_normalize() { - # stdin: state, health → stdout: short token + color category local state="${1:-}" health="${2:-}" state=$(echo "$state" | tr '[:upper:]' '[:lower:]') health=$(echo "$health" | tr '[:upper:]' '[:lower:]') @@ -604,15 +611,28 @@ _status_normalize() { fi } +_status_short_bg_label() { + case "${1:-}" in + "Seerr (internal)") echo "Gateway" ;; + "Gluetun (VPN)") echo "Gluetun" ;; + "Media purge watch") echo "Purge" ;; + "VPN watchdog") echo "Watchdog" ;; + "Byparr (solver)") echo "Byparr" ;; + *) echo "${1:-}" ;; + esac +} + check_status() { - local raw_docker=0 - local arg + local raw_docker=0 show_all=0 compact=0 arg for arg in "$@"; do case "$arg" in --docker|-d) raw_docker=1 ;; + --all|-a) show_all=1 ;; + --compact) compact=1 ;; -h|--help) - echo "Usage: ${APP_CLI_NAME} status [--docker]" - echo " Default: operator dashboard (name, state, URL)." + echo "Usage: ${APP_CLI_NAME:-assemblrr} status [--all | --docker]" + echo " Default: operator dashboard (Web UIs + background summary)." + echo " --all: show every background/internal container individually." echo " --docker: raw docker compose ps table." return 0 ;; @@ -625,36 +645,51 @@ check_status() { fi if ! type list_service_catalog >/dev/null 2>&1; then - log_warning "Service catalog not loaded — falling back to docker compose ps" "${DC[@]}" ps || log_error "Failed to check services" return 0 fi - # Load live state: service -> state|health + local rows_raw + rows_raw=$(_status_compose_rows) + declare -A st_state=() declare -A st_health=() - local svc state health line + local svc state health while IFS=$'\t' read -r svc state health; do [ -z "$svc" ] && continue st_state["$svc"]="$state" st_health["$svc"]="$health" - done < <(_status_compose_rows) + done <<< "$rows_raw" - local media="${MEDIA_SERVICE:-jellyfin}" - local vpn="${VPN_ENABLED:-n}" - local vpn_label="off" - [ "$vpn" = "y" ] && vpn_label="on" + if [ "$compact" -eq 0 ]; then + local -a badges=() + if [ "${VPN_ENABLED:-n}" = "y" ]; then + badges+=("VPN on") + else + badges+=("VPN off") + fi + [ "${GPU_TRANSCODING:-none}" != "none" ] && badges+=("GPU ${GPU_TRANSCODING}") + [ "${VUETORRENT_ENABLED:-n}" = "y" ] && badges+=("VueTorrent") + [ "${BYPARR_ENABLED:-n}" = "y" ] && badges+=("Byparr") + [ "${USENET_ENABLED:-n}" = "y" ] && badges+=("Usenet") + local badge_str="" b + for b in "${badges[@]}"; do + [ -n "$badge_str" ] && badge_str+=" · " + badge_str+="$b" + done + echo "${APP_DISPLAY_NAME:-assemblrr} · ${badge_str}" + ASSEMBLRR_SHOW_LEFTOVERS=0 print_detected_locations + echo + fi - echo "${APP_DISPLAY_NAME} · media=${media} · VPN ${vpn_label}" - print_detected_locations - echo - printf " %-14s %-12s %s\n" "SERVICE" "STATE" "URL / NOTE" - printf " %-14s %-12s %s\n" "--------------" "------------" "---------------------------" + printf " %-18s %-12s %s\n" "SERVICE" "STATE" "URL" + printf " %-18s %-12s %s\n" "------------------" "------------" "------------------------" - local label port path kind token url note - local seen="" - local unhealthy=0 - local total=0 + local label port path kind token url note seen="" unhealthy=0 total=0 + local bg_total=0 bg_ok=0 + local -a bg_names=() + local ui_host="${API_HOST:-localhost}" + [ "$ui_host" = "127.0.0.1" ] && ui_host="localhost" while IFS='|' read -r svc label port path kind; do [ -z "$svc" ] && continue @@ -663,14 +698,24 @@ check_status() { state="${st_state[$svc]:-}" health="${st_health[$svc]:-}" token=$(_status_normalize "$state" "$health") - if [ "$token" = "unhealthy" ] || [ "$token" = "missing" ] || [ "$token" = "exited" ] || [ "$token" = "dead" ]; then - unhealthy=$((unhealthy + 1)) + case "$token" in + unhealthy|missing|exited|dead) unhealthy=$((unhealthy + 1)) ;; + esac + + if [ "$kind" = "internal" ]; then + bg_total=$((bg_total + 1)) + if [ "$token" = "healthy" ] || [ "$token" = "running" ]; then + bg_ok=$((bg_ok + 1)) + fi + bg_names+=("$(_status_short_bg_label "$label")") + if [ "$show_all" -eq 0 ] && { [ "$token" = "healthy" ] || [ "$token" = "running" ]; }; then + continue + fi fi - url="" - note="" + url="" note="" if [ "$kind" = "ui" ]; then - url=$(service_ui_url "$port" "$path" "localhost") + url=$(service_ui_url "$port" "$path" "$ui_host") if [ "$token" = "missing" ] || [ "$token" = "exited" ]; then note="(down)" fi @@ -678,16 +723,12 @@ check_status() { note="(internal)" fi - # STATE column without color for width, then rewrite — use plain token padded + color on same width - printf " %-14s " "$label" + printf " %-18s " "$label" case "$token" in - healthy) printf "${GREEN}%-12s${NC}" "healthy" ;; - running) printf "${GREEN}%-12s${NC}" "running" ;; - starting) printf "${YELLOW}%-12s${NC}" "starting" ;; - unhealthy) printf "${RED}%-12s${NC}" "unhealthy" ;; - missing) printf "${RED}%-12s${NC}" "missing" ;; - exited) printf "${RED}%-12s${NC}" "exited" ;; - *) printf "${YELLOW}%-12s${NC}" "$token" ;; + healthy|running) printf "${GREEN:-}%-12s${NC:-}" "$token" ;; + starting) printf "${YELLOW:-}%-12s${NC:-}" "$token" ;; + unhealthy|missing|exited) printf "${RED:-}%-12s${NC:-}" "$token" ;; + *) printf "${YELLOW:-}%-12s${NC:-}" "$token" ;; esac if [ -n "$url" ]; then printf " %s" "$url" @@ -698,39 +739,57 @@ check_status() { fi done < <(list_service_catalog) - # Any compose services not in the catalog (custom overlays) while IFS=$'\t' read -r svc state health; do [ -z "$svc" ] && continue [[ "$seen" == *"|${svc}|"* ]] && continue total=$((total + 1)) token=$(_status_normalize "$state" "$health") - if [ "$token" = "unhealthy" ] || [ "$token" = "missing" ] || [ "$token" = "exited" ] || [ "$token" = "dead" ]; then - unhealthy=$((unhealthy + 1)) - fi - printf " %-14s " "$svc" case "$token" in - healthy) printf "${GREEN}%-12s${NC}" "healthy" ;; - running) printf "${GREEN}%-12s${NC}" "running" ;; - starting) printf "${YELLOW}%-12s${NC}" "starting" ;; - unhealthy) printf "${RED}%-12s${NC}" "unhealthy" ;; - *) printf "${YELLOW}%-12s${NC}" "$token" ;; + unhealthy|missing|exited|dead) unhealthy=$((unhealthy + 1)) ;; esac - printf " (custom / unlisted)\n" - done < <(_status_compose_rows) + printf " %-18s " "$svc" + case "$token" in + healthy|running) printf "${GREEN:-}%-12s${NC:-}" "$token" ;; + starting) printf "${YELLOW:-}%-12s${NC:-}" "$token" ;; + unhealthy) printf "${RED:-}%-12s${NC:-}" "$token" ;; + *) printf "${YELLOW:-}%-12s${NC:-}" "$token" ;; + esac + printf " (custom)\n" + done <<< "$rows_raw" - echo - if [ "$unhealthy" -gt 0 ]; then - log_warning "${unhealthy} service(s) need attention (${total} listed)." - return 1 + if [ "$show_all" -eq 0 ] && [ "$bg_total" -gt 0 ]; then + local bg_list="" n + for n in "${bg_names[@]}"; do + [ -n "$bg_list" ] && bg_list+=", " + bg_list+="$n" + done + echo + if [ "$bg_ok" -eq "$bg_total" ]; then + printf " %-18s ${GREEN:-}%s${NC:-} (%s)\n" "Background:" "${bg_ok}/${bg_total} healthy" "$bg_list" + else + local bg_bad=$((bg_total - bg_ok)) + printf " %-18s ${YELLOW:-}%s healthy, %s need attention${NC:-}\n" "Background:" "${bg_ok}/${bg_total}" "$bg_bad" + fi + fi + + if [ "$compact" -eq 0 ]; then + echo + if [ "$unhealthy" -gt 0 ]; then + log_warning "${unhealthy} service(s) need attention (${total} listed)." + return 1 + fi + log_success "All ${total} services look good." + else + [ "$unhealthy" -eq 0 ] || return 1 fi - log_success "All ${total} listed services look good." return 0 } update_containers() { local skip_backup=false local assume_yes=false - + local arg + for arg in "$@"; do case "$arg" in --skip-backup) skip_backup=true ;; @@ -738,40 +797,50 @@ update_containers() { esac done - echo -e "\nWARNING: Updating containers may cause data loss or compatibility issues if new versions have breaking changes!" - + echo + log_info "Note: ${APP_DISPLAY_NAME:-assemblrr} pins core service image tags in compose/*.yaml to tested releases." + log_info "To receive newer upstream service releases + migrations + wiring, use: ${APP_CLI_NAME:-assemblrr} upgrade" + echo + if [ "$skip_backup" = false ] && [ "$assume_yes" = false ]; then - read -p "Would you like to back up your current configuration first? [Y/n]: " -r + read_prompt "Create a backup before rebuilding sidecars / pulling custom overlay images? [Y/n]: " if [[ ! ${REPLY,,} =~ ^n$ ]]; then - local default_backup_dir="$HOME/assemblrr-backups" + local default_backup_dir="$HOME/${APP_NAME:-assemblrr}-backups" echo -e "\nStarting automatic backup to $default_backup_dir..." backup_app "$default_backup_dir" - echo -e "\nBackup complete. Proceeding with container update..." fi fi if [ "$assume_yes" = false ]; then - read -p "Are you sure you want to update all containers? [Y/n]: " -r + read_prompt "Rebuild local sidecars and pull any custom overlay images now? [Y/n]: " if [[ ${REPLY,,} =~ ^n$ ]]; then echo "Update aborted." return 0 fi fi - echo "Pulling latest container images..." - "${DC[@]}" pull || log_error "Failed to pull containers" - echo "Restarting ${APP_DISPLAY_NAME} services..." - restart_app - log_success "Containers updated successfully!" + log_info "Pulling registry images (ignoring locally built sidecars)..." + "${DC[@]}" pull --ignore-buildable || log_warning "Some registry pulls failed" + log_info "Rebuilding sidecars and recreating stack..." + if [ "${#COMPOSE_ARGS[@]}" -gt 0 ] && type compose_up_stack >/dev/null 2>&1; then + compose_up_stack "default" --build || log_error "Failed to update containers" + else + "${DC[@]}" up -d --build --remove-orphans || log_error "Failed to update containers" + fi + log_success "Containers refreshed!" } show_config() { - echo "${APP_DISPLAY_NAME} Configuration:" - print_detected_locations + echo "${APP_DISPLAY_NAME:-assemblrr} Configuration:" + ASSEMBLRR_SHOW_LEFTOVERS=0 print_detected_locations echo " Media service: ${MEDIA_SERVICE:-jellyfin}" echo " VPN enabled: ${VPN_ENABLED:-n}" echo " VPN type: ${VPN_TYPE:-openvpn}" echo " Timezone: ${TZ:-UTC}" + echo " VueTorrent: ${VUETORRENT_ENABLED:-n}" + echo " GPU transcoding: ${GPU_TRANSCODING:-none}" + echo " Byparr solver: ${BYPARR_ENABLED:-n}" + echo " SABnzbd / Usenet: ${USENET_ENABLED:-n}" if type quality_tier >/dev/null 2>&1; then if [ "$(quality_tier)" = "any" ]; then echo " Quality: any" @@ -785,7 +854,7 @@ show_config() { echo echo "Compose files:" local _prev="" _arg - for _arg in "${COMPOSE_ARGS[@]}"; do + for _arg in "${COMPOSE_ARGS[@]+"${COMPOSE_ARGS[@]}"}"; do if [ "$_prev" = "-f" ]; then echo " $_arg" fi @@ -794,7 +863,7 @@ show_config() { } show_config_help() { - echo "Usage: ${APP_CLI_NAME} config [subcommand]" + echo "Usage: ${APP_CLI_NAME:-assemblrr} config [subcommand]" echo echo "Subcommands:" printf " %-12s %s\n" "show" "Show current configuration" @@ -802,15 +871,15 @@ show_config_help() { printf " %-12s %s\n" "apply" "Re-wire running services (no compose replace)" echo echo "Examples:" - echo " ${APP_CLI_NAME} config # List config options" - echo " ${APP_CLI_NAME} config show # Show configuration" - echo " ${APP_CLI_NAME} config apply # Re-run service wiring only" - echo " ${APP_CLI_NAME} config edit # Pick a setting to change" + echo " ${APP_CLI_NAME:-assemblrr} config # List config options" + echo " ${APP_CLI_NAME:-assemblrr} config show # Show configuration" + echo " ${APP_CLI_NAME:-assemblrr} config apply # Re-run service wiring only" + echo " ${APP_CLI_NAME:-assemblrr} config edit # Pick a setting to change" } config_apply() { if [ ! -f "$INSTALL_DIR/config.sh" ]; then - log_error "config.sh not found in $INSTALL_DIR. Run '${APP_CLI_NAME} upgrade' first." + log_error "config.sh not found in $INSTALL_DIR. Run '${APP_CLI_NAME:-assemblrr} upgrade' first." fi log_info "Re-wiring services (no compose replace)..." ASSEMBLRR_NONINTERACTIVE=1 bash "$INSTALL_DIR/config.sh" @@ -823,7 +892,7 @@ _load_config_edit() { elif [ -f "$_lib_dir/config_edit.sh" ]; then src="$_lib_dir/config_edit.sh" else - log_error "config_edit.sh not found. Run '${APP_CLI_NAME} upgrade' to install modular config edit." + log_error "config_edit.sh not found. Run '${APP_CLI_NAME:-assemblrr} upgrade' to install modular config edit." fi # shellcheck source=/dev/null source "$src" @@ -833,76 +902,80 @@ config_cmd() { local sub=${1:-} shift || true case "$sub" in - "") - show_config_help - ;; - show) - show_config - ;; - apply|wire) - config_apply - ;; + "") show_config_help ;; + show) show_config ;; + apply|wire) config_apply ;; edit) _load_config_edit config_edit_run "${1:-}" ;; - --help|-h|help) - show_config_help - ;; - *) - log_error "Unknown config subcommand: $sub\nRun '${APP_CLI_NAME} config' for usage" - ;; + --help|-h|help) show_config_help ;; + *) log_error "Unknown config subcommand: $sub\nRun '${APP_CLI_NAME:-assemblrr} config' for usage" ;; esac } restore_app() { - local backup_file="$1" - - if [ ! -f "$backup_file" ]; then - log_error "Backup file not found: $backup_file" + local backup_file="${1:-}" + if ! validate_backup_archive "$backup_file"; then + log_error "Invalid or unsafe backup archive (must be a valid .tar.gz containing .env with safe relative paths): $backup_file" fi echo -e "\nWARNING: This will stop all services and overwrite the current installation!" echo "Backup file: $backup_file" - read -p "Are you sure you want to restore? [y/N]: " -r + read_prompt "Are you sure you want to restore? [y/N]: " if [[ ${REPLY,,} != "y" ]]; then echo "Restore cancelled." return 0 fi - echo "Stopping ${APP_DISPLAY_NAME} services..." + echo "Stopping ${APP_DISPLAY_NAME:-assemblrr} services..." "${DC[@]}" down 2>/dev/null || log_warning "Failed to stop services" - echo "Restoring from backup..." - - # Safely clear the current configuration instead of blindly overwriting - local timestamp=$(date +%Y%m%d_%H%M%S) - local backup_dir="${INSTALL_DIR}_backup_${timestamp}" - + local timestamp backup_dir abs_backup_file + timestamp=$(date +%Y%m%d_%H%M%S) + backup_dir="${INSTALL_DIR}_backup_${timestamp}" + echo "Creating safety snapshot of current state at ${backup_dir}..." wait_while "Creating safety snapshot" run_docker run --rm \ -v "$(dirname "$INSTALL_DIR"):/target_parent" \ - alpine cp -r "/target_parent/$(basename "$INSTALL_DIR")" "/target_parent/$(basename "$backup_dir")" \ + "${UTILITY_ALPINE_IMAGE:-alpine:3.24.4}" \ + cp -r "/target_parent/$(basename "$INSTALL_DIR")" "/target_parent/$(basename "$backup_dir")" \ || log_warning "Failed to create safety snapshot" wait_while "Clearing install directory" run_docker run --rm \ -v "$INSTALL_DIR:/target" \ - alpine sh -c 'find /target -mindepth 1 -maxdepth 1 ! -name "media" ! -name "downloads" -exec rm -rf {} +' + "${UTILITY_ALPINE_IMAGE:-alpine:3.24.4}" \ + sh -c 'find /target -mindepth 1 -maxdepth 1 ! -name "media" ! -name "downloads" -exec rm -rf {} +' - local abs_backup_file; abs_backup_file=$(realpath "$backup_file") + abs_backup_file=$(realpath "$backup_file") if ! wait_while "Restoring from backup" run_docker run --rm \ -v "$INSTALL_DIR:/target" \ - -v "$(dirname "$abs_backup_file"):/backup" \ - alpine tar -xzf "/backup/$(basename "$abs_backup_file")" -C /target; then + -v "$(dirname "$abs_backup_file"):/backup:ro" \ + "${UTILITY_ALPINE_IMAGE:-alpine:3.24.4}" \ + tar --no-same-owner -xzf "/backup/$(basename "$abs_backup_file")" -C /target; then log_error "Failed to extract backup" fi - echo "Starting ${APP_DISPLAY_NAME} services..." + # Adapt restored config to current host INSTALL_DIRECTORY / PUID / PGID if moved + local host_uid host_gid f + host_uid=$(id -u) + host_gid=$(id -g) + for f in "$INSTALL_DIR/.env" "$INSTALL_DIR/.assemblrr-config"; do + [ -f "$f" ] || continue + sed -i -E "s|^INSTALL_DIRECTORY=.*|INSTALL_DIRECTORY=\"${INSTALL_DIR}\"|" "$f" 2>/dev/null || true + done + [ -f "$INSTALL_DIR/.env" ] && sed -i -E "s|^INSTALL_DIRECTORY=.*|INSTALL_DIRECTORY=${INSTALL_DIR}|" "$INSTALL_DIR/.env" 2>/dev/null || true + if [ -d "$INSTALL_DIR/secrets" ]; then + chmod 700 "$INSTALL_DIR/secrets" + chmod 600 "$INSTALL_DIR/secrets/"* 2>/dev/null || true + fi + prepare_install_dirs "$INSTALL_DIR" "$host_uid" "$host_gid" 2>/dev/null || true + + echo "Starting ${APP_DISPLAY_NAME:-assemblrr} services..." "${DC[@]}" up -d --remove-orphans || log_warning "Failed to start services" echo "Cleaning up old safety snapshots (keeping last 3)..." - # Keep only the 3 most recent backups, remove the rest - ls -dt "${INSTALL_DIR}_backup_"* 2>/dev/null | tail -n +4 | while read -r old_backup; do + ls -dt "${INSTALL_DIR}_backup_"* 2>/dev/null | tail -n +4 | while IFS= read -r old_backup; do rm -rf "$old_backup" 2>/dev/null || true done @@ -919,35 +992,47 @@ show_logs() { } check_health() { - # Compact pass/fail over compose health (exit 1 if any unhealthy/missing expected UI service) - echo "${APP_DISPLAY_NAME} Health Check:" + echo "${APP_DISPLAY_NAME:-assemblrr} Health Check:" echo - local unhealthy=0 - local svc state health token + local rows_raw svc state health token label port path kind seen="" unhealthy=0 + rows_raw=$(_status_compose_rows) + + declare -A st_state=() st_health=() + while IFS=$'\t' read -r svc state health; do + [ -z "$svc" ] && continue + st_state["$svc"]="$state" + st_health["$svc"]="$health" + done <<< "$rows_raw" + + if type list_service_catalog >/dev/null 2>&1; then + while IFS='|' read -r svc label port path kind; do + [ -z "$svc" ] && continue + seen="${seen}|${svc}|" + token=$(_status_normalize "${st_state[$svc]:-}" "${st_health[$svc]:-}") + case "$token" in + healthy) log_success " $svc: healthy" ;; + running) log_warning " $svc: running (no healthcheck)" ;; + starting) log_warning " $svc: starting..." ;; + *) log_error_inline " $svc: $token"; unhealthy=$((unhealthy + 1)) ;; + esac + done < <(list_service_catalog) + fi while IFS=$'\t' read -r svc state health; do [ -z "$svc" ] && continue + [[ "$seen" == *"|${svc}|"* ]] && continue token=$(_status_normalize "$state" "$health") case "$token" in - healthy) - log_success " $svc: healthy" - ;; - running) - log_warning " $svc: running (no healthcheck)" - ;; - starting) - log_warning " $svc: starting..." - ;; - *) - log_error_inline " $svc: $token" - unhealthy=$((unhealthy + 1)) - ;; + healthy) log_success " $svc: healthy (custom)" ;; + running) log_warning " $svc: running (custom)" ;; + starting) log_warning " $svc: starting..." ;; + *) log_error_inline " $svc: $token (custom)"; unhealthy=$((unhealthy + 1)) ;; esac - done < <(_status_compose_rows) + done <<< "$rows_raw" echo if [ "$unhealthy" -gt 0 ]; then - log_warning "$unhealthy service(s) are unhealthy" + log_warning "$unhealthy service(s) need attention" return 1 fi log_success "All services are healthy" @@ -955,74 +1040,53 @@ check_health() { } main() { - local command=${1:-"--help"} - local destination=${2:-.} + local command="${1:---help}" + case "$command" in + --help|-h|help) + show_help + return 0 + ;; + esac + _cli_init + + local destination="${2:-.}" if [ "$command" = "backup" ]; then destination=$(realpath "$destination" 2>/dev/null || echo "$destination") || log_error "Invalid backup destination path" fi case "$command" in - --help) - show_help - ;; - restart) - restart_app "${@:2}" - ;; - stop) - stop_app "${@:2}" - ;; - start) - start_app "${@:2}" - ;; - status) - check_status "${@:2}" - ;; - check-vpn) - check_vpn - ;; - destroy) - destroy_app "${@:2}" - ;; - uninstall) - uninstall_app "${@:2}" - ;; - backup) - backup_app "$destination" - ;; + restart) restart_app "${@:2}" ;; + stop) stop_app "${@:2}" ;; + start) start_app "${@:2}" ;; + status) check_status "${@:2}" ;; + check-vpn) check_vpn ;; + destroy) destroy_app "${@:2}" ;; + uninstall) uninstall_app "${@:2}" ;; + backup) backup_app "$destination" ;; restore) - [ -z "${2:-}" ] && log_error "Usage: ${APP_CLI_NAME} restore /path/to/backup.tar.gz" + [ -z "${2:-}" ] && log_error "Usage: ${APP_CLI_NAME:-assemblrr} restore /path/to/backup.tar.gz" restore_app "${2}" ;; - update-containers) - update_containers "${@:2}" - ;; - update-cli) - log_info "The CLI is ${INSTALL_DIR}/cli.sh. Update with: ${APP_CLI_NAME} upgrade" - ;; + update-containers) update_containers "${@:2}" ;; + update-cli) log_info "The CLI is ${INSTALL_DIR}/cli.sh. Update with: ${APP_CLI_NAME:-assemblrr} upgrade" ;; upgrade) if ! type upgrade_app >/dev/null 2>&1; then log_error "Upgrade engine not found. Update CLI from a current checkout: bash /path/to/repo/bin/cli.sh upgrade --from /path/to/repo" fi upgrade_app "${@:2}" ;; - logs) - show_logs "$@" - ;; - health) - check_health - ;; - config) - config_cmd "${@:2}" - ;; + logs) show_logs "$@" ;; + health) check_health ;; + config) config_cmd "${@:2}" ;; purge) - [ $# -lt 2 ] && log_error "Usage: ${APP_CLI_NAME} purge --movie-id N | --series-id N | --path PATH | --tmdb ID | --tvdb ID" + [ $# -lt 2 ] && log_error "Usage: ${APP_CLI_NAME:-assemblrr} purge --movie-id N | --series-id N | --path PATH | --tmdb ID | --tvdb ID" purge_media "${@:2}" ;; - *) - log_error "Unknown command: $command\nRun '${APP_CLI_NAME} --help' for usage information" - ;; + *) log_error "Unknown command: $command\nRun '${APP_CLI_NAME:-assemblrr} --help' for usage information" ;; esac } -main "$@" +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi diff --git a/bin/config.sh b/bin/config.sh old mode 100644 new mode 100755 index fb297c3..7320d93 --- a/bin/config.sh +++ b/bin/config.sh @@ -1,17 +1,14 @@ #!/bin/bash -set -euo pipefail - +# SPDX-License-Identifier: GPL-3.0-or-later # Service wiring — invoked by setup and upgrade. # Exit 0 if all required steps succeed; exit 1 if any required step fails. +set -euo pipefail -# --- Config discovery --- - -# Locate lib/ directory (handles both repo layout and installed layout) _cfg_self="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" if [ -f "$_cfg_self/../lib/core.sh" ]; then - _lib_dir="$_cfg_self/../lib" # repo: bin/ and lib/ are siblings + _lib_dir="$_cfg_self/../lib" elif [ -f "$_cfg_self/lib/core.sh" ]; then - _lib_dir="$_cfg_self/lib" # installed: lib/ is subdirectory of install dir + _lib_dir="$_cfg_self/lib" elif [ -f "${ASSEMBLRR_DIR:-$HOME/assemblrr}/lib/core.sh" ]; then _lib_dir="${ASSEMBLRR_DIR:-$HOME/assemblrr}/lib" else @@ -19,235 +16,234 @@ else exit 1 fi -# Source core library (logging, colors, safe_source, find_install_directory) +# shellcheck source=/dev/null source "$_lib_dir/core.sh" -# Source branding +# shellcheck source=/dev/null source "$_lib_dir/branding.sh" +# shellcheck source=/dev/null +source "$_lib_dir/fzf-tui.sh" +# shellcheck source=/dev/null +source "$_lib_dir/api.sh" +# shellcheck source=/dev/null +source "$_lib_dir/arr.sh" +# shellcheck source=/dev/null +source "$_lib_dir/recyclarr.sh" +# shellcheck source=/dev/null +source "$_lib_dir/jellyfin.sh" +# shellcheck source=/dev/null +source "$_lib_dir/seerr.sh" +# shellcheck source=/dev/null +source "$_lib_dir/bazarr.sh" +# shellcheck source=/dev/null +source "$_lib_dir/usenet.sh" -INSTALL_DIR=$(find_install_directory) -if [ -z "$INSTALL_DIR" ]; then - log_error "Could not find installation. Run setup first." -fi +_cfg_log_info() { + echo " $1" + printf ' %s\n' "$1" >> "${CONFIGURE_LOG:-/dev/null}" +} -# Source runtime config and branding -safe_source "$INSTALL_DIR/.assemblrr-config" -load_branding "$INSTALL_DIR" - -# Source .env for VPN_ENABLED and other settings -set -a; safe_source "$INSTALL_DIR/.env"; set +a -API_HOST="${API_HOST:-127.0.0.1}" - -# --- Constants --- - -# Docker network URLs (for inter-service communication) -RADARR_DOCKER_URL="http://radarr:7878" -SONARR_DOCKER_URL="http://sonarr:8989" -PROWLARR_DOCKER_URL="http://prowlarr:9696" - -# Download client host depends on VPN mode -if [ "${VPN_ENABLED:-n}" = "y" ]; then - QBITTORRENT_HOST="gluetun" -else - QBITTORRENT_HOST="qbittorrent" -fi - -# Auth credentials -AUTH_USERNAME=$(cat "$INSTALL_DIR/secrets/auth_username.txt" 2>/dev/null || echo "$USER") -AUTH_PASSWORD=$(cat "$INSTALL_DIR/secrets/auth_password.txt" 2>/dev/null || echo "") - -# --- Logging --- - -# Always create a configure log file (same output for both express and manual) -CONFIGURE_LOG="/tmp/${APP_NAME}-configure-$(date '+%Y%m%d-%H%M%S').log" - -# Extended logging for configure (step markers on top of lib/core.sh base, tee to log file) -_cfg_log_info() { echo " $1" | tee -a "$CONFIGURE_LOG"; } - -# Step markers for the summary line (exit code uses _wire_critical_fail) _configure_total=0 _configure_ok=0 _configure_fail=0 -log_step() { echo -e " ${GREEN}✓${NC} $1" | tee -a "$CONFIGURE_LOG"; _configure_ok=$((_configure_ok + 1)); _configure_total=$((_configure_total + 1)); } -log_step_fail() { echo -e " ${RED}✗${NC} $1" | tee -a "$CONFIGURE_LOG"; _configure_fail=$((_configure_fail + 1)); _configure_total=$((_configure_total + 1)); } +log_step() { + printf ' %b✓%b %s\n' "${GREEN:-}" "${NC:-}" "$1" + printf ' ✓ %s\n' "$1" >> "${CONFIGURE_LOG:-/dev/null}" + _configure_ok=$((_configure_ok + 1)) + _configure_total=$((_configure_total + 1)) +} +log_step_fail() { + printf ' %b✗%b %s\n' "${RED:-}" "${NC:-}" "$1" >&2 + printf ' ✗ %s\n' "$1" >> "${CONFIGURE_LOG:-/dev/null}" + _configure_fail=$((_configure_fail + 1)) + _configure_total=$((_configure_total + 1)) +} _wire_critical_fail=0 _wire_optional_fail=0 -# Required step: on failure count and continue run_critical() { - set +e - "$@" - local rc=$? - set -e - if [ "$rc" -ne 0 ]; then + if ! "$@"; then _wire_critical_fail=$((_wire_critical_fail + 1)) fi return 0 } -# Nice-to-have step: never fails the overall run run_optional() { - set +e - "$@" - local rc=$? - set -e - if [ "$rc" -ne 0 ]; then + if ! "$@"; then _wire_optional_fail=$((_wire_optional_fail + 1)) fi return 0 } -# Prompt for custom indexers (fzf TUI) -source "$_lib_dir/fzf-tui.sh" +main() { + INSTALL_DIR=$(find_install_directory || true) + if [ -z "${INSTALL_DIR:-}" ]; then + log_error "Could not find installation. Run setup first." + fi -# --- API helpers --- -source "$_lib_dir/api.sh" + safe_source "$INSTALL_DIR/.assemblrr-config" + load_branding "$INSTALL_DIR" + set -a + [ -f "$INSTALL_DIR/.env" ] && safe_source "$INSTALL_DIR/.env" + set +a -# --- Service configuration modules --- -source "$_lib_dir/arr.sh" -source "$_lib_dir/jellyfin.sh" -source "$_lib_dir/seerr.sh" -source "$_lib_dir/bazarr.sh" + API_HOST="${API_HOST:-127.0.0.1}" + RADARR_DOCKER_URL="${RADARR_DOCKER_URL:-http://radarr:7878}" + SONARR_DOCKER_URL="${SONARR_DOCKER_URL:-http://sonarr:8989}" + PROWLARR_DOCKER_URL="${PROWLARR_DOCKER_URL:-http://prowlarr:9696}" + if [ "${VPN_ENABLED:-n}" = "y" ] || [ "${VPN_ENABLED:-n}" = "Y" ]; then + QBITTORRENT_HOST="gluetun" + else + QBITTORRENT_HOST="qbittorrent" + fi -# --- Main --- + AUTH_USERNAME=$(cat "$INSTALL_DIR/secrets/auth_username.txt" 2>/dev/null || echo "$USER") + AUTH_PASSWORD=$(cat "$INSTALL_DIR/secrets/auth_password.txt" 2>/dev/null || echo "") + CONFIGURE_LOG="${CONFIGURE_LOG:-/tmp/${APP_NAME:-assemblrr}-configure-$(date '+%Y%m%d-%H%M%S').log}" -echo -_cfg_log_info "Wiring ${APP_DISPLAY_NAME} services..." + echo + _cfg_log_info "Wiring ${APP_DISPLAY_NAME} services..." -# API keys from config.xml (services write these on first start) -RADARR_API_KEY="" -SONARR_API_KEY="" -PROWLARR_API_KEY="" - -if ! RADARR_API_KEY=$(read_api_key "radarr"); then RADARR_API_KEY="" - _wire_critical_fail=$((_wire_critical_fail + 1)) -fi - -if ! SONARR_API_KEY=$(read_api_key "sonarr"); then SONARR_API_KEY="" - _wire_critical_fail=$((_wire_critical_fail + 1)) -fi - -if ! PROWLARR_API_KEY=$(read_api_key "prowlarr"); then PROWLARR_API_KEY="" - _wire_critical_fail=$((_wire_critical_fail + 1)) -fi -# Drop key if API never becomes ready so later steps skip that service -if [ -n "$RADARR_API_KEY" ]; then - if ! wait_for_api "Radarr" "7878" "$RADARR_API_KEY"; then + if ! RADARR_API_KEY=$(read_api_key "radarr"); then + RADARR_API_KEY="" + _wire_critical_fail=$((_wire_critical_fail + 1)) + fi + if ! SONARR_API_KEY=$(read_api_key "sonarr"); then + SONARR_API_KEY="" + _wire_critical_fail=$((_wire_critical_fail + 1)) + fi + if ! PROWLARR_API_KEY=$(read_api_key "prowlarr"); then + PROWLARR_API_KEY="" + _wire_critical_fail=$((_wire_critical_fail + 1)) + fi + + if [ -n "$RADARR_API_KEY" ] && ! wait_for_api "Radarr" "7878" "$RADARR_API_KEY"; then _wire_critical_fail=$((_wire_critical_fail + 1)) RADARR_API_KEY="" fi -fi - -if [ -n "$SONARR_API_KEY" ]; then - if ! wait_for_api "Sonarr" "8989" "$SONARR_API_KEY"; then + if [ -n "$SONARR_API_KEY" ] && ! wait_for_api "Sonarr" "8989" "$SONARR_API_KEY"; then _wire_critical_fail=$((_wire_critical_fail + 1)) SONARR_API_KEY="" fi -fi - -if [ -n "$PROWLARR_API_KEY" ]; then - if wait_for_api "Prowlarr" "9696" "$PROWLARR_API_KEY" "/api/v1/system/status"; then - run_optional configure_indexers "$PROWLARR_API_KEY" - else - _wire_critical_fail=$((_wire_critical_fail + 1)) - PROWLARR_API_KEY="" + if [ -n "$PROWLARR_API_KEY" ]; then + if wait_for_api "Prowlarr" "9696" "$PROWLARR_API_KEY" "/api/v1/system/status"; then + run_optional configure_indexers "$PROWLARR_API_KEY" + else + _wire_critical_fail=$((_wire_critical_fail + 1)) + PROWLARR_API_KEY="" + fi fi -fi -if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then - run_critical qbit_set_credentials -fi + if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then + run_critical qbit_set_credentials + fi -if [ -n "$RADARR_API_KEY" ]; then - run_critical configure_radarr "$RADARR_API_KEY" - run_optional add_arr_purge_hook "Radarr" "7878" "$RADARR_API_KEY" -fi + if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then + run_critical configure_sabnzbd + fi -if [ -n "$SONARR_API_KEY" ]; then - run_critical configure_sonarr "$SONARR_API_KEY" - run_optional add_arr_purge_hook "Sonarr" "8989" "$SONARR_API_KEY" -fi + if [ -n "$RADARR_API_KEY" ]; then + run_critical configure_radarr "$RADARR_API_KEY" + run_optional add_arr_purge_hook "Radarr" "7878" "$RADARR_API_KEY" + fi -if [ -n "$PROWLARR_API_KEY" ]; then - run_critical configure_prowlarr "$PROWLARR_API_KEY" "$RADARR_API_KEY" "$SONARR_API_KEY" -fi + if [ -n "$SONARR_API_KEY" ]; then + run_critical configure_sonarr "$SONARR_API_KEY" + run_optional add_arr_purge_hook "Sonarr" "8989" "$SONARR_API_KEY" + fi + + if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then + if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then + run_critical arr_configure_sabnzbd + fi + fi + + if [ -n "$PROWLARR_API_KEY" ]; then + run_critical configure_prowlarr "$PROWLARR_API_KEY" "$RADARR_API_KEY" "$SONARR_API_KEY" + if [ "${BYPARR_ENABLED:-n}" = "y" ] || [ "${BYPARR_ENABLED:-n}" = "Y" ]; then + run_optional prowlarr_sync_byparr_proxy "$PROWLARR_API_KEY" + fi + fi -if [ "${MEDIA_SERVICE:-}" = "jellyfin" ]; then run_critical configure_jellyfin run_optional configure_jellyfin_notifications -fi -# Bazarr after *arr (+ Jellyfin key when available): auto-subs for Sonarr/Radarr library -if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then - run_optional configure_subtitle_providers - run_critical configure_bazarr -fi - -# Recyclarr before Seerr (profiles must exist for Seerr defaults) -run_critical configure_recyclarr - -if [ -n "$RADARR_API_KEY" ]; then - run_critical relax_quality_sizes "Radarr" "7878" "$RADARR_API_KEY" - run_critical set_default_quality_profile "Radarr" "7878" "$RADARR_API_KEY" "lookup_radarr_profile" -fi -if [ -n "$SONARR_API_KEY" ]; then - run_critical relax_quality_sizes "Sonarr" "8989" "$SONARR_API_KEY" - run_critical set_default_quality_profile "Sonarr" "8989" "$SONARR_API_KEY" "lookup_sonarr_profile" -fi - -# Existing files under media roots → *arr library (so Bazarr/Seerr see them) -if [ -n "$RADARR_API_KEY" ]; then - run_optional import_radarr_existing_media "$RADARR_API_KEY" -fi -if [ -n "$SONARR_API_KEY" ]; then - run_optional import_sonarr_existing_media "$SONARR_API_KEY" -fi -# After imports, pull *arr library into Bazarr -run_optional trigger_bazarr_library_sync - -run_critical configure_seerr - -echo -if [ "$_wire_critical_fail" -gt 0 ]; then - echo -e " ${RED}Wiring failed: ${_wire_critical_fail} required step(s)${NC}" | tee -a "$CONFIGURE_LOG" - if [ "$_configure_ok" -gt 0 ] || [ "$_configure_fail" -gt 0 ]; then - echo -e " ${YELLOW}${_configure_ok} ok, ${_configure_fail} failed (see markers above)${NC}" | tee -a "$CONFIGURE_LOG" + if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then + run_optional configure_subtitle_providers + run_critical configure_bazarr fi - echo -e " ${YELLOW}Log: $CONFIGURE_LOG${NC}" | tee -a "$CONFIGURE_LOG" - echo - _cfg_log_info "Fix issues, then re-run: ${APP_CLI_NAME:-assemblrr} config apply" - echo - exit 1 -fi -if [ "$_configure_fail" -gt 0 ] || [ "$_wire_optional_fail" -gt 0 ]; then - echo -e " ${GREEN}Required wiring succeeded${NC}" | tee -a "$CONFIGURE_LOG" - echo -e " ${YELLOW}Some optional steps had issues — log: $CONFIGURE_LOG${NC}" | tee -a "$CONFIGURE_LOG" - echo -else - echo -e " ${GREEN}All ${_configure_ok} steps succeeded${NC}" | tee -a "$CONFIGURE_LOG" - echo -fi + if [ -n "$RADARR_API_KEY" ] || [ -n "$SONARR_API_KEY" ]; then + run_critical configure_recyclarr + if [ -n "$RADARR_API_KEY" ]; then + run_critical relax_quality_sizes "Radarr" "7878" "$RADARR_API_KEY" + run_critical set_default_quality_profile "Radarr" "7878" "$RADARR_API_KEY" "lookup_radarr_profile" + fi + if [ -n "$SONARR_API_KEY" ]; then + run_critical relax_quality_sizes "Sonarr" "8989" "$SONARR_API_KEY" + run_critical set_default_quality_profile "Sonarr" "8989" "$SONARR_API_KEY" "lookup_sonarr_profile" + fi + if [ -n "$RADARR_API_KEY" ]; then + run_optional import_radarr_existing_media "$RADARR_API_KEY" + fi + if [ -n "$SONARR_API_KEY" ]; then + run_optional import_sonarr_existing_media "$SONARR_API_KEY" + fi + run_optional trigger_bazarr_library_sync + run_critical configure_seerr + else + _cfg_log_info "Skipping Recyclarr & Seerr wiring (neither Radarr nor Sonarr API key available)" + fi -_cfg_log_info "Next steps:" -if [ "${MEDIA_SERVICE:-}" = "jellyfin" ]; then - _cfg_log_info " 1. Open Jellyfin at http://${API_HOST}:8096" - _cfg_log_info " 2. Open Seerr at http://${API_HOST}:5055 and request a movie" - _cfg_log_info " 3. It will download via qBittorrent; Bazarr grabs subtitles; Jellyfin shows both" - _cfg_log_info " 4. Bazarr UI: http://${API_HOST}:6767" -else - _cfg_log_info " 1. Open Seerr at http://${API_HOST}:5055" - _cfg_log_info " 2. Request a movie — it will download automatically via qBittorrent" - _cfg_log_info " 3. Bazarr downloads subtitles alongside media (http://${API_HOST}:6767)" - _cfg_log_info " 4. Your media service will pick up video + sidecar subs from your media folder" -fi -echo -if [ -n "$AUTH_USERNAME" ]; then - _cfg_log_info "Login credentials: $AUTH_USERNAME / (the password you set during setup)" -fi + echo + if [ "$_wire_critical_fail" -gt 0 ]; then + printf ' %bWiring failed: %s required step(s)%b\n' "${RED:-}" "${_wire_critical_fail}" "${NC:-}" + printf ' Wiring failed: %s required step(s)\n' "${_wire_critical_fail}" >> "$CONFIGURE_LOG" + if [ "$_configure_ok" -gt 0 ] || [ "$_configure_fail" -gt 0 ]; then + printf ' %b%s ok, %s failed (see markers above)%b\n' "${YELLOW:-}" "${_configure_ok}" "${_configure_fail}" "${NC:-}" + printf ' %s ok, %s failed (see markers above)\n' "${_configure_ok}" "${_configure_fail}" >> "$CONFIGURE_LOG" + fi + printf ' %bLog: %s%b\n\n' "${YELLOW:-}" "$CONFIGURE_LOG" "${NC:-}" + _cfg_log_info "Fix issues, then re-run: ${APP_CLI_NAME:-assemblrr} config apply" + echo + exit 1 + fi -exit 0 + if [ "$_configure_fail" -gt 0 ] || [ "$_wire_optional_fail" -gt 0 ]; then + printf ' %bRequired wiring succeeded%b\n' "${GREEN:-}" "${NC:-}" + printf ' %bSome optional steps had issues — log: %s%b\n' "${YELLOW:-}" "$CONFIGURE_LOG" "${NC:-}" + printf ' Required wiring succeeded (optional issues: %s)\n' "$_wire_optional_fail" >> "$CONFIGURE_LOG" + else + printf ' %b✓ All %s wiring steps succeeded%b\n' "${GREEN:-}" "${_configure_ok}" "${NC:-}" + printf ' All %s wiring steps succeeded\n' "${_configure_ok}" >> "$CONFIGURE_LOG" + fi + + if [ "${ASSEMBLRR_FROM_SETUP:-0}" = "1" ]; then + exit 0 + fi + + echo + local ui_host="$API_HOST" + [ "$ui_host" = "127.0.0.1" ] && ui_host="localhost" + _cfg_log_info "Next steps:" + _cfg_log_info " 1. Open Jellyfin at http://${ui_host}:8096" + _cfg_log_info " 2. Open Seerr at http://${ui_host}:5055 and request a movie or show" + _cfg_log_info " 3. qBittorrent UI: http://${ui_host}:8081 | Bazarr UI: http://${ui_host}:6767" + if [ "${USENET_ENABLED:-n}" = "y" ] || [ "${USENET_ENABLED:-n}" = "Y" ]; then + _cfg_log_info " 4. SABnzbd UI: http://${ui_host}:8085" + fi + echo + if [ -n "$AUTH_USERNAME" ]; then + _cfg_log_info "Login credentials: $AUTH_USERNAME / (the password you set during setup)" + fi + + exit 0 +} + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi diff --git a/bin/docker-install.sh b/bin/docker-install.sh old mode 100644 new mode 100755 index 40da992..912ce1f --- a/bin/docker-install.sh +++ b/bin/docker-install.sh @@ -1,22 +1,24 @@ #!/bin/bash -set -euo pipefail - -# Docker installation helper — supports multiple distros +# SPDX-License-Identifier: GPL-3.0-or-later +# Docker installation helper — supports Ubuntu/Debian/derivatives, Arch, Fedora # Called by setup.sh when Docker is not found +set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" APP_ROOT="$SCRIPT_DIR" -# Source shared library (safe_source, logging, colors) if [ -f "$SCRIPT_DIR/../lib/core.sh" ]; then APP_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + # shellcheck source=/dev/null source "$APP_ROOT/lib/core.sh" + # shellcheck source=/dev/null source "$APP_ROOT/lib/branding.sh" elif [ -f "$SCRIPT_DIR/lib/core.sh" ]; then + # shellcheck source=/dev/null source "$SCRIPT_DIR/lib/core.sh" + # shellcheck source=/dev/null source "$SCRIPT_DIR/lib/branding.sh" else - # Minimal fallback if lib modules are not available log_error() { echo -e "\033[0;31m$1\033[0m" >&2; exit 1; } log_info() { echo "$1"; } log_success() { echo -e "\033[0;32m$1\033[0m"; } @@ -27,14 +29,13 @@ else } fi -# Source branding — use load_branding for validation + fallback load_branding "$APP_ROOT" detect_distro() { if [ -f /etc/os-release ]; then # shellcheck disable=SC1091 . /etc/os-release - echo "$ID" + echo "${ID:-unknown}" elif [ -f /etc/arch-release ]; then echo "arch" elif [ -f /etc/fedora-release ]; then @@ -46,17 +47,32 @@ detect_distro() { install_docker_debian() { local distro_id="$1" - local codename - codename=$(lsb_release -cs 2>/dev/null || echo "unknown") + local repo_distro="$distro_id" + local codename="" + + if [ -f /etc/os-release ]; then + # shellcheck disable=SC1091 + . /etc/os-release + codename="${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}" + fi + if [ -z "$codename" ]; then + codename=$(lsb_release -cs 2>/dev/null || echo "noble") + fi + + # Linux Mint, Pop!_OS, and elementary OS track Ubuntu upstream repos on download.docker.com + case "$distro_id" in + linuxmint|pop|elementary) repo_distro="ubuntu" ;; + esac sudo apt-get update sudo apt-get install -y ca-certificates curl gnupg lsb-release sudo mkdir -p /etc/apt/keyrings - curl -fsSL "https://download.docker.com/linux/$distro_id/gpg" | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg + curl -fsSL "https://download.docker.com/linux/$repo_distro/gpg" \ + | sudo gpg --yes --batch --dearmor -o /etc/apt/keyrings/docker.gpg - echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/$distro_id \ -$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null + echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/$repo_distro $codename stable" \ + | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin @@ -72,7 +88,10 @@ install_docker_arch() { install_docker_fedora() { sudo dnf install -y dnf-plugins-core - sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo + # Fedora 41+ uses DNF5 (`addrepo --from-repofile=...`); older releases use `--add-repo`. + if ! sudo dnf config-manager addrepo --overwrite --from-repofile=https://download.docker.com/linux/fedora/docker-ce.repo 2>/dev/null; then + sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo + fi sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin } @@ -97,12 +116,14 @@ main() { ;; esac - # Add user to docker group sudo usermod -aG docker "$USER" - # Start Docker service - sudo systemctl enable docker - sudo systemctl start docker + if [ "$(ps -p 1 -o comm= 2>/dev/null || true)" = "systemd" ]; then + sudo systemctl enable docker + sudo systemctl start docker + else + log_info "Non-systemd environment detected — start dockerd or Docker Desktop manually if needed." + fi log_success "Docker installed successfully!" log_info "NOTE: You may need to log out and back in for group changes to take effect." @@ -110,4 +131,6 @@ main() { exit 0 } -main +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi diff --git a/bin/setup.sh b/bin/setup.sh old mode 100644 new mode 100755 index 3ed0bfc..906cfd8 --- a/bin/setup.sh +++ b/bin/setup.sh @@ -1,11 +1,11 @@ #!/bin/bash +# SPDX-License-Identifier: GPL-3.0-or-later +# assemblrr first-time setup, reconfigure, and backup-restore wizard set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" APP_ROOT="" -# Support both repository layout (`bin/` + `lib/`) and installed layout -# (entrypoints copied into the install root with `lib/` underneath). if [ -f "$SCRIPT_DIR/../lib/core.sh" ]; then APP_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" elif [ -f "$SCRIPT_DIR/lib/core.sh" ]; then @@ -18,124 +18,59 @@ fi resolve_project_file() { local relative_path="$1" local candidate="$APP_ROOT/$relative_path" - if [ -f "$candidate" ]; then echo "$candidate" return 0 fi - case "$relative_path" in - bin/*) - candidate="$APP_ROOT/${relative_path#bin/}" - ;; + bin/*) candidate="$APP_ROOT/${relative_path#bin/}" ;; esac - if [ -f "$candidate" ]; then echo "$candidate" return 0 fi - return 1 } -# Source core library (logging, colors, safe_source, path utilities) +# shellcheck source=/dev/null source "$APP_ROOT/lib/core.sh" - -# Source branding — all names/paths come from here +# shellcheck source=/dev/null source "$APP_ROOT/lib/branding.sh" load_branding "$APP_ROOT" - -# Source Docker Compose builder +# shellcheck source=/dev/null source "$APP_ROOT/lib/compose.sh" - -# Source VPN helpers +# shellcheck source=/dev/null source "$APP_ROOT/lib/vpn.sh" +# shellcheck source=/dev/null +source "$APP_ROOT/lib/managed_files.sh" +# shellcheck source=/dev/null +source "$APP_ROOT/lib/fzf-tui.sh" +# shellcheck source=/dev/null +source "$APP_ROOT/lib/services.sh" +# shellcheck source=/dev/null +source "$APP_ROOT/lib/quality.sh" +# shellcheck source=/dev/null +[ -f "$APP_ROOT/lib/qbit.sh" ] && source "$APP_ROOT/lib/qbit.sh" +# shellcheck source=/dev/null +[ -f "$APP_ROOT/lib/usenet.sh" ] && source "$APP_ROOT/lib/usenet.sh" +# shellcheck source=/dev/null +source "$APP_ROOT/lib/prompts.sh" -echo "====================================================" -echo " | | | | " -echo " __ _ ___ ___ ___ _ __ ___ | |__ | |_ __ _ __ " -echo " / _\` / __/ __|/ _ \ '_ \` _ \\| '_ \\| | '__| '__|" -echo "| (_| \\__ \\__ \\ __/ | | | | | |_) | | | | | " -echo " \\__,_|___/___/\\___|_| |_| |_|_.__/|_|_| |_| " -echo " " -echo "====================================================" -echo "Welcome to ${APP_DISPLAY_NAME} (${APP_DESCRIPTION})" -echo "====================================================" -echo "" - -# --- Setup mode & argument parsing --- -RESTORE_BACKUP_FILE="" -while [ $# -gt 0 ]; do - case "$1" in - --restore) - SETUP_MODE="restore" - if [ -n "${2:-}" ] && [[ ! "$2" =~ ^-- ]]; then - RESTORE_BACKUP_FILE="$2" - shift - fi - shift - ;; - --restore=*) - SETUP_MODE="restore" - RESTORE_BACKUP_FILE="${1#*=}" - shift - ;; - --express) - SETUP_MODE="express" - shift - ;; - --manual) - SETUP_MODE="manual" - shift - ;; - *) - shift - ;; - esac -done - -if [ -z "${SETUP_MODE:-}" ]; then - echo " 1) Express (recommended — minimal questions, smart defaults)" - echo " 2) Manual (full control over every setting)" - echo " 3) Restore (rebuild stack from an existing backup archive)" - while true; do - read -p "Choose setup mode [1]: " setup_mode_choice - setup_mode_choice=${setup_mode_choice:-1} - case "$setup_mode_choice" in - 1) SETUP_MODE="express"; break ;; - 2) SETUP_MODE="manual"; break ;; - 3) SETUP_MODE="restore"; break ;; - *) log_warning "Invalid choice. Please choose 1, 2, or 3." ;; - esac - done -fi -export SETUP_MODE - -if [ "$SETUP_MODE" = "express" ]; then - echo "" - log_success "Express mode — we'll use smart defaults and only ask the essentials." - echo "" -elif [ "$SETUP_MODE" = "restore" ]; then - echo "" - log_info "Restore mode — we'll rebuild your stack from an existing backup archive." - echo "" -else - echo "" - log_info "Manual mode — you'll configure every setting." - echo "" -fi - -# Constants -readonly SUPPORTED_MEDIA_SERVICES=("jellyfin" "emby" "plex") +readonly SUPPORTED_MEDIA_SERVICES=("jellyfin") readonly DEFAULT_MEDIA_SERVICE="jellyfin" readonly DEFAULT_VPN_SERVICE="protonvpn" -readonly MEDIA_SUBDIRS=("torrents/movies" "torrents/tv" "media/movies" "media/tv" "blackhole") +readonly MEDIA_SUBDIRS=("torrents/movies" "torrents/tv" "torrents/incomplete" "usenet/incomplete" "usenet/complete/movies" "usenet/complete/tv" "media/movies" "media/tv" "blackhole") +readonly REQUIRED_COMMANDS=("curl" "jq" "sed" "awk" "envsubst" "fzf" "python3") -# Dependencies -readonly REQUIRED_COMMANDS=("curl" "jq" "sed" "awk" "envsubst" "fzf") - -# LOG_FILE is set in main() — lib/core.sh log_info/log_debug handle file logging natively -# Path utilities (expand_path, read_masked, create_and_verify_directory, etc.) are in lib/core.sh +setup_show_help() { + echo "Usage: setup.sh [--express | --manual | --restore [archive.tar.gz] | --reconfigure]" + echo + echo "Modes:" + echo " --express Minimal prompts with smart defaults" + echo " --manual Full interactive setup (including optional overlays)" + echo " --reconfigure Re-run wizard on an existing installation" + echo " --restore FILE Rebuild stack from a backup archive" +} detect_package_manager() { if command -v apt-get &>/dev/null; then @@ -151,10 +86,34 @@ detect_package_manager() { fi } +_map_distro_package() { + local pm="$1" cmd="$2" + case "$cmd" in + envsubst) + case "$pm" in + apt) echo "gettext-base" ;; + *) echo "gettext" ;; + esac + ;; + python3) + case "$pm" in + pacman) echo "python" ;; + *) echo "python3" ;; + esac + ;; + *) + echo "$cmd" + ;; + esac +} + install_packages() { - local pkgs=("$@") - local pm + local pm pkgs=() c mapped pm=$(detect_package_manager) + for c in "$@"; do + mapped=$(_map_distro_package "$pm" "$c") + pkgs+=("$mapped") + done case "$pm" in apt) @@ -164,8 +123,6 @@ install_packages() { echo log_warning "Arch Linux: about to run a full system upgrade (pacman -Syu)." log_info "A partial install (-Sy without -u) can break jq (GLIBC mismatch)." - log_info "This updates the whole system, then installs: ${pkgs[*]}" - echo sudo pacman -Syu --noconfirm --needed "${pkgs[@]}" ;; dnf) @@ -181,10 +138,10 @@ install_packages() { } check_dependencies() { - local missing_packages=() + local missing_packages=() pkg works for pkg in "${REQUIRED_COMMANDS[@]}"; do - local works=false + works=false if command -v "$pkg" &>/dev/null; then case "$pkg" in curl) curl --version &>/dev/null && works=true ;; @@ -193,10 +150,10 @@ check_dependencies() { sed) echo "" | sed '' &>/dev/null && works=true ;; envsubst) echo "" | envsubst &>/dev/null && works=true ;; fzf) fzf --version &>/dev/null && works=true ;; + python3) python3 --version &>/dev/null && works=true ;; *) works=true ;; esac fi - if ! $works; then missing_packages+=("$pkg") else @@ -206,33 +163,14 @@ check_dependencies() { if [ ${#missing_packages[@]} -gt 0 ]; then log_warning "Missing required packages: ${missing_packages[*]}" - read -p "Would you like to install the missing packages? (y/N) [Default = n]: " install_deps + local install_deps="n" + read_prompt "Would you like to install the missing packages? (y/N) [Default = n]: " install_deps install_deps=${install_deps:-"n"} if [ "${install_deps,,}" = "y" ]; then echo "Installing missing packages..." if ! install_packages "${missing_packages[@]}"; then - log_error "Failed to install missing packages. Please install them manually: ${missing_packages[*]}" - fi - local still_broken=() - local pkg - for pkg in "${missing_packages[@]}"; do - case "$pkg" in - jq) echo "{}" | jq . &>/dev/null || still_broken+=("$pkg") ;; - fzf) fzf --version &>/dev/null || still_broken+=("$pkg") ;; - curl) curl --version &>/dev/null || still_broken+=("$pkg") ;; - *) command -v "$pkg" &>/dev/null || still_broken+=("$pkg") ;; - esac - done - if [ ${#still_broken[@]} -gt 0 ]; then - echo - log_warning "Installed, but still not runnable: ${still_broken[*]}" - if printf '%s\n' "${still_broken[@]}" | grep -qx jq; then - jq . &1 | head -5 || true - log_info "On Arch this is usually a partial upgrade. In WSL run: sudo pacman -Syu" - log_info "Then open a new WSL terminal and re-run setup." - fi - log_error "Please fix the packages above and re-run setup." + log_error "Failed to install missing packages. Please install manually: ${missing_packages[*]}" fi log_success "Successfully installed missing packages" else @@ -240,20 +178,15 @@ check_dependencies() { fi fi - # Check Docker and Docker Compose if ! verify_docker; then if ! command -v docker &>/dev/null || ! docker compose version &>/dev/null; then log_warning "Docker/Docker Compose not found!" - - # If in WSL2, do not attempt to install Docker inside the distro. - # Recommend installing Docker Desktop on Windows. if grep -qi microsoft /proc/version 2>/dev/null; then - log_error "WSL2 environment detected, but Docker Desktop is not running or not installed on Windows.\n\nPlease install Docker Desktop for Windows and enable WSL2 integration:\n https://docs.docker.com/desktop/wsl/" + log_error "WSL2 detected, but Docker Desktop is not running or not installed on Windows.\n\nPlease install Docker Desktop for Windows and enable WSL2 integration:\n https://docs.docker.com/desktop/wsl/" fi - - read -p "Install Docker and Docker Compose? (y/N) [Default = n]: " install_docker + local install_docker="n" + read_prompt "Install Docker and Docker Compose? (y/N) [Default = n]: " install_docker install_docker=${install_docker:-"n"} - if [ "${install_docker,,}" = "y" ]; then bash "$SCRIPT_DIR/docker-install.sh" if ! verify_docker; then @@ -267,26 +200,15 @@ check_dependencies() { fi fi - # Perform snap check if docker is installed if command -v docker &>/dev/null; then if [ "$(command -v docker)" = "/snap/bin/docker" ]; then - log_error "Docker is installed via snap. ${APP_DISPLAY_NAME} requires the official Docker installation. Please remove snap Docker and install from https://docs.docker.com/engine/install/" + log_error "Docker is installed via snap. ${APP_DISPLAY_NAME} requires the official Docker installation: https://docs.docker.com/engine/install/" fi log_success "Docker is installed and running" fi - return 0 } -# --- Setup prompts (sourced from lib/prompts.sh) --- -# Requires: lib/core.sh already sourced, constants defined above -# fzf-tui helpers (fzf_multi_select, fzf_single_select_data) must be sourced before prompts -source "$APP_ROOT/lib/managed_files.sh" -source "$APP_ROOT/lib/fzf-tui.sh" -source "$APP_ROOT/lib/services.sh" -source "$APP_ROOT/lib/quality.sh" -source "$APP_ROOT/lib/prompts.sh" - _copy_stall_error() { log_error "Timed out writing to ${install_directory} — the drive looks stuck (flaky USB / WSL). From PowerShell: wsl --shutdown — then check the drive in Explorer, or re-run setup and pick Home." } @@ -315,8 +237,8 @@ copy_configuration_files() { fi if ! src_path=$(resolve_project_file "$src"); then - if [[ "$src" == compose/examples/* ]]; then - log_debug "Optional example file not found: $src" + if [[ "$src" == compose/examples/* ]] || [[ "$src" == NOTICE ]]; then + log_debug "Optional file not found: $src" continue fi log_error "Failed to locate source file: $src" @@ -329,7 +251,9 @@ copy_configuration_files() { _copy_stall_error elif [ "$rc" -eq 0 ]; then case "$src" in - scripts/*|bin/cli.sh|bin/config.sh|bin/setup.sh) chmod +x "$dest_path" ;; + scripts/*.sh|scripts/*.py|bin/*.sh|migrations/*.sh|platform/linux/*.sh) + chmod +x "$dest_path" 2>/dev/null || true + ;; esac copied=$((copied + 1)) else @@ -341,11 +265,9 @@ copy_configuration_files() { generate_env_file() { local env_file="$install_directory/.env" - log_debug "Generating environment configuration..." - # Set VPN-related variables for envsubst (credentials go to secrets/) - if [ "${setup_vpn,,}" == "y" ]; then + if [ "${setup_vpn,,}" = "y" ]; then VPN_ENABLED="y" VPN_SERVICE="$vpn_service" VPN_TYPE="$vpn_type" @@ -366,30 +288,32 @@ generate_env_file() { VPN_PORT_FORWARDING="off" fi - # Export all variables for envsubst API_HOST="${API_HOST:-127.0.0.1}" export PUID="$puid" export PGID="$pgid" export MEDIA_DIRECTORY="$media_directory" export INSTALL_DIRECTORY="$install_directory" - export MEDIA_SERVICE="$media_service" + export MEDIA_SERVICE="${media_service:-jellyfin}" export TZ="$tz" export VPN_ENABLED VPN_SERVICE VPN_TYPE export WIREGUARD_ADDRESSES export PORT_FORWARD_ONLY VPN_PORT_FORWARDING + export VUETORRENT_ENABLED="${vuetorrent_enabled:-y}" + export GPU_TRANSCODING="${gpu_transcoding:-none}" + export BYPARR_ENABLED="${byparr_enabled:-n}" + export USENET_ENABLED="${usenet_enabled:-n}" export API_HOST local env_template if ! env_template=$(resolve_project_file ".env.example"); then log_error "Failed to locate .env.example" fi - # Explicit key list so envsubst does not pull in unrelated shell variables - envsubst '${PUID} ${PGID} ${MEDIA_DIRECTORY} ${INSTALL_DIRECTORY} ${MEDIA_SERVICE} ${TZ} ${VPN_ENABLED} ${VPN_SERVICE} ${VPN_TYPE} ${WIREGUARD_ADDRESSES} ${PORT_FORWARD_ONLY} ${VPN_PORT_FORWARDING} ${API_HOST}' \ + # Explicit key list matching .env.example 1-to-1 + envsubst '${PUID} ${PGID} ${MEDIA_DIRECTORY} ${INSTALL_DIRECTORY} ${MEDIA_SERVICE} ${TZ} ${VPN_ENABLED} ${VPN_SERVICE} ${VPN_TYPE} ${WIREGUARD_ADDRESSES} ${PORT_FORWARD_ONLY} ${VPN_PORT_FORWARDING} ${VUETORRENT_ENABLED} ${GPU_TRANSCODING} ${BYPARR_ENABLED} ${USENET_ENABLED} ${API_HOST}' \ < "$env_template" | tr -d '\r' > "$env_file" || \ log_error "Failed to generate .env file" chmod 600 "$env_file" - log_debug "Environment configuration generated ($env_file)" } @@ -397,80 +321,48 @@ write_vpn_secrets() { if [ "${setup_vpn,,}" != "y" ]; then return 0 fi - local secrets_dir="$install_directory/secrets" mkdir -p "$secrets_dir" + chmod 700 "$secrets_dir" if [ "$vpn_type" = "openvpn" ]; then - echo -n "${vpn_user:-}" > "$secrets_dir/openvpn_user.txt" - echo -n "${vpn_password:-}" > "$secrets_dir/openvpn_password.txt" - # Create empty WireGuard secret so the secret definition always resolves - : > "$secrets_dir/wireguard_private_key.txt" + write_secret_file "$secrets_dir/openvpn_user.txt" "${vpn_user:-}" + write_secret_file "$secrets_dir/openvpn_password.txt" "${vpn_password:-}" + write_secret_file "$secrets_dir/wireguard_private_key.txt" "" else - echo -n "${wireguard_private_key:-}" > "$secrets_dir/wireguard_private_key.txt" - # Create empty OpenVPN secrets so the secret definitions always resolve - : > "$secrets_dir/openvpn_user.txt" - : > "$secrets_dir/openvpn_password.txt" + write_secret_file "$secrets_dir/wireguard_private_key.txt" "${wireguard_private_key:-}" + write_secret_file "$secrets_dir/openvpn_user.txt" "" + write_secret_file "$secrets_dir/openvpn_password.txt" "" fi - - chmod 600 "$secrets_dir"/*.txt log_success "VPN secrets written to $secrets_dir" } write_auth_secrets() { local secrets_dir="$install_directory/secrets" mkdir -p "$secrets_dir" - - echo -n "${auth_username:-admin}" > "$secrets_dir/auth_username.txt" - echo -n "${auth_password:-}" > "$secrets_dir/auth_password.txt" - chmod 600 "$secrets_dir/auth_username.txt" "$secrets_dir/auth_password.txt" + chmod 700 "$secrets_dir" + write_secret_file "$secrets_dir/auth_username.txt" "${auth_username:-admin}" + write_secret_file "$secrets_dir/auth_password.txt" "${auth_password:-}" log_success "Auth credentials written to $secrets_dir" } write_opensubtitles_secrets() { local secrets_dir="$install_directory/secrets" mkdir -p "$secrets_dir" - if [ "${opensubtitles_enabled:-n}" = "y" ] && [ -n "${opensubtitles_username:-}" ]; then - echo -n "${opensubtitles_username}" > "$secrets_dir/opensubtitles_username.txt" - echo -n "${opensubtitles_password:-}" > "$secrets_dir/opensubtitles_password.txt" - chmod 600 "$secrets_dir/opensubtitles_username.txt" "$secrets_dir/opensubtitles_password.txt" + write_secret_file "$secrets_dir/opensubtitles_username.txt" "${opensubtitles_username}" + write_secret_file "$secrets_dir/opensubtitles_password.txt" "${opensubtitles_password:-}" log_success "OpenSubtitles.com credentials written to $secrets_dir" else - # Clear stale creds if user opted out on re-run rm -f "$secrets_dir/opensubtitles_username.txt" "$secrets_dir/opensubtitles_password.txt" 2>/dev/null || true fi } -write_qbittorrent_config() { - local qbit_config_dir="$install_directory/config/qbittorrent/qBittorrent" - mkdir -p "$qbit_config_dir" - - local pbkdf2_hash - pbkdf2_hash=$(qbit_generate_pbkdf2 "${auth_password:-}") - - if [ -n "$pbkdf2_hash" ]; then - if [ "${setup_vpn,,}" = "y" ]; then - cat > "$qbit_config_dir/qBittorrent.conf" << EOF -[BitTorrent] -Session\Interface=tun0 -Session\InterfaceName=tun0 - -[Preferences] -WebUI\Username=${auth_username:-admin} -WebUI\Password_PBKDF2=$pbkdf2_hash -WebUI\Port=8081 -EOF - log_success "Pre-configured qBittorrent credentials and tun0 bind" - else - cat > "$qbit_config_dir/qBittorrent.conf" << EOF -[Preferences] -WebUI\Username=${auth_username:-admin} -WebUI\Password_PBKDF2=$pbkdf2_hash -WebUI\Port=8081 -EOF - log_success "Pre-configured qBittorrent credentials (bypassing WebAPI restrictions)" - fi +write_usenet_secrets() { + local secrets_dir="$install_directory/secrets" + if [ "${usenet_enabled:-n}" = "y" ] && [ -n "${usenet_password:-}" ]; then + mkdir -p "$secrets_dir" + write_secret_file "$secrets_dir/usenet_password.txt" "${usenet_password}" fi } @@ -479,14 +371,10 @@ validate_vpn_config() { } test_vpn_connection() { - # Profile is only needed for media services; Gluetun has no profile. - local profile="${media_service:-jellyfin}" build_compose_args "$install_directory" "${setup_vpn,,}" - test_vpn_connection_shared run_docker compose "${COMPOSE_ARGS[@]}" --profile "$profile" + test_vpn_connection_shared run_docker compose "${COMPOSE_ARGS[@]}" } -# Provisional host vars so Gluetun can start before the rest of the wizard. -# Final paths/user are collected after a successful tunnel test and may change. set_provisional_vpn_test_defaults() { username="${username:-$USER}" puid="${puid:-$(id -u)}" @@ -497,8 +385,8 @@ set_provisional_vpn_test_defaults() { install_directory=$(expand_path "$install_directory") media_directory=$(expand_path "$media_directory") fi - media_service="${media_service:-jellyfin}" - media_service_port="${media_service_port:-8096}" + media_service="jellyfin" + media_service_port=8096 if [ -z "${tz:-}" ]; then tz=$(cat /etc/timezone 2>/dev/null || timedatectl show -p Timezone -v 2>/dev/null | tail -1 || echo "UTC") tz=${tz:-UTC} @@ -506,8 +394,6 @@ set_provisional_vpn_test_defaults() { export username puid pgid install_directory media_directory media_service media_service_port tz } -# Gate the rest of setup on a working tunnel. On failure, re-prompt credentials -# and retry instead of abandoning a half-finished install. ensure_vpn_connection() { if [ "${setup_vpn,,}" != "y" ]; then return 0 @@ -522,26 +408,13 @@ ensure_vpn_connection() { echo echo -e "${RED}VPN test failed — cannot continue setup without a working VPN.${NC}" - echo -e "${YELLOW}Download clients (qBittorrent, SABnzbd) require the VPN to function.${NC}" - echo - echo "Credentials live under $install_directory/secrets/ (not as passwords in .env)." - if [ "${vpn_type:-openvpn}" = "wireguard" ]; then - echo " WireGuard key: $install_directory/secrets/wireguard_private_key.txt" - echo " WG address: WIREGUARD_ADDRESSES in $install_directory/.env" - else - echo " OpenVPN user: $install_directory/secrets/openvpn_user.txt" - echo " OpenVPN pass: $install_directory/secrets/openvpn_password.txt" - fi - echo "Gluetun logs above usually show why the tunnel failed." - echo - + echo "Credentials live under $install_directory/secrets/ (not in .env)." local retry="" - read -p "Re-enter VPN credentials and try again? (Y/n) [Default = y]: " retry + read_prompt "Re-enter VPN credentials and try again? (Y/n) [Default = y]: " retry retry=${retry:-y} if [ "${retry,,}" != "y" ]; then echo echo "Setup stopped — VPN was not verified, so the rest of the wizard was not run." - echo "When you are ready, re-run setup and enter correct VPN details:" local raw_base="${APP_REPO_URL:-https://github.com/soulis-1256/assemblrr}" raw_base="${raw_base/github.com/raw.githubusercontent.com}/main" echo " Linux / WSL2: bash <(curl -fsSL ${raw_base}/platform/linux/bootstrap.sh)" @@ -557,18 +430,14 @@ ensure_vpn_connection() { log_info "Re-enter VPN credentials for ${vpn_service:-your provider} (${vpn_type:-openvpn})." prompt_vpn_credentials write_vpn_secrets - # WIREGUARD_ADDRESSES and related values live in .env generate_env_file done } -# Right after VPN prompts: materialize a minimal install and prove the tunnel -# before asking about users, paths, media, etc. early_vpn_gate() { if [ "${setup_vpn,,}" != "y" ]; then return 0 fi - echo log_info "Testing VPN connection before the rest of setup..." set_provisional_vpn_test_defaults @@ -577,7 +446,6 @@ early_vpn_gate() { bootstrap_operator generate_env_file write_vpn_secrets - # Bind mounts must exist as the host user before Gluetun starts prepare_install_dirs "$install_directory" "$puid" "$pgid" ensure_vpn_connection log_success "VPN is working — continuing with the rest of setup." @@ -589,10 +457,19 @@ write_runtime_config() { cat > "$config_file" << EOF INSTALL_DIRECTORY="$install_directory" MEDIA_DIRECTORY="$media_directory" -MEDIA_SERVICE="$media_service" +MEDIA_SERVICE="${media_service:-jellyfin}" VPN_ENABLED="${setup_vpn,,}" VPN_TYPE="${vpn_type:-openvpn}" TZ="$tz" +VUETORRENT_ENABLED="${vuetorrent_enabled:-y}" +GPU_TRANSCODING="${gpu_transcoding:-none}" +BYPARR_ENABLED="${byparr_enabled:-n}" +USENET_ENABLED="${usenet_enabled:-n}" +USENET_HOST="${usenet_host:-}" +USENET_PORT="${usenet_port:-563}" +USENET_SSL="${usenet_ssl:-y}" +USENET_USERNAME="${usenet_username:-}" +USENET_CONNECTIONS="${usenet_connections:-8}" QUALITY_TIER="$(quality_tier)" QUALITY_SOURCE="$(quality_source)" SEERR_IS_4K="$(quality_seerr_is_4k)" @@ -605,8 +482,26 @@ EOF log_debug "Runtime config written to $config_file" } -# build_compose_args is defined in lib/compose.sh -# Usage: build_compose_args "$install_directory" "${setup_vpn,,}" +_record_install_metadata() { + local channel="${ASSEMBLRR_INSTALL_REF:-main}" + printf '%s\n' "$channel" > "$install_directory/.assemblrr-channel" + + local sha="unknown" + if [ -d "$APP_ROOT/.git" ]; then + sha=$(git -C "$APP_ROOT" rev-parse --short HEAD 2>/dev/null || echo "unknown") + fi + printf 'setup:%s@%s(%s)\n' "${APP_REPO_URL:-https://github.com/soulis-1256/assemblrr}" "$channel" "$sha" \ + > "$install_directory/.assemblrr-version" + + if [ -d "$APP_ROOT/migrations" ]; then + local mf mid + : > "$install_directory/.assemblrr-migrations" + while IFS= read -r -d '' mf; do + mid=$(sed -n 's/^migration_id=["\x27]\([^"\x27]*\)["\x27].*/\1/p' "$mf" 2>/dev/null | head -1) + [ -n "$mid" ] && printf '%s\n' "$mid" >> "$install_directory/.assemblrr-migrations" + done < <(find "$APP_ROOT/migrations" -maxdepth 1 -type f -name '*.sh' -print0 2>/dev/null | sort -z) + fi +} install_cli() { if [ ! -f "$install_directory/cli.sh" ]; then @@ -618,12 +513,12 @@ install_cli() { log_debug "CLI installed to $HOME/.local/bin/$APP_CLI_NAME" } -# Materialize install tree + operator CLI as soon as we know the install path. -# Lets users run: assemblrr uninstall after aborting mid-setup. -# Callers still generate .env / secrets when those steps are ready. bootstrap_operator() { local quiet="${1:-}" mkdir -p "$install_directory" + if [ "${ASSEMBLRR_RECONFIGURE:-0}" != "1" ]; then + : > "$install_directory/.assemblrr-setup-in-progress" + fi copy_configuration_files write_runtime_config if install_cli; then @@ -637,18 +532,32 @@ bootstrap_operator() { set_permissions() { log_debug "Setting ownership for install and media directories..." - - # Install bind-mount tree (idempotent; also fixes root-owned leftovers) prepare_install_dirs "$install_directory" "$puid" "$pgid" - if [ ! -d "$media_directory" ]; then mkdir -p "$media_directory" || log_error "Failed to create media directory $media_directory" fi ensure_owned "$media_directory" "$puid" "$pgid" - log_debug "Ownership set for $install_directory and $media_directory" } +_validate_restore_archive() { + local archive="$1" + [ -f "$archive" ] || return 1 + gzip -t "$archive" 2>/dev/null || return 1 + local listing has_env=0 bad_path=0 entry + listing=$(tar -tzf "$archive" 2>/dev/null) || return 1 + while IFS= read -r entry; do + [ -z "$entry" ] && continue + case "$entry" in + .env|./.env) has_env=1 ;; + esac + case "$entry" in + /*|..|../*|*/../*|*/..) bad_path=1; break ;; + esac + done <<< "$listing" + [ "$bad_path" -eq 0 ] && [ "$has_env" -eq 1 ] +} + restore_from_backup_wizard() { echo "" log_info "========================================================" @@ -656,41 +565,35 @@ restore_from_backup_wizard() { log_info "========================================================" echo "" - local backup_file="${RESTORE_BACKUP_FILE:-}" + local backup_file="${RESTORE_BACKUP_FILE:-}" backup_input="" while [ -z "$backup_file" ] || [ ! -f "$backup_file" ]; do - read -p "Enter path to backup archive (.tar.gz): " backup_input + read_prompt "Enter path to backup archive (.tar.gz): " backup_input backup_input=${backup_input:-} if [ -z "$backup_input" ]; then log_warning "Please enter a valid file path." continue fi - backup_file=$(expand_path "$backup_input") if [ ! -f "$backup_file" ]; then log_warning "Backup file not found: $backup_file" backup_file="" continue fi - - if ! gzip -t "$backup_file" 2>/dev/null; then - log_warning "File does not appear to be a valid .tar.gz archive: $backup_file" + if ! _validate_restore_archive "$backup_file"; then + log_warning "Invalid or unsafe backup archive (must contain .env without traversal): $backup_file" backup_file="" continue fi done echo "" - local default_install="$APP_DEFAULT_INSTALL_DIR" - local target_install="" + local default_install="$APP_DEFAULT_INSTALL_DIR" target_install="" target_input="" while true; do - read -p "Enter target installation directory [$default_install]: " target_input + read_prompt "Enter target installation directory [$default_install]: " target_input target_input=${target_input:-$default_install} target_install=$(expand_path "$target_input") - if [ -z "$target_install" ]; then - log_warning "Invalid directory path." - continue - fi - break + [ -n "$target_install" ] && break + log_warning "Invalid directory path." done install_directory="$target_install" @@ -699,7 +602,8 @@ restore_from_backup_wizard() { if [ -d "$install_directory" ] && [ "$(ls -A "$install_directory" 2>/dev/null)" ]; then echo "" log_warning "Target directory $install_directory already exists and is not empty." - read -p "Overwrite existing directory contents with backup? [y/N]: " confirm_overwrite + local confirm_overwrite="n" + read_prompt "Overwrite existing directory contents with backup? [y/N]: " confirm_overwrite confirm_overwrite=${confirm_overwrite:-n} if [[ ! ${confirm_overwrite,,} =~ ^y$ ]]; then log_info "Restore cancelled." @@ -708,24 +612,21 @@ restore_from_backup_wizard() { fi mkdir -p "$install_directory" - log_info "Extracting backup archive into $install_directory..." local abs_backup abs_backup=$(realpath "$backup_file") - if ! tar -xzf "$abs_backup" -C "$install_directory" 2>/dev/null; then + if ! tar --no-same-owner -xzf "$abs_backup" -C "$install_directory" 2>/dev/null; then if ! run_docker run --rm \ -v "$install_directory:/target" \ - -v "$(dirname "$abs_backup"):/backup" \ - alpine tar -xzf "/backup/$(basename "$abs_backup")" -C /target; then + -v "$(dirname "$abs_backup"):/backup:ro" \ + "${UTILITY_ALPINE_IMAGE:-alpine:3.24.4}" \ + tar --no-same-owner -xzf "/backup/$(basename "$abs_backup")" -C /target; then log_error "Failed to extract backup archive." fi fi - # Read configuration from restored files - local restored_puid restored_pgid restored_media restored_service restored_vpn restored_tz if [ -f "$install_directory/.env" ]; then - # shellcheck disable=SC1090 safe_source "$install_directory/.env" 2>/dev/null || true fi if [ -f "$install_directory/.assemblrr-config" ]; then @@ -734,16 +635,21 @@ restore_from_backup_wizard() { safe_source "$install_directory/.${APP_NAME}-config" 2>/dev/null || true fi + # Cross-host adaptation: rewrite INSTALL_DIRECTORY if extracted to a new host path + local f + for f in "$install_directory/.assemblrr-config" "$install_directory/.${APP_NAME}-config"; do + [ -f "$f" ] && sed -i -E "s|^INSTALL_DIRECTORY=.*|INSTALL_DIRECTORY=\"${install_directory}\"|" "$f" 2>/dev/null || true + done + [ -f "$install_directory/.env" ] && sed -i -E "s|^INSTALL_DIRECTORY=.*|INSTALL_DIRECTORY=${install_directory}|" "$install_directory/.env" 2>/dev/null || true + puid="${PUID:-$(id -u)}" pgid="${PGID:-$(id -g)}" media_directory="${MEDIA_DIRECTORY:-$APP_DEFAULT_MEDIA_DIR}" media_service="${MEDIA_SERVICE:-jellyfin}" setup_vpn="${VPN_ENABLED:-n}" tz="${TZ:-UTC}" - export puid pgid media_directory media_service setup_vpn tz - # Ensure bind-mount skeleton and permissions prepare_install_dirs "$install_directory" "$puid" "$pgid" if [ ! -d "$media_directory" ]; then mkdir -p "$media_directory" 2>/dev/null || true @@ -751,11 +657,7 @@ restore_from_backup_wizard() { ensure_owned "$media_directory" "$puid" "$pgid" 2>/dev/null || true write_install_pointer "$install_directory" "$media_directory" - # Make scripts executable - chmod +x "$install_directory/bin/"*.sh "$install_directory/scripts/"*.sh 2>/dev/null || true - chmod +x "$install_directory/cli.sh" "$install_directory/config.sh" "$install_directory/setup.sh" 2>/dev/null || true - - # Install CLI globally + chmod +x "$install_directory/scripts/"*.sh "$install_directory/cli.sh" "$install_directory/config.sh" "$install_directory/setup.sh" 2>/dev/null || true install_cli log_success "Backup extracted and configuration loaded." @@ -763,194 +665,360 @@ restore_from_backup_wizard() { log_info "Starting restored services..." build_compose_args "$install_directory" "${setup_vpn,,}" - if ! compose_up_stack "$media_service"; then + if ! compose_up_stack "default"; then log_warning "Failed to start some restored services." log_info "Run '$APP_CLI_NAME logs' or '$APP_CLI_NAME status' to inspect." exit 1 fi + rm -f "$install_directory/.assemblrr-setup-in-progress" + echo "" + echo "========================================================" + log_success "${APP_DISPLAY_NAME} restored and running!" + echo "========================================================" echo "" if [ -f "$install_directory/cli.sh" ]; then - log_info "Service dashboard:" - bash "$install_directory/cli.sh" status || true + bash "$install_directory/cli.sh" status --compact || true + echo + fi + printf " %-18s %s · %s\n" "Paths:" "$install_directory" "$media_directory" + printf " %-18s %s status | config edit | upgrade | uninstall\n" "Manage:" "$APP_CLI_NAME" + echo "" + exit 0 +} + +setup_on_interrupt() { + trap - INT TERM + stty echo 2>/dev/null || true + echo >&2 + + local inst="${install_directory:-${_ASSEMBLRR_PROVISIONAL_INSTALL:-}}" + local media="${media_directory:-}" + local has_inst=0 has_media=0 has_containers=0 + if [ -n "$inst" ] && [ -d "$inst" ] && [ -f "$inst/.assemblrr-setup-in-progress" ]; then + has_inst=1 + fi + if [ -n "$media" ] && [ -d "$media" ]; then + has_media=1 + fi + if command -v docker >/dev/null 2>&1 && docker ps -a --format '{{.Names}}' 2>/dev/null | grep -qx 'gluetun'; then + has_containers=1 fi - echo "" - log_success "All done! ${APP_DISPLAY_NAME} has been restored and is running." - log_info "Install directory: $install_directory" - log_info "Media directory: $media_directory" - log_info "Manage the stack: $APP_CLI_NAME status" - exit 0 + if [ "$has_inst" -eq 0 ] && [ "$has_containers" -eq 0 ]; then + log_info "Setup cancelled — nothing was installed." + exit 130 + fi + + echo + log_warning "Setup interrupted before completion." + echo "Created so far:" + [ "$has_inst" -eq 1 ] && echo " - Partial config & CLI: $inst" + [ "$has_containers" -eq 1 ] && echo " - Temporary VPN container: gluetun" + [ "$has_media" -eq 1 ] && echo " - Media folders: $media" + echo "Not installed yet:" + echo " - Core media stack containers & service wiring" + echo + + local ans="n" + if [ -t 0 ] && [ -r /dev/tty ]; then + read_prompt "Clean up partial setup now (stops temp containers & deletes partial config; keeps any media files)? [Y/n]: " ans + ans=${ans:-y} + fi + + if [ "${ans,,}" = "y" ]; then + if [ "$has_inst" -eq 1 ]; then + type _cleanup_leftover_compose >/dev/null 2>&1 && _cleanup_leftover_compose "$inst" + safe_rm_rf "$inst" + elif [ "$has_containers" -eq 1 ]; then + docker rm -f gluetun >/dev/null 2>&1 || true + docker network rm "${APP_NETWORK_NAME:-assemblrr_network}" >/dev/null 2>&1 || true + fi + local ptr ptr_inst removed_ptr=false + for ptr in "$HOME/.assemblrr-config" "$HOME/.${APP_NAME:-assemblrr}-config"; do + [ -f "$ptr" ] || continue + ptr_inst=$(_pointer_get "$ptr" "INSTALL_DIRECTORY") + if [ -n "$ptr_inst" ] && [ ! -d "$ptr_inst" ]; then + rm -f "$ptr" + removed_ptr=true + fi + done + if [ "$removed_ptr" = true ]; then + rm -f "$HOME/.local/bin/${APP_CLI_NAME:-assemblrr}" 2>/dev/null || true + fi + if [ "$has_media" -eq 1 ]; then + if [ -z "$(find "$media" -type f -print -quit 2>/dev/null || true)" ]; then + safe_rm_rf "$media" + log_info "Empty media folder skeleton removed ($media)." + else + log_info "Existing files found under $media — kept untouched." + fi + fi + log_success "Partial setup cleaned up." + else + log_info "Partial setup left in place. Re-run setup.sh to clean up, or run: ${APP_CLI_NAME:-assemblrr} uninstall --force" + fi + exit 130 } main() { -# Prevent running as root -if [[ "$EUID" = 0 ]]; then - log_error "${APP_DISPLAY_NAME} must run without sudo! Please run with regular permissions" -fi - -# Setup logging -LOG_FILE="/tmp/${APP_NAME}-setup-$(date '+%Y%m%d-%H%M%S').log" -log_info "Setup log: $LOG_FILE" -log_info "Checking prerequisites..." -check_dependencies - -if [ "${SETUP_MODE:-}" = "restore" ]; then - restore_from_backup_wizard -fi - -refuse_setup_if_already_installed -offer_leftover_cleanup - -# 1) VPN questions, then immediately test the tunnel (fail fast). -# VPN path bootstraps install tree + CLI early so uninstall works if you abort. -configure_vpn -early_vpn_gate - -# 2) Only after VPN works (or is disabled): rest of the wizard -get_user_info -get_installation_paths -# No-VPN (or path change after provisional VPN defaults): ensure tree + CLI exist -bootstrap_operator quiet -configure_media_service -configure_quality_profile -configure_subtitle_language -configure_opensubtitles -configure_timezone -configure_auth - -# ---- Installation summary / confirmation ---- -echo -echo "========================================================" -echo " ${APP_DISPLAY_NAME} — Installation Summary" -echo "========================================================" -echo " User: $username (PUID=$puid, PGID=$pgid)" -echo " Install directory: $install_directory" -echo " Media directory: $media_directory" -if [ "${setup_vpn,,}" = "y" ]; then - echo " VPN: ENABLED ($vpn_service, $vpn_type)" - echo " Port forwarding: ${enable_port_forwarding:-n}" -else - echo " VPN: DISABLED" -fi -echo " Media service: $media_service (port $media_service_port)" -if [ "$QUALITY_TIER" = "any" ]; then - echo " Quality profile: any" -else - echo " Quality profile: $QUALITY_TIER / ${QUALITY_SOURCE:-bluray} (4K=$seerr_is_4k)" -fi -if [ -n "${subtitle_languages:-}" ] && [ "${subtitle_languages}" != "${subtitle_language:-}" ]; then - echo " Subtitle languages: ${subtitle_language} (preferred), ${subtitle_languages#*,}" -else - echo " Subtitle language: ${subtitle_language:-en (Bazarr default)}" -fi -if [ "${opensubtitles_enabled:-n}" = "y" ]; then - echo " OpenSubtitles.com: yes (username=${opensubtitles_username})" -else - echo " OpenSubtitles.com: no" -fi -echo " Timezone: $tz" -echo " Service login: $auth_username" -echo "========================================================" -echo -if [ "${SETUP_MODE:-}" != "express" ]; then - while true; do - read -p "Proceed with installation? (Y/n) [Default = y]: " proceed - proceed=${proceed:-"y"} - if [ "${proceed,,}" = "y" ]; then - break - elif [ "${proceed,,}" = "n" ]; then - log_info "Installation cancelled by user" - exit 0 - else - log_warning "Please answer y or n." - fi + RESTORE_BACKUP_FILE="" + while [ $# -gt 0 ]; do + case "$1" in + -h|--help) setup_show_help; exit 0 ;; + --restore) + SETUP_MODE="restore" + if [ -n "${2:-}" ] && [[ ! "$2" =~ ^-- ]]; then + RESTORE_BACKUP_FILE="$2" + shift + fi + shift + ;; + --restore=*) + SETUP_MODE="restore" + RESTORE_BACKUP_FILE="${1#*=}" + shift + ;; + --express) SETUP_MODE="express"; shift ;; + --manual) SETUP_MODE="manual"; shift ;; + --reconfigure) ASSEMBLRR_RECONFIGURE=1; export ASSEMBLRR_RECONFIGURE; shift ;; + *) shift ;; + esac done -fi -log_info "Configuring ${APP_DISPLAY_NAME} for user \"$username\" in \"$install_directory\"..." - -# Refresh install tree for final paths/settings (may differ from provisional VPN test defaults) -copy_configuration_files -generate_env_file -write_vpn_secrets - -# Final bind-mount skeleton + ownership before any further compose operations -prepare_install_dirs "$install_directory" "$puid" "$pgid" - -# Re-check only if we never verified (VPN disabled skips; early gate already set the flag) -if [ "${setup_vpn,,}" = "y" ] && [ "${VPN_ALREADY_VERIFIED:-}" != "1" ]; then - ensure_vpn_connection -elif [ "${setup_vpn,,}" = "y" ]; then - log_debug "VPN already verified earlier — not re-testing." -fi - -write_auth_secrets -write_opensubtitles_secrets -write_qbittorrent_config -write_runtime_config -install_cli -set_permissions - -log_success "Install files ready — starting services..." -# Ensure mounts still exist/owned immediately before the full stack comes up -prepare_install_dirs "$install_directory" "$puid" "$pgid" -build_compose_args "$install_directory" "${setup_vpn,,}" -if ! compose_up_stack "$media_service"; then - echo - log_warning "Failed to start ${APP_DISPLAY_NAME} services" - echo - log_info "The operator CLI is already installed. From a WSL or Linux shell:" - log_info " $HOME/.local/bin/$APP_CLI_NAME status" - log_info " $HOME/.local/bin/$APP_CLI_NAME uninstall" - log_info "If '$APP_CLI_NAME' is not found, use that full path (or open a new terminal)." - echo - exit 1 -fi - -# Wire services (Radarr, Prowlarr, etc.) -local wiring_ok=1 -if [ -f "$install_directory/config.sh" ]; then - if ! bash "$install_directory/config.sh"; then - wiring_ok=0 - log_warning "Service wiring had critical failures. Containers are still running." - log_warning "Fix the issues above, then re-run setup or: $APP_CLI_NAME upgrade" + if [[ "${EUID:-$(id -u)}" = 0 ]]; then + log_error "${APP_DISPLAY_NAME} must run without sudo! Please run with regular permissions" fi -fi -# Drop legacy name if an older install left it behind -rm -f "$install_directory/configure.sh" 2>/dev/null || true + trap 'setup_on_interrupt' INT TERM -echo -# Live dashboard once (status exits non-zero when something is unhealthy — -# that is still a successful print; do not fall back to a second URL list). -if [ -f "$install_directory/lib/services.sh" ]; then - # shellcheck source=/dev/null - source "$install_directory/lib/services.sh" -fi -if [ -f "$install_directory/cli.sh" ]; then - log_info "Service dashboard:" - bash "$install_directory/cli.sh" status || true - log_info "Re-check anytime: $APP_CLI_NAME status" -elif type running_services_location >/dev/null 2>&1; then - running_services_location - log_info "After install, run: $APP_CLI_NAME status" -fi -# Drop legacy cheat-sheet if an older setup left one behind -rm -f "$HOME/assemblrr_services.txt" 2>/dev/null || true + echo "====================================================" + echo " | | | | " + echo " __ _ ___ ___ ___ _ __ ___ | |__ | |_ __ _ __ " + echo " / _\` / __/ __|/ _ \ '_ \` _ \\| '_ \\| | '__| '__|" + echo "| (_| \\__ \\__ \\ __/ | | | | | |_) | | | | | " + echo " \\__,_|___/___/\\___|_| |_| |_|_.__/|_|_| |_| " + echo " " + echo "====================================================" + echo "Welcome to ${APP_DISPLAY_NAME} (${APP_DESCRIPTION})" + echo "====================================================" + echo "" -log_info "========================================================" -if [ "$wiring_ok" -eq 1 ]; then - log_success "All done! Enjoy ${APP_DISPLAY_NAME}!" - log_info "Install directory: $install_directory" - log_info "Docs: ${APP_REPO_URL}" - exit 0 -fi + if [ -z "${SETUP_MODE:-}" ]; then + echo " 1) Express (recommended — minimal questions, smart defaults)" + echo " 2) Manual (full control over every setting)" + echo " 3) Restore (rebuild stack from an existing backup archive)" + while true; do + read_prompt "Choose setup mode [1]: " setup_mode_choice + setup_mode_choice=${setup_mode_choice:-1} + case "$setup_mode_choice" in + 1) SETUP_MODE="express"; break ;; + 2) SETUP_MODE="manual"; break ;; + 3) SETUP_MODE="restore"; break ;; + *) log_warning "Invalid choice. Please choose 1, 2, or 3." ;; + esac + done + fi + export SETUP_MODE -log_warning "Setup finished, but service wiring failed." -log_warning "Install directory: $install_directory" -log_warning "Fix issues, then re-run setup or: $APP_CLI_NAME upgrade" -log_info "Docs: ${APP_REPO_URL}" -exit 1 + if [ "$SETUP_MODE" = "express" ]; then + echo "" + log_success "Express mode — we'll use smart defaults and only ask the essentials." + echo "" + elif [ "$SETUP_MODE" = "restore" ]; then + echo "" + log_info "Restore mode — we'll rebuild your stack from an existing backup archive." + echo "" + else + echo "" + log_info "Manual mode — you'll configure every setting." + echo "" + fi + + LOG_FILE="/tmp/${APP_NAME}-setup-$(date '+%Y%m%d-%H%M%S').log" + log_info "Setup log: $LOG_FILE" + log_info "Checking prerequisites..." + check_dependencies + + if [ "${SETUP_MODE:-}" = "restore" ]; then + restore_from_backup_wizard + fi + + refuse_setup_if_already_installed + offer_leftover_cleanup + + configure_vpn + early_vpn_gate + + get_user_info + get_installation_paths + bootstrap_operator quiet + configure_media_service + configure_quality_profile + configure_subtitle_language + configure_opensubtitles + configure_vuetorrent + configure_gpu_transcoding + configure_byparr + configure_usenet + configure_timezone + configure_auth + + echo + echo "========================================================" + echo " ${APP_DISPLAY_NAME} — Installation Summary" + echo "========================================================" + echo " User: $username (PUID=$puid, PGID=$pgid)" + echo " Install directory: $install_directory" + echo " Media directory: $media_directory" + if [ "${setup_vpn,,}" = "y" ]; then + echo " VPN: ENABLED ($vpn_service, $vpn_type)" + echo " Port forwarding: ${enable_port_forwarding:-n}" + else + echo " VPN: DISABLED" + fi + echo " Media service: $media_service (port $media_service_port)" + echo " VueTorrent UI: ${vuetorrent_enabled:-y}" + echo " GPU transcoding: ${gpu_transcoding:-none}" + echo " Byparr solver: ${byparr_enabled:-n}" + echo " SABnzbd / Usenet: ${usenet_enabled:-n}" + if [ "$QUALITY_TIER" = "any" ]; then + echo " Quality profile: any" + else + echo " Quality profile: $QUALITY_TIER / ${QUALITY_SOURCE:-bluray} (4K=$seerr_is_4k)" + fi + if [ -n "${subtitle_languages:-}" ] && [ "${subtitle_languages}" != "${subtitle_language:-}" ]; then + echo " Subtitle languages: ${subtitle_language} (preferred), ${subtitle_languages#*,}" + else + echo " Subtitle language: ${subtitle_language:-en (Bazarr default)}" + fi + if [ "${opensubtitles_enabled:-n}" = "y" ]; then + echo " OpenSubtitles.com: yes (username=${opensubtitles_username})" + else + echo " OpenSubtitles.com: no" + fi + echo " Timezone: $tz" + echo " Service login: $auth_username" + echo "========================================================" + echo + + if [ "${SETUP_MODE:-}" != "express" ]; then + while true; do + read_prompt "Proceed with installation? (Y/n) [Default = y]: " proceed + proceed=${proceed:-"y"} + if [ "${proceed,,}" = "y" ]; then + break + elif [ "${proceed,,}" = "n" ]; then + log_info "Installation cancelled by user" + exit 0 + else + log_warning "Please answer y or n." + fi + done + fi + + log_info "Configuring ${APP_DISPLAY_NAME} for user \"$username\" in \"$install_directory\"..." + + copy_configuration_files + generate_env_file + write_vpn_secrets + prepare_install_dirs "$install_directory" "$puid" "$pgid" + + if [ "${setup_vpn,,}" = "y" ] && [ "${VPN_ALREADY_VERIFIED:-}" != "1" ]; then + ensure_vpn_connection + elif [ "${setup_vpn,,}" = "y" ]; then + log_debug "VPN already verified earlier — not re-testing." + fi + + write_auth_secrets + write_opensubtitles_secrets + write_usenet_secrets + VUETORRENT_ENABLED="${vuetorrent_enabled:-y}" write_qbittorrent_config + write_runtime_config + _record_install_metadata + install_cli + set_permissions + + log_success "Install files ready — starting services..." + prepare_install_dirs "$install_directory" "$puid" "$pgid" + build_compose_args "$install_directory" "${setup_vpn,,}" + if ! compose_up_stack "default"; then + echo + log_warning "Failed to start ${APP_DISPLAY_NAME} services" + echo + log_info "The operator CLI is already installed. From a WSL or Linux shell:" + log_info " $HOME/.local/bin/$APP_CLI_NAME status" + log_info " $HOME/.local/bin/$APP_CLI_NAME uninstall" + log_info "If '$APP_CLI_NAME' is not found, use that full path (or open a new terminal)." + echo + exit 1 + fi + rm -f "$install_directory/.assemblrr-setup-in-progress" + trap - INT TERM + + local wiring_ok=1 + if [ -f "$install_directory/config.sh" ]; then + if ! ASSEMBLRR_FROM_SETUP=1 bash "$install_directory/config.sh"; then + wiring_ok=0 + log_warning "Service wiring had critical failures. Containers are still running." + log_warning "Fix the issues above, then re-run: $APP_CLI_NAME config apply" + fi + fi + rm -f "$install_directory/configure.sh" 2>/dev/null || true + rm -f "$HOME/assemblrr_services.txt" 2>/dev/null || true + + local -a ready_badges=() + if [ "${setup_vpn,,}" = "y" ]; then + ready_badges+=("VPN on") + else + ready_badges+=("VPN off") + fi + [ "${gpu_transcoding:-none}" != "none" ] && ready_badges+=("GPU ${gpu_transcoding}") + [ "${vuetorrent_enabled:-y}" = "y" ] && ready_badges+=("VueTorrent") + [ "${byparr_enabled:-n}" = "y" ] && ready_badges+=("Byparr") + [ "${usenet_enabled:-n}" = "y" ] && ready_badges+=("Usenet") + local badge_str="" _b + for _b in "${ready_badges[@]}"; do + [ -n "$badge_str" ] && badge_str+=" · " + badge_str+="$_b" + done + + local ui_host="${API_HOST:-localhost}" + [ "$ui_host" = "127.0.0.1" ] && ui_host="localhost" + + echo + echo "========================================================" + if [ "$wiring_ok" -eq 1 ]; then + log_success "${APP_DISPLAY_NAME} is ready! (${badge_str})" + else + log_warning "${APP_DISPLAY_NAME} started with wiring warnings (${badge_str})" + fi + echo "========================================================" + echo + + if [ -f "$install_directory/cli.sh" ]; then + bash "$install_directory/cli.sh" status --compact || true + echo + elif type running_services_location >/dev/null 2>&1; then + running_services_location + echo + fi + + if [ -n "${auth_username:-}" ]; then + printf " %-18s %s / \n" "Login:" "$auth_username" + fi + printf " %-18s %s · %s\n" "Paths:" "$install_directory" "$media_directory" + echo + printf " %-18s Request in Seerr (http://%s:5055/), watch in Jellyfin (http://%s:8096/)\n" "Start here:" "$ui_host" "$ui_host" + printf " %-18s %s status | config edit | upgrade | uninstall\n" "Manage:" "$APP_CLI_NAME" + if [ "$wiring_ok" -eq 0 ]; then + printf " %-18s %s config apply\n" "Fix wiring:" "$APP_CLI_NAME" + fi + echo + + [ "$wiring_ok" -eq 1 ] && exit 0 + exit 1 } -main "$@" +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi diff --git a/compose/base.yaml b/compose/base.yaml index b689aeb..c71354b 100644 --- a/compose/base.yaml +++ b/compose/base.yaml @@ -1,8 +1,7 @@ services: - # Jellyfin — open source media server (recommended) + # Jellyfin — open source media server (Jellyfin 12.4+) jellyfin: - profiles: ["jellyfin"] - image: lscr.io/linuxserver/jellyfin:10.11.11 + image: lscr.io/linuxserver/jellyfin:12.4ubu2604-ls60 container_name: jellyfin environment: - PUID=${PUID} @@ -27,61 +26,9 @@ services: assemblrr_network: ipv4_address: 172.60.0.11 - # Emby — UNSUPPORTED optional profile (express/default is Jellyfin only). - emby: - profiles: ["emby"] - image: lscr.io/linuxserver/emby - container_name: emby - environment: - - PUID=${PUID} - - PGID=${PGID} - - TZ=${TZ} - - VERSION=docker - volumes: - - /etc/localtime:/etc/localtime:ro - - ${MEDIA_DIRECTORY}:/data - - ${INSTALL_DIRECTORY}/config/emby:/config - ports: - - 8096:8096 - healthcheck: - test: ["CMD", "curl", "-sf", "http://127.0.0.1:8096/emby/System/Ping"] - interval: 10s - timeout: 5s - retries: 3 - start_period: 30s - start_interval: 2s - restart: unless-stopped - networks: - assemblrr_network: - ipv4_address: 172.60.0.11 - - # Plex — UNSUPPORTED optional profile (express/default is Jellyfin only). - plex: - profiles: ["plex"] - image: lscr.io/linuxserver/plex - container_name: plex - network_mode: host - environment: - - PUID=${PUID} - - PGID=${PGID} - - TZ=${TZ} - - VERSION=docker - volumes: - - /etc/localtime:/etc/localtime:ro - - ${MEDIA_DIRECTORY}:/data - - ${INSTALL_DIRECTORY}/config/plex:/config - restart: unless-stopped - healthcheck: - test: ["CMD", "curl", "-sf", "http://127.0.0.1:32400/identity"] - interval: 10s - timeout: 5s - retries: 3 - start_period: 30s - start_interval: 2s - - # qBittorrent — torrent client (ports added by overlay) + # qBittorrent — torrent client (ports/network added by vpn or direct-access overlay) qbittorrent: - image: lscr.io/linuxserver/qbittorrent:5.2.3 + image: lscr.io/linuxserver/qbittorrent:5.3.0 container_name: qbittorrent environment: - PUID=${PUID} @@ -103,7 +50,7 @@ services: # Sonarr — TV show management and automation sonarr: - image: lscr.io/linuxserver/sonarr:4.0.19.2979-ls321 + image: lscr.io/linuxserver/sonarr:4.0.20.3014-ls6 container_name: sonarr environment: - PUID=${PUID} @@ -131,7 +78,7 @@ services: # Radarr — movie management and automation radarr: - image: lscr.io/linuxserver/radarr:6.3.0.10514-ls313 + image: lscr.io/linuxserver/radarr:7.0.3.10918-ls328 container_name: radarr environment: - PUID=${PUID} @@ -159,7 +106,7 @@ services: # Prowlarr — indexer management for *arr apps prowlarr: - image: lscr.io/linuxserver/prowlarr:2.5.2.5491-ls156 + image: lscr.io/linuxserver/prowlarr:3.0.2.5780-ls169 container_name: prowlarr environment: - PUID=${PUID} @@ -182,12 +129,9 @@ services: assemblrr_network: ipv4_address: 172.60.0.15 - # Seerr — media request management (successor to Jellyseerr/Overseerr) - # Host port 5055 is published by seerr-gateway (not seerr) so DELETE /request - # can cancel in-flight *arr/qB grabs. Seerr stays on the Docker network only. - # Retirement: see docs/seerr-delete-request.md + # Seerr — media request management (internal; published via seerr-gateway:5055) seerr: - image: ghcr.io/seerr-team/seerr:v3.4.1 + image: ghcr.io/seerr-team/seerr:v3.5.2 container_name: seerr init: true environment: @@ -209,11 +153,11 @@ services: assemblrr_network: ipv4_address: 172.60.0.17 - # Thin reverse proxy in front of Seerr: pass-through + delete-request queue drain. + # Authenticating reverse proxy in front of Seerr: pass-through + delete-request purge. # TV: season-scoped via Sonarr when the request is a subset of remaining seasons. # SEERR_DELETE_REQUEST_PURGE=0 disables intercept (stock Seerr semantics). seerr-gateway: - image: python:3.12.14-alpine + image: python:3.12.16-alpine container_name: seerr-gateway environment: - TZ=${TZ} @@ -255,10 +199,9 @@ services: assemblrr_network: ipv4_address: 172.60.0.24 - # Recyclarr - automatically syncs TRaSH guides - # :latest is no longer published; pin a 8.x release (see recyclarr.dev). + # Recyclarr — automatically syncs TRaSH guides (:latest not published; pin 8.x) recyclarr: - image: ghcr.io/recyclarr/recyclarr:8.7.1 + image: ghcr.io/recyclarr/recyclarr:8.8.1 container_name: recyclarr user: ${PUID}:${PGID} environment: @@ -272,7 +215,7 @@ services: assemblrr_network: ipv4_address: 172.60.0.18 - # Deletes under /data/media → purge *arr entry + qB torrent/files + # Deletes under /data/media -> purge *arr entry + qB / SABnzbd items media-purge-watch: image: assemblrr/media-purge-watch:local pull_policy: build @@ -286,6 +229,7 @@ services: - CONFIG_DIR=/config - RADARR_URL=http://radarr:7878 - SONARR_URL=http://sonarr:8989 + - SABNZBD_URL=http://sabnzbd:8080 - AUTH_USERNAME_FILE=/run/secrets/auth_username.txt - AUTH_PASSWORD_FILE=/run/secrets/auth_password.txt - MEDIA_PURGE_WATCH=${MEDIA_PURGE_WATCH:-1} @@ -303,7 +247,7 @@ services: # Bazarr — automatic subtitle management (Sonarr/Radarr companion) bazarr: - image: lscr.io/linuxserver/bazarr:1.6.0 + image: lscr.io/linuxserver/bazarr:1.6.2 container_name: bazarr environment: - PUID=${PUID} diff --git a/compose/byparr.yaml b/compose/byparr.yaml new file mode 100644 index 0000000..7b6ab50 --- /dev/null +++ b/compose/byparr.yaml @@ -0,0 +1,25 @@ +# Overlay: Byparr Cloudflare challenge solver (drop-in FlareSolverr replacement for Prowlarr) +services: + byparr: + image: ghcr.io/thephaseless/byparr:3.1.1 + container_name: byparr + environment: + - TZ=${TZ} + shm_size: "1gb" + tmpfs: + - /tmp:exec,mode=1777,size=1G + healthcheck: + test: + [ + "CMD-SHELL", + "curl -sf http://127.0.0.1:8191/health >/dev/null || python3 -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8191/health', timeout=5)\"", + ] + interval: 30s + timeout: 10s + retries: 3 + start_period: 30s + start_interval: 2s + restart: unless-stopped + networks: + assemblrr_network: + ipv4_address: 172.60.0.26 diff --git a/compose/direct-access.yaml b/compose/direct-access.yaml index f2fdf0d..067194a 100644 --- a/compose/direct-access.yaml +++ b/compose/direct-access.yaml @@ -1,5 +1,5 @@ # Overlay: direct access ports and networks for qBittorrent (no VPN) -# Usage: docker compose -f base.yaml -f direct-access.yaml --profile up -d +# Usage: docker compose -f base.yaml -f direct-access.yaml up -d services: qbittorrent: diff --git a/compose/examples/custom.yaml.example b/compose/examples/custom.yaml.example index 26a692e..31d2faa 100644 --- a/compose/examples/custom.yaml.example +++ b/compose/examples/custom.yaml.example @@ -1,9 +1,8 @@ # Custom services overlay — NOT officially supported. # Rename this file to custom.yaml to add extra containers. They join assemblrr_network -# but are not wired, upgraded, or bugfixed by assemblrr. Express/default support is -# Jellyfin + qBittorrent + Sonarr/Radarr/Prowlarr/Bazarr/Seerr/Recyclarr (+ optional VPN). -# -# Usage: docker compose -f base.yaml -f [direct-access|vpn].yaml -f custom.yaml --profile up -d +# (.30+ IPs reserved for custom services) and are left untouched by assemblrr upgrades. +# Official core stack: Jellyfin + qBittorrent + Sonarr/Radarr/Prowlarr/Bazarr/Seerr/Recyclarr +# + optional overlays (vuetorrent, gpu-intel/gpu-nvidia, byparr, usenet, vpn). networks: default: @@ -12,11 +11,48 @@ networks: services: + # --- Emby (optional self-managed custom service; conflicts with Jellyfin 8096 unless remapped) --- + # Web UI: http://:8097 + # emby: + # image: lscr.io/linuxserver/emby:4.9.3.0 + # container_name: emby + # environment: + # - PUID=${PUID} + # - PGID=${PGID} + # - TZ=${TZ} + # volumes: + # - /etc/localtime:/etc/localtime:ro + # - ${MEDIA_DIRECTORY}:/data + # - ${INSTALL_DIRECTORY}/config/emby:/config + # ports: + # - 8097:8096 + # restart: unless-stopped + # networks: + # assemblrr_network: + # ipv4_address: 172.60.0.30 + + # --- Plex (optional self-managed custom service; uses host networking for DLNA/claim) --- + # Web UI: http://:32400/web + # plex: + # image: lscr.io/linuxserver/plex:1.43.0 + # container_name: plex + # network_mode: host + # environment: + # - PUID=${PUID} + # - PGID=${PGID} + # - TZ=${TZ} + # - VERSION=docker + # volumes: + # - /etc/localtime:/etc/localtime:ro + # - ${MEDIA_DIRECTORY}:/data + # - ${INSTALL_DIRECTORY}/config/plex:/config + # restart: unless-stopped + # --- Lidarr — Music management and automation --- - # Requires: Prowlarr indexer, qBittorrent download client (configure manually) + # Requires: Prowlarr indexer + download client (configure manually in Lidarr UI) # Web UI: http://:8686 # lidarr: - # image: lscr.io/linuxserver/lidarr:3.1.0.4875-ls39 + # image: lscr.io/linuxserver/lidarr:3.1.0 # container_name: lidarr # environment: # - PUID=${PUID} @@ -31,68 +67,20 @@ services: # restart: unless-stopped # networks: # assemblrr_network: - # ipv4_address: 172.60.0.20 + # ipv4_address: 172.60.0.32 - # --- SABnzbd — Usenet downloader --- - # Requires: A paid Usenet provider (Newshosting, Eweka, etc.) - # Note: Routes through VPN if enabled (same as qBittorrent) - # Web UI: http://:8080 - # sabnzbd: - # image: lscr.io/linuxserver/sabnzbd:5.1.0-ls267 - # container_name: sabnzbd + # --- Komodo Periphery — connect this host to a Komodo dashboard (see docs/komodo.md) --- + # periphery: + # image: ghcr.io/moghtech/komodo-periphery:1.19 + # container_name: komodo-periphery # environment: - # - PUID=${PUID} - # - PGID=${PGID} # - TZ=${TZ} # volumes: - # - /etc/localtime:/etc/localtime:ro - # - ${MEDIA_DIRECTORY}:/data - # - ${INSTALL_DIRECTORY}/config/sabnzbd:/config - # restart: unless-stopped - # networks: - # assemblrr_network: - # ipv4_address: 172.60.0.21 - - # --- Bazarr --- - # Bazarr ships in compose/base.yaml (auto-wired by config.sh). Do not re-add it here. - - # --- Portainer — optional Docker UI (not part of the default stack; prefer assemblrr CLI) --- - # Web UI: http://localhost:9000 - # portainer: - # image: portainer/portainer-ce - # container_name: portainer - # ports: - # - 9000:9000 - # volumes: - # - /etc/localtime:/etc/localtime:ro - # - /var/run/docker.sock:/var/run/docker.sock:ro - # - ${INSTALL_DIRECTORY}/config/portainer:/data - # restart: unless-stopped - # networks: - # assemblrr_network: - # ipv4_address: 172.60.0.16 - - # --- Watchtower — Automatic container update notifications --- - # MONITOR_ONLY=true: Notifies when updates are available, does NOT auto-update - # To enable notifications, set WATCHTOWER_NOTIFICATION_URL (see: https://containrrr.dev/shoutrrr/v0.5/services/) - # Examples: - # Discord: discord://token@id - # Telegram: telegram://bottoken@ChatID - # Slack: slack://token@channel - # Email: smtp://user:pass@host:port/?from=addr&to=addr - # watchtower: - # image: nickfedor/watchtower - # container_name: watchtower - # environment: - # - WATCHTOWER_CLEANUP=true - # - TZ=${TZ} - # - WATCHTOWER_SCHEDULE=0 0 4 * * * - # - WATCHTOWER_MONITOR_ONLY=true - # - WATCHTOWER_NOTIFICATIONS=shoutrrr - # - WATCHTOWER_NOTIFICATION_URL=discord://token@id - # volumes: # - /var/run/docker.sock:/var/run/docker.sock + # - ${INSTALL_DIRECTORY}:${INSTALL_DIRECTORY} + # ports: + # - 8120:8120 # restart: unless-stopped # networks: # assemblrr_network: - # ipv4_address: 172.60.0.23 + # ipv4_address: 172.60.0.33 diff --git a/compose/gpu-intel.yaml b/compose/gpu-intel.yaml new file mode 100644 index 0000000..8e7b894 --- /dev/null +++ b/compose/gpu-intel.yaml @@ -0,0 +1,5 @@ +# Overlay: Intel Quick Sync / AMD VAAPI hardware transcoding for Jellyfin +services: + jellyfin: + devices: + - /dev/dri:/dev/dri diff --git a/compose/gpu-nvidia.yaml b/compose/gpu-nvidia.yaml new file mode 100644 index 0000000..6dbf396 --- /dev/null +++ b/compose/gpu-nvidia.yaml @@ -0,0 +1,13 @@ +# Overlay: NVIDIA NVENC/NVDEC hardware transcoding for Jellyfin +services: + jellyfin: + environment: + - NVIDIA_VISIBLE_DEVICES=all + - NVIDIA_DRIVER_CAPABILITIES=all + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] diff --git a/compose/sidecars/media-purge-watch.Dockerfile b/compose/sidecars/media-purge-watch.Dockerfile index 0833346..25fd4fa 100644 --- a/compose/sidecars/media-purge-watch.Dockerfile +++ b/compose/sidecars/media-purge-watch.Dockerfile @@ -1,5 +1,5 @@ # Built on the host so inotify/curl/jq are in the image, not apk'd at every start. -FROM alpine:3.21 +FROM alpine:3.24.4 RUN apk add --no-cache bash curl jq inotify-tools WORKDIR /scripts ENTRYPOINT ["bash"] diff --git a/compose/sidecars/vpn-watchdog.Dockerfile b/compose/sidecars/vpn-watchdog.Dockerfile index 62e3f8f..645d5a9 100644 --- a/compose/sidecars/vpn-watchdog.Dockerfile +++ b/compose/sidecars/vpn-watchdog.Dockerfile @@ -1,5 +1,5 @@ # Built on the host (not through Gluetun) so Alpine packages never go out the VPN. -FROM alpine:3.21 +FROM alpine:3.24.4 RUN apk add --no-cache bash curl jq docker-cli WORKDIR /scripts ENTRYPOINT ["bash"] diff --git a/compose/usenet.yaml b/compose/usenet.yaml new file mode 100644 index 0000000..0944543 --- /dev/null +++ b/compose/usenet.yaml @@ -0,0 +1,26 @@ +# Overlay: SABnzbd Usenet downloader (wired automatically into Sonarr/Radarr/Prowlarr) +services: + sabnzbd: + image: lscr.io/linuxserver/sabnzbd:5.1.3 + container_name: sabnzbd + environment: + - PUID=${PUID} + - PGID=${PGID} + - TZ=${TZ} + volumes: + - /etc/localtime:/etc/localtime:ro + - ${MEDIA_DIRECTORY}:/data + - ${INSTALL_DIRECTORY}/config/sabnzbd:/config + ports: + - 8085:8080 + healthcheck: + test: ["CMD", "curl", "-sf", "http://127.0.0.1:8080/api?mode=version"] + interval: 10s + timeout: 5s + retries: 3 + start_period: 30s + start_interval: 2s + restart: unless-stopped + networks: + assemblrr_network: + ipv4_address: 172.60.0.25 diff --git a/compose/vpn.yaml b/compose/vpn.yaml index 8239e75..3f33b53 100644 --- a/compose/vpn.yaml +++ b/compose/vpn.yaml @@ -1,5 +1,5 @@ # Overlay: VPN via Gluetun — routes qBittorrent through VPN -# Usage: docker compose -f base.yaml -f vpn.yaml --profile up -d +# Usage: docker compose -f base.yaml -f vpn.yaml up -d services: gluetun: @@ -65,7 +65,7 @@ services: restart: unless-stopped deunhealth: - image: qmcgaw/deunhealth:v0.3.0 + image: qmcgaw/deunhealth@sha256:db1e4fcd3aceeb0da34a83f7a8a5432df586e6d0388ddb6ad8dd7b479e4aa25d container_name: deunhealth network_mode: "none" environment: diff --git a/compose/vuetorrent.yaml b/compose/vuetorrent.yaml new file mode 100644 index 0000000..f464162 --- /dev/null +++ b/compose/vuetorrent.yaml @@ -0,0 +1,5 @@ +# Overlay: VueTorrent alternate WebUI mod for LinuxServer.io qBittorrent +services: + qbittorrent: + environment: + - DOCKER_MODS=ghcr.io/vuetorrent/vuetorrent-lsio-mod:2.37.0 diff --git a/docs/api-reference.md b/docs/api-reference.md index c46a56f..1d2b434 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -10,19 +10,25 @@ assemblrr services generate API keys during initial boot. Extract them using the | Service | Port | Config / Secret Location | Auth Header / Query Parameter | | :--- | :--- | :--- | :--- | -| **Radarr** | `7878` | `config/radarr/config.xml` | `?apikey=$KEY` or `X-Api-Key: $KEY` | -| **Sonarr** | `8989` | `config/sonarr/config.xml` | `?apikey=$KEY` or `X-Api-Key: $KEY` | -| **Prowlarr** | `9696` | `config/prowlarr/config.xml` | `?apikey=$KEY` or `X-Api-Key: $KEY` | -| **Bazarr** | `6767` | `secrets/bazarr_api_key.txt` | `?apikey=$KEY` or `X-API-KEY: $KEY` | +| **Radarr** | `7878` | `config/radarr/config.xml` | `X-Api-Key: $KEY` | +| **Sonarr** | `8989` | `config/sonarr/config.xml` | `X-Api-Key: $KEY` | +| **Prowlarr** | `9696` | `config/prowlarr/config.xml` | `X-Api-Key: $KEY` | +| **Bazarr** | `6767` | `secrets/bazarr_api_key.txt` | `X-API-KEY: $KEY` | | **Seerr** | `5055` | `config/seerr/settings.json` | `X-Api-Key: $KEY` | -| **Jellyfin** | `8096` | `secrets/jellyfin_api_key.txt` | `X-Emby-Token: $KEY` or `Authorization: MediaBrowser Token="$KEY"` | -| **qBittorrent** | `8080` | `config/qbittorrent/` | Cookie-based auth via `/api/v2/auth/login` | +| **Jellyfin** | `8096` | `secrets/jellyfin_api_key.txt` | `Authorization: MediaBrowser Client="cli", Device="cli", DeviceId="cli", Version="1.0", Token="$KEY"` | +| **qBittorrent** | `8081` | `secrets/auth_*.txt` | Cookie-based auth (`SID` / `QBT_SID_*`) via `/api/v2/auth/login` | +| **SABnzbd** *(opt.)* | `8085` | `config/sabnzbd/sabnzbd.ini` | `?apikey=$KEY` (`mode=...&output=json`) | +| **Byparr** *(opt.)* | `8191` (internal) | — | Unauthenticated HTTP challenge proxy inside `assemblrr_network` | + +> [!NOTE] +> Jellyfin 12.4 removed legacy `X-Emby-Token` defaults in favor of standard `Authorization: MediaBrowser ... Token="..."` headers. assemblrr uses `Authorization: MediaBrowser` across all scripts and setup modules. ### Quick Key Extraction (Bash Snippet) ```bash RADARR_KEY=$(sed -n 's/.*\(.*\)<\/ApiKey>.*/\1/p' config/radarr/config.xml | head -1) SONARR_KEY=$(sed -n 's/.*\(.*\)<\/ApiKey>.*/\1/p' config/sonarr/config.xml | head -1) PROWLARR_KEY=$(sed -n 's/.*\(.*\)<\/ApiKey>.*/\1/p' config/prowlarr/config.xml | head -1) +SABNZBD_KEY=$(sed -n 's/^[[:space:]]*api_key[[:space:]]*=[[:space:]]*//p' config/sabnzbd/sabnzbd.ini | head -1) BAZARR_KEY=$(cat secrets/bazarr_api_key.txt 2>/dev/null) JELLYFIN_KEY=$(cat secrets/jellyfin_api_key.txt 2>/dev/null) ``` @@ -34,60 +40,60 @@ JELLYFIN_KEY=$(cat secrets/jellyfin_api_key.txt 2>/dev/null) ### 1. Quality Profiles * **List all profiles:** ```bash - curl -s "http://127.0.0.1:7878/api/v3/qualityprofile?apikey=$RADARR_KEY" | jq '.[] | {id: .id, name: .name}' + curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/qualityprofile" | jq '.[] | {id: .id, name: .name}' ``` * **Inspect a specific profile:** ```bash - curl -s "http://127.0.0.1:7878/api/v3/qualityprofile/1?apikey=$RADARR_KEY" | jq . - ``` -* **Delete an orphaned profile:** - ```bash - curl -s -X DELETE "http://127.0.0.1:7878/api/v3/qualityprofile/8?apikey=$RADARR_KEY" + curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/qualityprofile/1" | jq . ``` ### 2. Media Management & Hardlinks * **Inspect Media Management config:** ```bash - curl -s "http://127.0.0.1:7878/api/v3/config/mediamanagement?apikey=$RADARR_KEY" | jq '{copyUsingHardlinks, recycleBin, recycleBinCleanupDays}' - ``` -* **Disable recycle bin and verify hardlinks:** - ```bash - curl -s "http://127.0.0.1:7878/api/v3/config/mediamanagement?apikey=$RADARR_KEY" \ - | jq '.copyUsingHardlinks = true | .recycleBin = "" | .recycleBinCleanupDays = 0' \ - | curl -s -X PUT "http://127.0.0.1:7878/api/v3/config/mediamanagement?apikey=$RADARR_KEY" -H "Content-Type: application/json" -d @- + curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/config/mediamanagement" | jq '{copyUsingHardlinks, recycleBin, recycleBinCleanupDays}' ``` -### 3. Root Folders -* **List root folders and default profile IDs:** - ```bash - curl -s "http://127.0.0.1:7878/api/v3/rootfolder?apikey=$RADARR_KEY" | jq . - ``` - -### 4. Queue & Active Downloads +### 3. Queue & Active Downloads * **Inspect download queue:** ```bash - curl -s "http://127.0.0.1:7878/api/v3/queue?apikey=$RADARR_KEY" | jq '.records[] | {id: .id, title: .title, status: .status, downloadId: .downloadId}' + curl -s -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/queue" | jq '.records[] | {id: .id, title: .title, status: .status, downloadId: .downloadId}' ``` * **Drain a specific queue item from *arr and download client:** ```bash - curl -s -X DELETE "http://127.0.0.1:7878/api/v3/queue/123?apikey=$RADARR_KEY&removeFromClient=true&blocklist=false" + curl -s -X DELETE -H "X-Api-Key: $RADARR_KEY" "http://127.0.0.1:7878/api/v3/queue/123?removeFromClient=true&blocklist=false" ``` --- ## Seerr & Seerr Gateway Recipes -`seerr-gateway` sits on port `5055` as a sidecar proxying Overseas/Jellyseerr. +`seerr-gateway` sits on port `5055` and verifies caller permissions via `GET /api/v1/auth/me` before intercepting `DELETE /api/v1/request/:id`. +* **Check gateway health & upstream readiness:** + ```bash + curl -s http://127.0.0.1:5055/_assemblrr/ready | jq . + ``` * **List pending/approved requests:** ```bash curl -s "http://127.0.0.1:5055/api/v1/request?take=20" -H "X-Api-Key: $SEERR_KEY" | jq '.results[] | {id: .id, type: .type, media: .media.tmdbId, status: .status}' ``` -* **Test request-delete cascade:** + +--- + +## Optional Overlays: SABnzbd & Byparr + +* **Check SABnzbd version and queue (when `USENET_ENABLED=y`):** ```bash - curl -i -X DELETE "http://127.0.0.1:5055/api/v1/request/42" -H "X-Api-Key: $SEERR_KEY" + curl -s "http://127.0.0.1:8085/api?mode=queue&output=json&apikey=$SABNZBD_KEY" | jq . + ``` +* **Check Byparr health (inside container network when `BYPARR_ENABLED=y`):** + ```bash + docker exec byparr python3 -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8191/health').read().decode())" + ``` +* **Inspect Prowlarr indexer proxies (`byparr` tag):** + ```bash + curl -s -H "X-Api-Key: $PROWLARR_KEY" "http://127.0.0.1:9696/api/v1/indexerProxy" | jq . ``` - *(Responses will include `X-Assemblrr-Purge-Detail` headers indicating queue drains and media deletions.)* --- @@ -101,22 +107,19 @@ JELLYFIN_KEY=$(cat secrets/jellyfin_api_key.txt 2>/dev/null) ```bash docker exec recyclarr recyclarr list quality-profiles radarr docker exec recyclarr recyclarr list quality-profiles sonarr - docker exec recyclarr recyclarr list custom-formats radarr ``` --- ## Official API Documentation Links -| Service | Official Documentation | Notes | -| :--- | :--- | :--- | -| **Radarr** | https://radarr.video/docs/api/ | OpenAPI / Swagger UI | -| **Sonarr** | https://sonarr.tv/docs/api/ | v3 OpenAPI spec (covers Sonarr v3 and v4) | -| **Prowlarr** | https://prowlarr.com/docs/api/ | OpenAPI / Swagger UI | -| **Bazarr** | https://wiki.bazarr.media/ | Companion subtitle manager API | -| **Seerr** | https://api-docs.overseerr.dev/ | Jellyseerr / Overseerr Swagger UI | -| **Jellyfin** | https://api.jellyfin.org/ | OpenAPI stable spec | -| **qBittorrent** | https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1) | Web API Reference | -| **Servarr Wiki** | https://wiki.servarr.com/ | Servarr community configuration & troubleshooting | - - +| Service | Official Documentation | +| :--- | :--- | +| **Radarr** | https://radarr.video/docs/api/ | +| **Sonarr** | https://sonarr.tv/docs/api/ | +| **Prowlarr** | https://prowlarr.com/docs/api/ | +| **Bazarr** | https://wiki.bazarr.media/ | +| **Seerr** | https://api-docs.overseerr.dev/ | +| **Jellyfin** | https://api.jellyfin.org/ | +| **qBittorrent** | https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1) | +| **SABnzbd** | https://sabnzbd.org/wiki/configuration/4.3/api | diff --git a/docs/komodo.md b/docs/komodo.md new file mode 100644 index 0000000..a9bcf63 --- /dev/null +++ b/docs/komodo.md @@ -0,0 +1,37 @@ +# Running assemblrr with Komodo + +[Komodo](https://komo.do/) can deploy and monitor assemblrr's Compose stack once `setup` (or a manual `.env` + `secrets/` setup) has initialized the install directory. + +## How Compose Overlays Fit Komodo + +assemblrr keeps its stack modular under `compose/`: + +- **Always required:** `compose/base.yaml` + **one** network mode (`compose/vpn.yaml` or `compose/direct-access.yaml`) +- **Optional feature overlays:** + - `compose/vuetorrent.yaml` (`VUETORRENT_ENABLED=y`) + - `compose/gpu-intel.yaml` (`GPU_TRANSCODING=intel`) or `compose/gpu-nvidia.yaml` (`GPU_TRANSCODING=nvidia`) + - `compose/byparr.yaml` (`BYPARR_ENABLED=y`) + - `compose/usenet.yaml` (`USENET_ENABLED=y`) +- **Custom services:** `compose/custom.yaml` (always appended last; see [`compose/examples/custom.yaml.example`](../compose/examples/custom.yaml.example) for a `komodo-periphery` service block on `.33`) + +## Recommended Komodo Stack Configuration + +1. Run `assemblrr` setup (or `restore`) once on the target host so `.env`, `secrets/`, `config/`, and `scripts/` exist with proper `PUID`/`PGID` permissions. +2. Point a **Komodo Stack** at your install directory (e.g. `~/assemblrr`) with **File Paths** matching your enabled overlays, in order: + ```text + compose/base.yaml + compose/vpn.yaml + compose/vuetorrent.yaml + compose/gpu-intel.yaml + compose/byparr.yaml + compose/usenet.yaml + compose/custom.yaml + ``` + *(Omit any overlay you did not enable, or replace `compose/vpn.yaml` with `compose/direct-access.yaml`.)* +3. Configure **Env File Path**: `.env` (or paste generated `.env` values into Komodo's environment editor without duplicating secret files from `secrets/`). +4. Keep **Project Directory** set to the install root (`INSTALL_DIRECTORY`) so relative secret and config paths resolve correctly. + +## Upgrades & Re-wiring + +- Use `assemblrr upgrade --skip-stack` (from CLI) if you let Komodo handle `docker compose up -d --build`, or run `assemblrr upgrade` normally and let Komodo re-sync state. +- Whenever you add a service or change API credentials, run `assemblrr config apply` to re-run idempotent `*arr` / Jellyfin / Bazarr / Seerr / SABnzbd wiring. diff --git a/docs/seerr-delete-request.md b/docs/seerr-delete-request.md index d63c12f..ba7276b 100644 --- a/docs/seerr-delete-request.md +++ b/docs/seerr-delete-request.md @@ -1,8 +1,8 @@ # Seerr “Delete request” → media purge -assemblrr product intent: when a user deletes a Seerr **request**, the stack -should also remove **that request’s** library files under `media/` and the -matching qBittorrent torrent/data under `torrents/` (hardlink-aware). +assemblrr product intent: when an authorized user deletes a Seerr **request**, the stack +should also remove **that request’s** library files under `media/` and the matching download +items under `torrents/` / `usenet/` (hardlink-aware). - **Movies:** the whole title. - **TV:** only the seasons on that request. Other seasons of the same show stay, @@ -20,64 +20,47 @@ listens only on the Docker network. Almost all traffic is proxied unchanged. On **`DELETE /api/v1/request/:id`** only (when purge is enabled): -1. `GET /api/v1/request/:id` — capture linked `media.id`, `is4k`, type, and - requested season numbers (same auth headers as the client). -2. **Drain the *arr download queue first** (while the title still exists): - `DELETE /api/v3/queue/{id}?removeFromClient=true`. That is how an in-progress - grab is cancelled — Radarr/Sonarr already know the torrent hash. Queue drain - is best-effort (missing API key or empty queue is not a hard failure). -3. Purge files: +1. `GET /api/v1/auth/me` — verify caller identity & Seerr permissions (`ADMIN` or `MANAGE_REQUESTS`) + before invoking any privileged `*arr` APIs (prevents confused-deputy deletion). Non-admin users + cancelling their own **pending** request pass straight through to Seerr `DELETE` without touching + downloaded files; unauthorized attempts fail closed (`401`/`403`). +2. `GET /api/v1/request/:id` — capture linked `media.id`, `is4k`, type, and + requested season numbers (fails closed with `502` on upstream 5xx). +3. **Drain the *arr download queue first** (while the title still exists): + `DELETE /api/v3/queue/{id}?removeFromClient=true`. +4. Purge files: - **Movie**, or a TV request that covers every remaining on-disk/monitored season (specials count as remaining) → `DELETE /api/v1/media/:mediaId/file?is4k=…` - (Seerr → *arr `deleteFiles` → assemblrr purge hooks / qB). + (Seerr → *arr `deleteFiles` → assemblrr purge hooks / qB / SABnzbd). - **TV subset of seasons** → Sonarr `DELETE /episodefile/{id}` for those seasons only, then unmonitor them. Seerr title-level file-delete is **not** called, so `/data/media/tv/Show` is not wiped. `media-purge-watch` - then season-scopes qB cleanup when that season folder empties. -4. `DELETE /api/v1/request/:id` — drop the request row (response returned to - the client). - -If media was never linked, step 2 is skipped; the request is still deleted. -Auth failures on step 1 are returned to the client with no deletes. -If a TV request has no season list, the Sonarr API key is missing, or a -season-scoped Sonarr call fails, the gateway returns **502** and does -**not** delete the request (it never title-deletes on uncertainty). + then season-scopes download cleanup when that season folder empties. +5. `DELETE /api/v1/request/:id` — drop the request row and return the response. | Piece | Role | |------|------| -| `scripts/seerr-gateway.py` | Reverse proxy + request-delete intercept (season-aware for TV) | -| `compose/base.yaml` → `seerr-gateway` | Publishes 5055; `seerr` is internal only; reads Sonarr API key | -| `scripts/arr-purge-hook.sh` / `media-purge.sh` | qB + disk cleanup; `--seasons` for partial TV | -| `scripts/media-purge-watch.sh` | inotify: empty season folder → `--seasons` purge (even if other seasons are only monitored/downloading); movie / series-root delete → title purge | +| `scripts/seerr-gateway.py` | Authenticating reverse proxy + request-delete intercept | +| `compose/base.yaml` → `seerr-gateway` | Publishes 5055; `seerr` is internal only; reads Sonarr/Radarr API keys | +| `scripts/arr-purge-hook.sh` / `media-purge.sh` | qB + SABnzbd + disk cleanup; `--seasons` for partial TV | +| `scripts/media-purge-watch.sh` | inotify: empty season folder → `--seasons` purge; movie / series-root delete → title purge | -### Title-level delete in Seerr (not season-safe) - -Seerr’s own **bulk delete / “remove from library” / delete files** on a TV -card is `DELETE /api/v1/media/:id/file`. That always removes the **entire -series** from Sonarr (`deleteFiles: true`). assemblrr does **not** intercept -that path: it means “this title”. - -When a title is deleted, library files are deleted immediately to instantly reclaim disk space. The series-delete hook then removes the matching qB torrent **and** leftover folders under `torrents/tv` / `torrents/movies` (Completed Download Handling often drops the qB row first, which used to leave the download directory behind). - -### Purge safety (qB) +### Purge safety (`media-purge.sh`) `media-purge.sh` prefers under-delete over collateral damage: -1. *arr **queue + history** download hashes that still exist in qB. The hash is - identity — a live grab named `The Avengers 2012 REPACK…` is removed even - though it does not look like `The Avengers (2012)`. -2. Title + year match on torrent name / content path. `(2012)` and `2012` are - the same year; indexer prefixes (`www.UIndex.org - …`) are allowed; the - token after the title must be that year so `Avengers Age of Ultron 2015` - and `It Comes at Night 2017` stay put. +1. *arr **queue + history** download IDs/hashes that still exist in qBittorrent or SABnzbd (`SABnzbd_nzo_*`). +2. Title + year match on release name / content path. `(2016)` and `2016` are + the same year; indexer domain prefixes (`indexer.example - …`) are allowed; the + token after the title must be that year so `Alpha Film Sequel Extended (2022)` + or `Nova Comes at Night 2017` stay untouched for `Alpha Film (2016)` or `Nova (2017)`. 3. Refuse ambiguous multi-matches on the name step. Short keys (`Oz`) skipped. 4. **Season purge:** torrent must name one of the requested seasons (`S01` / - `Season 1`) and must **not** also name another season. Packs like - `Show.S01.S02.COMPLETE` and ranges like `Show.S01-03` are left alone - when deleting S01 only. A torrent with no season token is left alone - on the name step (queue/history hashes for that season are still removed). + `Season 1` / `Specials`) with strict token boundaries (ignoring codecs like `DTS5.1` or `x265`) + and must **not** also name another season. Packs like `Sample.Show.S01.S02.COMPLETE` + and ranges like `Sample.Show.S01-03` are left alone when deleting S01 only. -See `media-purge.sh --match-self-test`. +See `tests/unit/test_media_purge_match.sh`. Env: @@ -87,57 +70,18 @@ Env: | `MEDIA_PURGE_WATCH` | `1` | `1` = inotify watcher on library video deletes; `0` = disable watcher only | | `SEERR_UPSTREAM` | `http://seerr:5055` | Upstream Seerr (container) | | `SONARR_URL` | `http://sonarr:8989` | Used by the gateway for TV season deletes + queue drain | -| `SONARR_CONFIG` | `/config/sonarr/config.xml` | API key source when `SONARR_API_KEY` is unset | | `RADARR_URL` | `http://radarr:7878` | Used by the gateway to drain in-progress movie grabs | -| `RADARR_CONFIG` | `/config/radarr/config.xml` | API key source when `RADARR_API_KEY` is unset | -Debug response headers on intercepted deletes: +## When Seerr adds this natively -- `X-Assemblrr-Request-Delete-Purge: 1` -- `X-Assemblrr-Purge-Detail: …` (e.g. `queue_movie:1:1;media_file_deleted:7:204`, - `seasons_deleted:6:10:1:3`, `no_media`) - -Health (gateway only, not Seerr): - -- `GET /_assemblrr/health` — process up -- `GET /_assemblrr/ready` — upstream Seerr public settings reachable - -## Why not a Seerr fork - -Forking Seerr for one product preference is ongoing merge cost. The gateway -owns only this behavior and stays a small managed script. - -## When Seerr adds this natively — **must adjust** - -If a future Seerr/Overseerr release deletes media (or offers a setting to) on -request delete, **this gateway intercept becomes wrong or redundant** (double -delete races, confusing semantics). Do the following: - -1. **Confirm** upstream behavior in Seerr release notes / source: - - Does `DELETE /api/v1/request/:id` call *arr with `deleteFiles`? - - Is it always on, or a setting? - - Is it season-scoped for TV? -2. **Short term:** set `SEERR_DELETE_REQUEST_PURGE=0` in the install `.env` - (or compose environment) and restart `seerr-gateway`. Traffic stays on 5055; - intercept is off. Verify once that stock delete-request still meets product - intent with your purge hooks. -3. **Long term (preferred once native behavior is permanent and correct):** - - Remove the `seerr-gateway` service from `compose/base.yaml` - - Publish `5055:5055` on `seerr` again - - Drop `scripts/seerr-gateway.py` from `lib/managed_files.sh` and the repo - - Update this doc, `lib/services.sh` (catalog back to `seerr|Seerr|5055`), - `docs/uninstall.md`, and live tests that assert gateway headers - - Remove any mention of `SEERR_DELETE_REQUEST_PURGE` -4. **Do not** leave the intercept enabled “just in case” after Seerr already - purges on request delete — that can double-call *arr delete paths. - -Track ownership: this file and `scripts/seerr-gateway.py` header comment. +If a future Seerr release natively deletes media on request delete, set `SEERR_DELETE_REQUEST_PURGE=0` +or remove `seerr-gateway` from `compose/base.yaml` and publish `5055:5055` directly on `seerr`. ## Tests ```bash -# Offline unit (mock Seerr + mock Sonarr): -python3 scripts/seerr-gateway.py --self-test +# Offline gateway unit suite (mock Seerr + Sonarr + Radarr): +python3 -m unittest tests/unit/test_seerr_gateway_suite.py -v # or ./tests/unit/test_seerr_gateway.sh @@ -148,7 +92,3 @@ python3 scripts/seerr-gateway.py --self-test # Live (opt-in; real install): ASSEMBLRR_ALLOW_LIVE_TEST=1 ./tests/integration/media_purge_e2e.sh ``` - -The live suite includes **delete request through the gateway** → full cascade -for a **movie**, and documents that stock Seerr request-delete alone does not -wipe files. diff --git a/docs/trash-guides.md b/docs/trash-guides.md index 2a2f41a..fe17353 100644 --- a/docs/trash-guides.md +++ b/docs/trash-guides.md @@ -2,7 +2,7 @@ assemblrr uses [Recyclarr](https://recyclarr.dev/) to sync [TRaSH Guides](https://trash-guides.info/) quality profiles and custom formats into Radarr and Sonarr. -**Subtitles:** Bazarr is wired separately (not via Recyclarr). On first install and every `assemblrr upgrade`, assemblrr applies [TRaSH Bazarr suggested scoring](https://trash-guides.info/Bazarr/Bazarr-suggested-scoring/) (series min 90, movies 80, auto-sync 96/86). If any selected subtitle language is not English, those minimum scores drop to 70/50: OpenSubtitles.com rarely hash-matches non-English WEB-DL releases, and TRaSH 90/80 would skip them. Subsync still retimes anything below the sync thresholds. Subtitle languages are a two-step fzf: multi-select what to download, then (if more than one) which Jellyfin should prefer. Providers are chosen interactively from the running Bazarr image (fzf multi-select; nothing enabled unless you pick it). OpenSubtitles.com is enabled only when you saved credentials during setup. Greek also enables the `greeksubs` provider unless you confirmed a provider list without it. +**Subtitles:** Bazarr is wired separately (not via Recyclarr). On first install and every `assemblrr upgrade`, assemblrr applies [TRaSH Bazarr suggested scoring](https://trash-guides.info/Bazarr/Bazarr-suggested-scoring/) (series min 90, movies 80, auto-sync 96/86). If any selected subtitle language is not English, those minimum scores drop to 70/50: OpenSubtitles.com rarely hash-matches non-English WEB-DL releases, and TRaSH 90/80 would skip them. Subsync still retimes anything below the sync thresholds. Subtitle languages are a two-step fzf: multi-select what to download, then (if more than one) which Jellyfin should prefer. Providers are chosen interactively from the running Bazarr image (fzf multi-select; nothing auto-enabled beyond OpenSubtitles.com when credentials were explicitly saved). **Both resolutions and both movie sources are always installed** as assemblrr-named profiles: diff --git a/docs/uninstall.md b/docs/uninstall.md index 7826847..f0fe24a 100644 --- a/docs/uninstall.md +++ b/docs/uninstall.md @@ -13,7 +13,7 @@ root-owned; plain `rm -rf` then fails — use the Docker removal step in Option | Component | Default location | |---|---| -| Containers | `jellyfin`/`emby`/`plex` (your choice), `qbittorrent`, `sonarr`, `radarr`, `prowlarr`, `bazarr`, `seerr`, `seerr-gateway`, `media-purge-watch`, `recyclarr` — plus `gluetun`, `deunhealth`, `vpn-watchdog` when VPN is enabled; older installs may still have `portainer` | +| Containers | `jellyfin`, `qbittorrent`, `sonarr`, `radarr`, `prowlarr`, `bazarr`, `seerr`, `seerr-gateway`, `media-purge-watch`, `recyclarr` — plus `sabnzbd` (`usenet`), `byparr` (`byparr`), and `gluetun`/`deunhealth`/`vpn-watchdog` (`vpn`) when enabled; older installs may have `portainer`/`emby`/`plex` | | Docker network | `assemblrr_network` | | Install directory (config, secrets, compose files) | `~/assemblrr` (or the path you chose) | | Media directory (your movies/TV/downloads) | `~/assemblrr-media` (or the path you chose) | @@ -93,7 +93,7 @@ you deliberately remove it in step 3. **1. Remove containers and the network:** ```bash -docker rm -f jellyfin emby plex qbittorrent sonarr radarr prowlarr bazarr \ +docker rm -f jellyfin sabnzbd byparr qbittorrent sonarr radarr prowlarr bazarr \ seerr seerr-gateway media-purge-watch recyclarr portainer \ gluetun deunhealth vpn-watchdog 2>/dev/null # portainer: only if an older install still has it @@ -141,12 +141,11 @@ rm -f ~/.assemblrr-config 2>/dev/null # discovery pointer **5. Optional — remove the Docker images:** ```bash -# VPN mode also pulls qmcgaw/gluetun and qmcgaw/deunhealth; -# swap jellyfin for emby/plex if you chose a different media server docker rmi lscr.io/linuxserver/jellyfin lscr.io/linuxserver/qbittorrent \ lscr.io/linuxserver/sonarr lscr.io/linuxserver/radarr \ - lscr.io/linuxserver/prowlarr \ - ghcr.io/seerr-team/seerr ghcr.io/recyclarr/recyclarr alpine:3 + lscr.io/linuxserver/prowlarr lscr.io/linuxserver/bazarr \ + lscr.io/linuxserver/sabnzbd ghcr.io/thephaseless/byparr \ + ghcr.io/seerr-team/seerr ghcr.io/recyclarr/recyclarr alpine:3.24.4 # older installs: docker rmi portainer/portainer-ce ``` diff --git a/lib/api.sh b/lib/api.sh old mode 100644 new mode 100755 index 2184b3e..4ed514d --- a/lib/api.sh +++ b/lib/api.sh @@ -1,28 +1,93 @@ #!/bin/bash -# assemblrr API helpers — sourced by config.sh -# Provides: jq helpers, API request wrappers, API key discovery, wait_for_api -# Requires: lib/core.sh already sourced (for logging), API_HOST and INSTALL_DIR set +# SPDX-License-Identifier: GPL-3.0-or-later +# assemblrr API / HTTP helpers — sourced by wiring modules and entrypoints +# Requires: lib/core.sh (logging), API_HOST and INSTALL_DIR set -set -euo pipefail +if [ -n "${_ASSEMBLRR_API_SOURCED:-}" ]; then + return 0 +fi +readonly _ASSEMBLRR_API_SOURCED=1 -# --- JSON helpers using jq --- +ASSEMBLRR_CURL_BIN="${ASSEMBLRR_CURL_BIN:-curl}" +HTTP_STATUS="" +HTTP_BODY="" + +# --- JSON & encoding helpers --- jq_json_get() { local json="$1" local key="$2" - echo "$json" | jq -r --arg k "$key" '.[$k] // empty' 2>/dev/null + printf '%s' "$json" | jq -r --arg k "$key" '.[$k] // empty' 2>/dev/null } jq_json_has_key() { local json="$1" local key="$2" - echo "$json" | jq -e --arg k "$key" 'has($k)' >/dev/null 2>&1 + printf '%s' "$json" | jq -e --arg k "$key" 'has($k)' >/dev/null 2>&1 } jq_json_list_values() { local json="$1" local key="$2" - echo "$json" | jq -r --arg k "$key" '.[][$k] // empty' 2>/dev/null + printf '%s' "$json" | jq -r --arg k "$key" '.[][$k] // empty' 2>/dev/null +} + +urlencode() { + jq -rn --arg v "${1:-}" '$v | @uri' 2>/dev/null || printf '%s' "${1:-}" +} + +# --- Shared HTTP transport --- + +# Execute curl and populate globals HTTP_STATUS (3-digit code, "000" on network failure) +# and HTTP_BODY. Returns 0 on 2xx, 1 otherwise. +http_request() { + local method="$1" + local url="$2" + shift 2 + + local tmp rc=0 + tmp=$(mktemp) + HTTP_STATUS="" + HTTP_BODY="" + + HTTP_STATUS=$("$ASSEMBLRR_CURL_BIN" -s -o "$tmp" -w "%{http_code}" --connect-timeout 5 --max-time 30 \ + -X "$method" "$@" "$url" 2>/dev/null) || rc=$? + HTTP_BODY=$(cat "$tmp" 2>/dev/null || true) + rm -f "$tmp" + + HTTP_STATUS="${HTTP_STATUS//[^0-9]/}" + if [ "${#HTTP_STATUS}" -ne 3 ]; then + HTTP_STATUS="000" + fi + + if [ "$rc" -eq 0 ] && [ "$HTTP_STATUS" -ge 200 ] && [ "$HTTP_STATUS" -lt 300 ]; then + return 0 + fi + return 1 +} + +# Reusable polling helper: wait_until