From 7a101e44746e22de6162be206e6161395401be97 Mon Sep 17 00:00:00 2001 From: soulis-1256 Date: Sat, 21 Nov 2026 21:53:22 +0200 Subject: [PATCH] fix(watchdog,seerr,ci): reuse qBit session cookie, fix single-instance Seerr is4k routing, resolve all shellcheck CI issues --- bin/cli.sh | 1 + bin/setup.sh | 17 +- lib/config_edit.sh | 4 + lib/fs.sh | 14 +- lib/log.sh | 1 + lib/paths.sh | 7 +- lib/prompts.sh | 1 + lib/recyclarr.sh | 1 + lib/seerr.sh | 10 +- scripts/jellyfin-refresh.sh | 137 +++++++------ scripts/media-purge-watch.sh | 3 +- scripts/media-purge.sh | 5 +- scripts/vpn-watchdog.sh | 258 ++++++++++++++---------- tests/helpers.sh | 1 + tests/integration/watchdog_stall.sh | 3 +- tests/unit/test_compose.sh | 4 +- tests/unit/test_config_edit.sh | 9 + tests/unit/test_core.sh | 1 + tests/unit/test_env_example.sh | 4 +- tests/unit/test_media_purge_match.sh | 1 + tests/unit/test_overlays.sh | 12 +- tests/unit/test_prepare_install_dirs.sh | 1 + tests/unit/test_quality.sh | 12 +- tests/unit/test_setup_restore.sh | 10 +- tests/unit/test_usenet.sh | 1 + tests/unit/test_vpn_watchdog.sh | 5 + 26 files changed, 304 insertions(+), 219 deletions(-) diff --git a/bin/cli.sh b/bin/cli.sh index 293fa3b..b5048f0 100755 --- a/bin/cli.sh +++ b/bin/cli.sh @@ -978,6 +978,7 @@ restore_app() { "${DC[@]}" up -d --remove-orphans || log_warning "Failed to start services" echo "Cleaning up old safety snapshots (keeping last 3)..." + # shellcheck disable=SC2012 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 diff --git a/bin/setup.sh b/bin/setup.sh index eb51d79..d0d0f9e 100755 --- a/bin/setup.sh +++ b/bin/setup.sh @@ -269,8 +269,8 @@ generate_env_file() { if [ "${setup_vpn,,}" = "y" ]; then VPN_ENABLED="y" - VPN_SERVICE="$vpn_service" - VPN_TYPE="$vpn_type" + VPN_SERVICE="${vpn_service:-}" + VPN_TYPE="${vpn_type:-openvpn}" WIREGUARD_ADDRESSES="${wireguard_addresses:-}" if [ "${enable_port_forwarding,,}" = "y" ]; then PORT_FORWARD_ONLY="on" @@ -299,7 +299,11 @@ generate_env_file() { export WIREGUARD_ADDRESSES export PORT_FORWARD_ONLY VPN_PORT_FORWARDING export QBIT_UI="${qbit_ui:-vuetorrent}" - [ "$QBIT_UI" = "vuetorrent" ] && export VUETORRENT_ENABLED="y" || export VUETORRENT_ENABLED="n" + if [ "$QBIT_UI" = "vuetorrent" ]; then + export VUETORRENT_ENABLED="y" + else + export VUETORRENT_ENABLED="n" + fi export GPU_TRANSCODING="${gpu_transcoding:-none}" export BYPARR_ENABLED="${byparr_enabled:-n}" export USENET_ENABLED="${usenet_enabled:-n}" @@ -310,6 +314,7 @@ generate_env_file() { log_error "Failed to locate .env.example" fi # Explicit key list matching .env.example 1-to-1 + # shellcheck disable=SC2016 envsubst '${PUID} ${PGID} ${MEDIA_DIRECTORY} ${INSTALL_DIRECTORY} ${MEDIA_SERVICE} ${TZ} ${VPN_ENABLED} ${VPN_SERVICE} ${VPN_TYPE} ${WIREGUARD_ADDRESSES} ${PORT_FORWARD_ONLY} ${VPN_PORT_FORWARDING} ${QBIT_UI} ${VUETORRENT_ENABLED} ${GPU_TRANSCODING} ${BYPARR_ENABLED} ${USENET_ENABLED} ${API_HOST}' \ < "$env_template" | tr -d '\r' > "$env_file" || \ log_error "Failed to generate .env file" @@ -872,8 +877,10 @@ main() { echo " User: $username (PUID=$puid, PGID=$pgid)" echo " Install directory: $install_directory" echo " Media directory: $media_directory" + setup_vpn="${setup_vpn:-n}" + enable_port_forwarding="${enable_port_forwarding:-n}" if [ "${setup_vpn,,}" = "y" ]; then - echo " VPN: ENABLED ($vpn_service, $vpn_type)" + echo " VPN: ENABLED (${vpn_service:-}, ${vpn_type:-wireguard})" echo " Port forwarding: ${enable_port_forwarding:-n}" else echo " VPN: DISABLED" @@ -886,7 +893,7 @@ main() { if [ "$QUALITY_TIER" = "any" ]; then echo " Quality profile: any" else - echo " Quality profile: $QUALITY_TIER / ${QUALITY_SOURCE:-bluray} (4K=$seerr_is_4k)" + echo " Quality profile: $QUALITY_TIER / ${QUALITY_SOURCE:-bluray} (4K=${seerr_is_4k:-false})" fi if [ -n "${subtitle_languages:-}" ] && [ "${subtitle_languages}" != "${subtitle_language:-}" ]; then echo " Subtitle languages: ${subtitle_language} (preferred), ${subtitle_languages#*,}" diff --git a/lib/config_edit.sh b/lib/config_edit.sh index 65a56cc..a355cb6 100755 --- a/lib/config_edit.sh +++ b/lib/config_edit.sh @@ -155,13 +155,16 @@ _config_edit_load() { CONFIGURE_LOG="${CONFIGURE_LOG:-/tmp/${APP_NAME:-assemblrr}-config-edit-$(date '+%Y%m%d-%H%M%S').log}" if ! type _cfg_log_info >/dev/null 2>&1; then + # shellcheck disable=SC2329 _cfg_log_info() { echo " $1" | tee -a "$CONFIGURE_LOG"; } fi if ! type log_step >/dev/null 2>&1; then _configure_total=0 _configure_ok=0 _configure_fail=0 + # shellcheck disable=SC2329 log_step() { printf ' %b✓%b %s\n' "${GREEN:-}" "${NC:-}" "$1"; printf ' ✓ %s\n' "$1" >> "$CONFIGURE_LOG"; _configure_ok=$((_configure_ok + 1)); _configure_total=$((_configure_total + 1)); } + # shellcheck disable=SC2329 log_step_fail() { printf ' %b✗%b %s\n' "${RED:-}" "${NC:-}" "$1"; printf ' ✗ %s\n' "$1" >> "$CONFIGURE_LOG"; _configure_fail=$((_configure_fail + 1)); _configure_total=$((_configure_total + 1)); } fi @@ -599,6 +602,7 @@ _config_edit_vpn() { local prev_vpn="${VPN_ENABLED:-n}" configure_vpn || return $? local enabled="n" + setup_vpn="${setup_vpn:-n}" [ "${setup_vpn,,}" = "y" ] && enabled="y" if [ "$enabled" = "n" ] && [ "${prev_vpn,,}" != "y" ]; then log_info "VPN already disabled — no restart needed." diff --git a/lib/fs.sh b/lib/fs.sh index 506dcfc..7563cc0 100755 --- a/lib/fs.sh +++ b/lib/fs.sh @@ -110,6 +110,7 @@ _append_path_line() { ensure_local_bin_on_path() { export PATH="$HOME/.local/bin:$PATH" + # shellcheck disable=SC2016 local line='export PATH="$HOME/.local/bin:$PATH"' local marker='.local/bin' _append_path_line "$HOME/.profile" "$line" "$marker" @@ -121,6 +122,7 @@ ensure_local_bin_on_path() { _append_path_line "$HOME/.zshrc" "$line" "$marker" fi if command -v fish >/dev/null 2>&1 || [ -d "$HOME/.config/fish" ]; then + # shellcheck disable=SC2016 _append_path_line "$HOME/.config/fish/config.fish" 'fish_add_path $HOME/.local/bin' "$marker" fi } @@ -131,18 +133,18 @@ _canonical_path() { realpath -m "$p" 2>/dev/null && return 0 fi # Pure-bash fallback normalizing /./ and /../ segments - local -a segs=() out=() + local -a _cp_segs=() _cp_out=() local s - IFS='/' read -ra segs <<< "$p" - for s in "${segs[@]}"; do + IFS='/' read -ra _cp_segs <<< "$p" + for s in "${_cp_segs[@]}"; do case "$s" in ""|".") continue ;; - "..") [ "${#out[@]}" -gt 0 ] && unset 'out[${#out[@]}-1]' ;; - *) out+=("$s") ;; + "..") [ "${#_cp_out[@]}" -gt 0 ] && unset '_cp_out[${#_cp_out[@]}-1]' ;; + *) _cp_out+=("$s") ;; esac done local joined - joined=$(IFS=/; echo "${out[*]}") + joined=$(IFS=/; echo "${_cp_out[*]}") echo "/$joined" } diff --git a/lib/log.sh b/lib/log.sh index d463438..6c45d08 100755 --- a/lib/log.sh +++ b/lib/log.sh @@ -72,6 +72,7 @@ wait_while() { ) & ticker=$! + # shellcheck disable=SC2329 _wait_while_cleanup() { kill "$ticker" 2>/dev/null || true wait "$ticker" 2>/dev/null || true diff --git a/lib/paths.sh b/lib/paths.sh index a60c30b..38b18c2 100755 --- a/lib/paths.sh +++ b/lib/paths.sh @@ -67,6 +67,7 @@ safe_source() { val="${BASH_REMATCH[1]}" elif [[ "$raw" =~ ^\"(([^\"\\]|\\.)*)\"$ ]]; then val="${BASH_REMATCH[1]}" + # shellcheck disable=SC2016 if [[ "$val" == *'$('* ]] || [[ "$val" == *'`'* ]]; then log_error_inline "Rejecting command substitution in $file: $line" return 1 @@ -77,6 +78,7 @@ safe_source() { val=$(_safe_expand_vars "$val") else # Unquoted value: reject whitespace, shell metacharacters, or quotes + # shellcheck disable=SC2016 case "$raw" in *[[:space:]]*|*'$('*|*'`'*|*';'*|*'|'*|*'&'*|*'>'*|*'<'*|*'('*|*')'*|*\"*|*\'*) log_error_inline "Rejecting unsafe value in $file: $line" @@ -91,7 +93,7 @@ safe_source() { # Make earlier assignments visible to subsequent lines (e.g. branding.conf) printf -v "$key" '%s' "$val" if [ "$do_export" -eq 1 ]; then - export "$key" + export "${key?}" fi done < "$file" return 0 @@ -133,7 +135,7 @@ _pointer_get() { local line [ -f "$file" ] || return 0 line=$(grep -E "^${key}=" "$file" 2>/dev/null | tail -1) || true - line="${line#${key}=}" + line="${line#"${key}"=}" line="${line%$'\r'}" line="${line#\"}" line="${line%\"}" @@ -485,6 +487,7 @@ probe_writable_path() { start=$(date +%s) export ASSEMBLRR_PROBE_FILE="$probe" + # shellcheck disable=SC2016 run_with_timeout "$secs" bash -c \ 'printf ok > "$ASSEMBLRR_PROBE_FILE" && grep -qx ok "$ASSEMBLRR_PROBE_FILE" && rm -f "$ASSEMBLRR_PROBE_FILE"' \ || rc=$? diff --git a/lib/prompts.sh b/lib/prompts.sh index 28534e7..3459c53 100755 --- a/lib/prompts.sh +++ b/lib/prompts.sh @@ -155,6 +155,7 @@ configure_seerr_profile() { configure_subtitle_language() { local iso639_url="https://raw.githubusercontent.com/jellyfin/jellyfin/master/Emby.Server.Implementations/Localization/iso6392.txt" + # shellcheck disable=SC2016 local awk_filter='$4 != "" {print $1 "\t" $4}' SELECTED_SUBTITLE_LANGUAGES=() diff --git a/lib/recyclarr.sh b/lib/recyclarr.sh index d15a95f..731b2c2 100755 --- a/lib/recyclarr.sh +++ b/lib/recyclarr.sh @@ -36,6 +36,7 @@ configure_recyclarr() { # Write with 0600 (contains Radarr/Sonarr API keys) if ! ( umask 077 + # shellcheck disable=SC2016 envsubst '${RADARR_API_KEY} ${SONARR_API_KEY}' \ < "$template_root/recyclarr.yml" \ > "$recyclarr_config_dir/recyclarr.yml" diff --git a/lib/seerr.sh b/lib/seerr.sh index 0e1071f..3c72905 100755 --- a/lib/seerr.sh +++ b/lib/seerr.sh @@ -163,8 +163,9 @@ configure_seerr() { return 1 fi - local connect_errors=0 is_4k - is_4k=$(quality_seerr_is_4k) + # Single-instance setup: Seerr treats is4k=true as a secondary 4K-only server and fails + # default requests when no non-4K server exists; 4K quality is governed by activeProfileName. + local connect_errors=0 is_4k="false" if [ -n "${RADARR_API_KEY:-}" ]; then local radarr_id radarr_id=$(seerr_service_id "radarr" "$seerr_cookie_jar" || true) @@ -253,8 +254,9 @@ configure_seerr() { return 1 fi - local connect_errors=0 is_4k - is_4k=$(quality_seerr_is_4k) + # Single-instance setup: Seerr treats is4k=true as a secondary 4K-only server and fails + # default requests when no non-4K server exists; 4K quality is governed by activeProfileName. + local connect_errors=0 is_4k="false" if [ -n "${RADARR_API_KEY:-}" ]; then if ! seerr_connect_service "radarr" 7878 "$RADARR_API_KEY" "lookup_radarr_profile" \ "/data/media/movies" "$is_4k" "$seerr_cookie_jar"; then diff --git a/scripts/jellyfin-refresh.sh b/scripts/jellyfin-refresh.sh index 1b6956a..9bc8a59 100755 --- a/scripts/jellyfin-refresh.sh +++ b/scripts/jellyfin-refresh.sh @@ -54,18 +54,6 @@ jf_refresh_auth_header() { "${JF_API_KEY:-}" } -if [ "${JF_REFRESH_SOURCE_ONLY:-0}" = "1" ]; then - return 0 2>/dev/null || exit 0 -fi - -_JF_KEY_FROM_SECRET=0 -if [ -f "/run/secrets/jellyfin_api_key.txt" ]; then - JF_API_KEY=$(tr -d '\r\n' < /run/secrets/jellyfin_api_key.txt) - _JF_KEY_FROM_SECRET=1 -else - JF_API_KEY="${JELLYFIN_API_KEY:-}" -fi - jf_refresh_curl() { curl -sS --connect-timeout 5 --max-time 30 \ -H "$(jf_refresh_auth_header)" \ @@ -143,67 +131,82 @@ jf_refresh_acquire_lock() { return 1 } -if [ "${1:-}" = "--heal-only" ]; then +jf_refresh_main() { + _JF_KEY_FROM_SECRET=0 + if [ -f "/run/secrets/jellyfin_api_key.txt" ]; then + JF_API_KEY=$(tr -d '\r\n' < /run/secrets/jellyfin_api_key.txt) + _JF_KEY_FROM_SECRET=1 + else + JF_API_KEY="${JELLYFIN_API_KEY:-}" + fi + + if [ "${1:-}" = "--heal-only" ]; then + if [ -z "$JF_API_KEY" ]; then + echo "Jellyfin refresh: JELLYFIN_API_KEY not set" >&2 + exit 1 + fi + if jf_refresh_acquire_lock; then + trap 'rm -rf "$JF_HEAL_LOCK_DIR"' EXIT + jf_refresh_heal_after_scan + fi + exit 0 + fi + + if jf_refresh_is_test_event; then + echo "Jellyfin refresh: test event received, skipping" + exit 0 + fi + if [ -z "$JF_API_KEY" ]; then echo "Jellyfin refresh: JELLYFIN_API_KEY not set" >&2 exit 1 fi - if jf_refresh_acquire_lock; then - trap 'rm -rf "$JF_HEAL_LOCK_DIR"' EXIT - jf_refresh_heal_after_scan - fi - exit 0 -fi -if jf_refresh_is_test_event; then - echo "Jellyfin refresh: test event received, skipping" - exit 0 -fi + local tasks_json scan_state http_code script_path + tasks_json=$(jf_refresh_curl "http://${JF_HOST}:${JF_PORT}/ScheduledTasks" || echo "") + scan_state=$(jf_refresh_scan_state "$tasks_json") -if [ -z "$JF_API_KEY" ]; then - echo "Jellyfin refresh: JELLYFIN_API_KEY not set" >&2 - exit 1 -fi - -TASKS_JSON=$(jf_refresh_curl "http://${JF_HOST}:${JF_PORT}/ScheduledTasks" || echo "") -SCAN_STATE=$(jf_refresh_scan_state "$TASKS_JSON") - -if jf_refresh_scan_busy "$SCAN_STATE"; then - echo "Jellyfin refresh: scan already ${SCAN_STATE}, not cancelling" -else - HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 15 \ - -X POST \ - -H "$(jf_refresh_auth_header)" \ - "http://${JF_HOST}:${JF_PORT}/Library/Refresh" 2>/dev/null || echo "000") - - if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then - echo "Jellyfin refresh: triggered successfully (HTTP ${HTTP_CODE})" + if jf_refresh_scan_busy "$scan_state"; then + echo "Jellyfin refresh: scan already ${scan_state}, not cancelling" else - echo "Jellyfin refresh: failed (HTTP ${HTTP_CODE})" >&2 - exit 1 + http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 15 \ + -X POST \ + -H "$(jf_refresh_auth_header)" \ + "http://${JF_HOST}:${JF_PORT}/Library/Refresh" 2>/dev/null || echo "000") + + if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then + echo "Jellyfin refresh: triggered successfully (HTTP ${http_code})" + else + echo "Jellyfin refresh: failed (HTTP ${http_code})" >&2 + exit 1 + fi fi + + # Sonarr/Radarr wait on this process; heal in the background so we do not + # block their notification pipeline. nohup survives the parent exiting. + script_path="$0" + case "$script_path" in + /*) ;; + *) script_path="$(pwd)/$script_path" ;; + esac + + local -a _env_args=( + "JELLYFIN_HOST=$JF_HOST" + "JELLYFIN_PORT=$JF_PORT" + "JF_REFRESH_HEAL_POLL_SEC=$JF_REFRESH_HEAL_POLL_SEC" + "JF_REFRESH_HEAL_MAX_POLLS=$JF_REFRESH_HEAL_MAX_POLLS" + "JF_HEAL_LOCK_DIR=$JF_HEAL_LOCK_DIR" + ) + # Only pass API key via env when the mounted secret file is absent (never expose secret in ps/environ) + if [ "$_JF_KEY_FROM_SECRET" -eq 0 ]; then + _env_args+=("JELLYFIN_API_KEY=$JF_API_KEY") + fi + + nohup env "${_env_args[@]}" \ + "$script_path" --heal-only >/tmp/assemblrr-jf-heal.log 2>&1 & + exit 0 +} + +if [ "${JF_REFRESH_SOURCE_ONLY:-0}" != "1" ]; then + jf_refresh_main "$@" fi - -# Sonarr/Radarr wait on this process; heal in the background so we do not -# block their notification pipeline. nohup survives the parent exiting. -SCRIPT_PATH="$0" -case "$SCRIPT_PATH" in - /*) ;; - *) SCRIPT_PATH="$(pwd)/$SCRIPT_PATH" ;; -esac - -_env_args=( - "JELLYFIN_HOST=$JF_HOST" - "JELLYFIN_PORT=$JF_PORT" - "JF_REFRESH_HEAL_POLL_SEC=$JF_REFRESH_HEAL_POLL_SEC" - "JF_REFRESH_HEAL_MAX_POLLS=$JF_REFRESH_HEAL_MAX_POLLS" - "JF_HEAL_LOCK_DIR=$JF_HEAL_LOCK_DIR" -) -# Only pass API key via env when the mounted secret file is absent (never expose secret in ps/environ) -if [ "$_JF_KEY_FROM_SECRET" -eq 0 ]; then - _env_args+=("JELLYFIN_API_KEY=$JF_API_KEY") -fi - -nohup env "${_env_args[@]}" \ - "$SCRIPT_PATH" --heal-only >/tmp/assemblrr-jf-heal.log 2>&1 & -exit 0 diff --git a/scripts/media-purge-watch.sh b/scripts/media-purge-watch.sh index a0f4d66..b279a31 100755 --- a/scripts/media-purge-watch.sh +++ b/scripts/media-purge-watch.sh @@ -34,7 +34,7 @@ purge_watch_is_ignored() { local base="${p##*/}" case "$base" in ""|.|..|.DS_Store|Thumbs.db) return 0 ;; - *write_test*|*_write_test.txt|radarr_write_test.txt|sonarr_write_test.txt) return 0 ;; + *write_test*) return 0 ;; .nfs*|.tmp*|*.tmp|*.partial|*.!qB|*.part) return 0 ;; esac case "$p" in @@ -237,6 +237,7 @@ purge_watch_arr_hold() { # --- sourced by unit tests: stop here --- if [ "${PURGE_WATCH_SOURCE_ONLY:-0}" = "1" ]; then + # shellcheck disable=SC2317 return 0 2>/dev/null || exit 0 fi diff --git a/scripts/media-purge.sh b/scripts/media-purge.sh index 324f6fc..9d9e1ee 100755 --- a/scripts/media-purge.sh +++ b/scripts/media-purge.sh @@ -225,7 +225,7 @@ qbit_login() { } qbit_torrents_info() { - qbit_login + qbit_login "" curl -s --connect-timeout 10 -b "$QBIT_JAR" -H "Referer: ${QBIT_BASE}/" \ "${QBIT_BASE}/api/v2/torrents/info" 2>/dev/null || echo "[]" } @@ -233,7 +233,7 @@ qbit_torrents_info() { qbit_delete_hashes() { local hashes=("$@") [ "${#hashes[@]}" -gt 0 ] || return 0 - qbit_login + qbit_login "" local csv="" h for h in "${hashes[@]}"; do h=$(echo "$h" | tr 'A-F' 'a-f' | tr -d '[:space:]') @@ -949,6 +949,7 @@ run_series_purge() { # --- sourced by unit tests: stop here --- if [ "${MEDIA_PURGE_SOURCE_ONLY:-0}" = "1" ]; then + # shellcheck disable=SC2317 return 0 2>/dev/null || exit 0 fi diff --git a/scripts/vpn-watchdog.sh b/scripts/vpn-watchdog.sh index a4961cf..9ad630d 100755 --- a/scripts/vpn-watchdog.sh +++ b/scripts/vpn-watchdog.sh @@ -89,32 +89,17 @@ watchdog_should_restart_vpn() { return 0 } -if [ "${WATCHDOG_SOURCE_ONLY:-0}" = "1" ]; then - return 0 2>/dev/null || exit 0 -fi - -COOKIE_JAR=$(mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_cookie.XXXXXX") -LOGIN_BODY=$(mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_login.XXXXXX") +# Reuse a persistent session cookie jar across ticks so qBittorrent 5.3's 15-session LRU +# cap does not evict interactive WebUI tabs; only log in again if missing or rejected. +# shellcheck disable=SC2329 cleanup_watchdog() { - rm -f "${COOKIE_JAR:-}" "${LOGIN_BODY:-}" + rm -f "${LOGIN_BODY:-}" "${TORRENTS_BODY:-}" } -trap cleanup_watchdog EXIT INT TERM - -if [ ! -r "$AUTH_USERNAME_FILE" ] || [ ! -r "$AUTH_PASSWORD_FILE" ]; then - log_watchdog ERROR "Watchdog credentials not readable ($AUTH_USERNAME_FILE / $AUTH_PASSWORD_FILE)." - exit 1 -fi - -QBIT_USER=$(tr -d '\r\n' < "$AUTH_USERNAME_FILE") -QBIT_PASS=$(tr -d '\r\n' < "$AUTH_PASSWORD_FILE") - -if [ ! -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_started" ]; then - log_watchdog INFO "VPN Watchdog active. Monitoring qBittorrent at ${QBIT_HOST} (Interval: ${WATCHDOG_INTERVAL}s, Heartbeat: ${HEARTBEAT_INTERVAL}s, Cooldown: ${WATCHDOG_COOLDOWN_SEC}s)." - touch "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_started" -fi login_qbit() { local http_code + (umask 077; : > "$COOKIE_JAR") + chmod 600 "$COOKIE_JAR" 2>/dev/null || true http_code=$(curl -sS -o "$LOGIN_BODY" -w "%{http_code}" --connect-timeout 5 --max-time 15 \ -c "$COOKIE_JAR" \ -H "Referer: http://${QBIT_HOST}" \ @@ -129,6 +114,15 @@ login_qbit() { watchdog_cookie_has_sid "$COOKIE_JAR" } +qbit_watchdog_fetch() { + local endpoint="$1" + local out_file="$2" + curl -sS -o "$out_file" -w "%{http_code}" --connect-timeout 5 --max-time 15 \ + -b "$COOKIE_JAR" \ + -H "Referer: http://${QBIT_HOST}" \ + "http://${QBIT_HOST}${endpoint}" 2>/dev/null || echo "000" +} + qbit_watchdog_get() { local endpoint="$1" curl -sS --connect-timeout 5 --max-time 15 \ @@ -137,102 +131,142 @@ qbit_watchdog_get() { "http://${QBIT_HOST}${endpoint}" 2>/dev/null || true } -if ! login_qbit; then - log_watchdog ERROR "Failed to authenticate to qBittorrent API." - echo "auth_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" - exit 1 -fi +watchdog_main() { + COOKIE_JAR="${WATCHDOG_STATE_DIR%/}/qbit_watchdog_cookie.txt" + LOGIN_BODY=$(mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_login.XXXXXX") + TORRENTS_BODY=$(mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_torrents.XXXXXX") + trap cleanup_watchdog EXIT INT TERM -TORRENTS=$(qbit_watchdog_get "/api/v2/torrents/info") -if [ -z "$TORRENTS" ] || ! printf '%s' "$TORRENTS" | jq -e 'type == "array"' >/dev/null 2>&1; then - log_watchdog ERROR "Failed to fetch valid torrent list from qBittorrent API." - echo "api_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" - exit 1 -fi + if [ ! -r "$AUTH_USERNAME_FILE" ] || [ ! -r "$AUTH_PASSWORD_FILE" ]; then + log_watchdog ERROR "Watchdog credentials not readable ($AUTH_USERNAME_FILE / $AUTH_PASSWORD_FILE)." + exit 1 + fi -last_status="" -if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" ]; then - last_status=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status") -fi -if [ -n "$last_status" ] && [ "$last_status" != "success" ]; then - log_watchdog INFO "Watchdog recovered: Connection to qBittorrent API restored." -fi -echo "success" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" + QBIT_USER=$(tr -d '\r\n' < "$AUTH_USERNAME_FILE") + QBIT_PASS=$(tr -d '\r\n' < "$AUTH_PASSWORD_FILE") -num_torrents=$(printf '%s' "$TORRENTS" | jq 'length' 2>/dev/null || echo 0) -[[ "$num_torrents" =~ ^[0-9]+$ ]] || num_torrents=0 + if [ ! -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_started" ]; then + log_watchdog INFO "VPN Watchdog active. Monitoring qBittorrent at ${QBIT_HOST} (Interval: ${WATCHDOG_INTERVAL}s, Heartbeat: ${HEARTBEAT_INTERVAL}s, Cooldown: ${WATCHDOG_COOLDOWN_SEC}s)." + touch "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_started" + fi -current_time=$(date +%s) -last_heartbeat=0 -if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" ]; then - last_heartbeat=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" 2>/dev/null || echo 0) - [[ "$last_heartbeat" =~ ^[0-9]+$ ]] || last_heartbeat=0 -fi + if ! watchdog_cookie_has_sid "$COOKIE_JAR"; then + if ! login_qbit; then + log_watchdog ERROR "Failed to authenticate to qBittorrent API." + echo "auth_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" + exit 1 + fi + fi -time_diff=$((current_time - last_heartbeat)) -if [ "$time_diff" -ge "$HEARTBEAT_INTERVAL" ]; then - log_watchdog INFO "Heartbeat: Watchdog is active. Connected to qBittorrent. Monitoring ${num_torrents} torrent(s). VPN routing is healthy." - echo "$current_time" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" -fi + local torrents_http torrents + torrents_http=$(qbit_watchdog_fetch "/api/v2/torrents/info" "$TORRENTS_BODY") + torrents=$(cat "$TORRENTS_BODY" 2>/dev/null || true) + if [ "$torrents_http" = "403" ] || [ "$torrents_http" = "401" ] || \ + [ -z "$torrents" ] || ! printf '%s' "$torrents" | jq -e 'type == "array"' >/dev/null 2>&1; then + if ! login_qbit; then + log_watchdog ERROR "Failed to authenticate to qBittorrent API." + echo "auth_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" + exit 1 + fi + torrents_http=$(qbit_watchdog_fetch "/api/v2/torrents/info" "$TORRENTS_BODY") + torrents=$(cat "$TORRENTS_BODY" 2>/dev/null || true) + fi -if [ "$num_torrents" -eq 0 ]; then - log_debug "No torrents found to check. Watchdog check completed silently." + if [ -z "$torrents" ] || ! printf '%s' "$torrents" | jq -e 'type == "array"' >/dev/null 2>&1; then + log_watchdog ERROR "Failed to fetch valid torrent list from qBittorrent API (HTTP ${torrents_http})." + echo "api_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" + exit 1 + fi + + local last_status="" + if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" ]; then + last_status=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status") + fi + if [ -n "$last_status" ] && [ "$last_status" != "success" ]; then + log_watchdog INFO "Watchdog recovered: Connection to qBittorrent API restored." + fi + echo "success" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" + + local num_torrents current_time last_heartbeat time_diff + num_torrents=$(printf '%s' "$torrents" | jq 'length' 2>/dev/null || echo 0) + [[ "$num_torrents" =~ ^[0-9]+$ ]] || num_torrents=0 + + current_time=$(date +%s) + last_heartbeat=0 + if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" ]; then + last_heartbeat=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" 2>/dev/null || echo 0) + [[ "$last_heartbeat" =~ ^[0-9]+$ ]] || last_heartbeat=0 + fi + + time_diff=$((current_time - last_heartbeat)) + if [ "$time_diff" -ge "$HEARTBEAT_INTERVAL" ]; then + log_watchdog INFO "Heartbeat: Watchdog is active. Connected to qBittorrent. Monitoring ${num_torrents} torrent(s). VPN routing is healthy." + echo "$current_time" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_heartbeat" + fi + + if [ "$num_torrents" -eq 0 ]; then + log_debug "No torrents found to check. Watchdog check completed silently." + exit 0 + fi + + local -a DETECTED_TORRENTS=() + local working_count=0 hash name properties trackers is_broken is_working + + while IFS=$'\t' read -r hash name; do + [ -z "$hash" ] && continue + + properties=$(qbit_watchdog_get "/api/v2/torrents/properties?hash=${hash}") + trackers=$(qbit_watchdog_get "/api/v2/torrents/trackers?hash=${hash}") + + read -r is_broken is_working < <(watchdog_classify_torrent "$properties" "$trackers") + if [ "$is_working" -eq 1 ]; then + working_count=$((working_count + 1)) + fi + if [ "$is_broken" -eq 1 ]; then + DETECTED_TORRENTS+=("$name") + fi + done < <(printf '%s' "$torrents" | jq -r '.[] | [(.hash // ""), (.name // "")] | @tsv' 2>/dev/null || true) + + local broken_count=${#DETECTED_TORRENTS[@]} + if [ "$broken_count" -gt 0 ]; then + local last_restart=0 gluetun_status remaining torrent_name + if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" ]; then + last_restart=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" 2>/dev/null || echo 0) + [[ "$last_restart" =~ ^[0-9]+$ ]] || last_restart=0 + fi + + if [ "$working_count" -gt 0 ]; then + log_debug "Ignoring ${broken_count} stalled torrent(s): ${working_count} torrent(s) have active peers/trackers (not a global VPN failure)." + exit 0 + fi + + # Optional: check Gluetun's local control endpoint if open without blocking on auth + gluetun_status=$(curl -sS --connect-timeout 2 --max-time 5 "${GLUETUN_CONTROL_URL}/v1/openvpn/status" 2>/dev/null | jq -r '.status // empty' 2>/dev/null || true) + if [ -n "$gluetun_status" ] && [ "$gluetun_status" != "running" ]; then + log_watchdog DETECTED "Gluetun reported VPN status '${gluetun_status}'." + fi + + if ! watchdog_should_restart_vpn "$broken_count" "$working_count" "$current_time" "$last_restart" "$WATCHDOG_COOLDOWN_SEC"; then + remaining=$((WATCHDOG_COOLDOWN_SEC - (current_time - last_restart))) + log_watchdog INFO "VPN restart cooldown active (${remaining}s remaining); skipping restart for ${broken_count} stalled torrent(s)." + exit 0 + fi + + log_watchdog DETECTED "VPN routing failure! Torrents with broken-network symptoms found:" + for torrent_name in "${DETECTED_TORRENTS[@]}"; do + log_watchdog DETECTED "$torrent_name" + done + log_watchdog ACTION "Triggering Gluetun restart to fetch a new VPN IP..." + echo "routing_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" + echo "$current_time" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" + docker restart gluetun + exit 1 + fi + + log_debug "Watchdog check completed successfully. Monitored ${num_torrents} torrents. All healthy." exit 0 +} + +if [ "${WATCHDOG_SOURCE_ONLY:-0}" != "1" ]; then + watchdog_main "$@" fi - -DETECTED_TORRENTS=() -working_count=0 - -while IFS=$'\t' read -r hash name; do - [ -z "$hash" ] && continue - - PROPERTIES=$(qbit_watchdog_get "/api/v2/torrents/properties?hash=${hash}") - TRACKERS=$(qbit_watchdog_get "/api/v2/torrents/trackers?hash=${hash}") - - read -r is_broken is_working < <(watchdog_classify_torrent "$PROPERTIES" "$TRACKERS") - if [ "$is_working" -eq 1 ]; then - working_count=$((working_count + 1)) - fi - if [ "$is_broken" -eq 1 ]; then - DETECTED_TORRENTS+=("$name") - fi -done < <(printf '%s' "$TORRENTS" | jq -r '.[] | [(.hash // ""), (.name // "")] | @tsv' 2>/dev/null || true) - -broken_count=${#DETECTED_TORRENTS[@]} -if [ "$broken_count" -gt 0 ]; then - last_restart=0 - if [ -f "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" ]; then - last_restart=$(cat "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" 2>/dev/null || echo 0) - [[ "$last_restart" =~ ^[0-9]+$ ]] || last_restart=0 - fi - - if [ "$working_count" -gt 0 ]; then - log_debug "Ignoring ${broken_count} stalled torrent(s): ${working_count} torrent(s) have active peers/trackers (not a global VPN failure)." - exit 0 - fi - - # Optional: check Gluetun's local control endpoint if open without blocking on auth - gluetun_status=$(curl -sS --connect-timeout 2 --max-time 5 "${GLUETUN_CONTROL_URL}/v1/openvpn/status" 2>/dev/null | jq -r '.status // empty' 2>/dev/null || true) - if [ -n "$gluetun_status" ] && [ "$gluetun_status" != "running" ]; then - log_watchdog DETECTED "Gluetun reported VPN status '${gluetun_status}'." - fi - - if ! watchdog_should_restart_vpn "$broken_count" "$working_count" "$current_time" "$last_restart" "$WATCHDOG_COOLDOWN_SEC"; then - remaining=$((WATCHDOG_COOLDOWN_SEC - (current_time - last_restart))) - log_watchdog INFO "VPN restart cooldown active (${remaining}s remaining); skipping restart for ${broken_count} stalled torrent(s)." - exit 0 - fi - - log_watchdog DETECTED "VPN routing failure! Torrents with broken-network symptoms found:" - for torrent_name in "${DETECTED_TORRENTS[@]}"; do - log_watchdog DETECTED "$torrent_name" - done - log_watchdog ACTION "Triggering Gluetun restart to fetch a new VPN IP..." - echo "routing_failed" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_status" - echo "$current_time" > "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_last_restart" - docker restart gluetun - exit 1 -fi - -log_debug "Watchdog check completed successfully. Monitored ${num_torrents} torrents. All healthy." -exit 0 diff --git a/tests/helpers.sh b/tests/helpers.sh index f9e2f75..b2cd9cb 100644 --- a/tests/helpers.sh +++ b/tests/helpers.sh @@ -122,6 +122,7 @@ assert_false() { # core.sh log_error exits; unit tests need a non-fatal stub stub_log_error_no_exit() { + # shellcheck disable=SC2329 log_error() { echo -e "${RED:-}$1${NC:-}" >&2 return 1 diff --git a/tests/integration/watchdog_stall.sh b/tests/integration/watchdog_stall.sh index 2f901b8..2c6574e 100755 --- a/tests/integration/watchdog_stall.sh +++ b/tests/integration/watchdog_stall.sh @@ -41,6 +41,7 @@ EOF require_live_opt_in +# shellcheck disable=SC2329 cleanup() { [ "$CLEANED_UP" -eq 1 ] && return 0 CLEANED_UP=1 @@ -155,7 +156,7 @@ set +e watchdog_out=$(bash "$watchdog" 2>&1) watchdog_rc=$? set -e -echo "$watchdog_out" | sed 's/^/ /' +printf ' %s\n' "${watchdog_out//$'\n'/$'\n '}" echo "" echo ">>> Assertions <<<" diff --git a/tests/unit/test_compose.sh b/tests/unit/test_compose.sh index 0414bbc..5615606 100755 --- a/tests/unit/test_compose.sh +++ b/tests/unit/test_compose.sh @@ -19,7 +19,7 @@ touch "$tmp/compose/base.yaml" "$tmp/compose/vpn.yaml" "$tmp/compose/direct-acce "$tmp/compose/vuetorrent.yaml" "$tmp/compose/qui.yaml" "$tmp/compose/gpu-intel.yaml" "$tmp/compose/gpu-nvidia.yaml" \ "$tmp/compose/byparr.yaml" "$tmp/compose/usenet.yaml" -QBIT_UI= VUETORRENT_ENABLED=n GPU_TRANSCODING=none BYPARR_ENABLED=n USENET_ENABLED=n +QBIT_UI='' VUETORRENT_ENABLED=n GPU_TRANSCODING=none BYPARR_ENABLED=n USENET_ENABLED=n test_suite "build_compose_args (VPN enabled)" build_compose_args "$tmp" "y" @@ -56,7 +56,7 @@ build_compose_args "$tmp" "y" assert_contains "${COMPOSE_ARGS[*]}" "-f $tmp/compose/qui.yaml" "includes qui.yaml when QBIT_UI=qui" assert_not_contains "${COMPOSE_ARGS[*]}" "vuetorrent.yaml" "excludes vuetorrent.yaml when QBIT_UI=qui" -QBIT_UI= VUETORRENT_ENABLED=n GPU_TRANSCODING=none BYPARR_ENABLED=n USENET_ENABLED=n +QBIT_UI='' VUETORRENT_ENABLED=n GPU_TRANSCODING=none BYPARR_ENABLED=n USENET_ENABLED=n rm -f "$tmp/compose/custom.yaml" test_suite "build_compose_args (case-insensitive VPN flag)" diff --git a/tests/unit/test_config_edit.sh b/tests/unit/test_config_edit.sh index 18a2e3b..62990fc 100755 --- a/tests/unit/test_config_edit.sh +++ b/tests/unit/test_config_edit.sh @@ -101,6 +101,7 @@ assert_contains "$profile_fn" "configure_recyclarr" "resyncs Recyclarr so WEB pa test_suite "vpn edit chmods only vpn secret files" vpn_fn=$(sed -n '/^_config_edit_vpn()/,/^}/p' "$REPO_ROOT/lib/config_edit.sh") +# shellcheck disable=SC2016 assert_not_contains "$vpn_fn" 'chmod 600 "$secrets_dir"/*.txt' "vpn edit does not chmod every secret" assert_contains "$vpn_fn" "openvpn_user.txt" "vpn chmod names openvpn_user" assert_contains "$vpn_fn" "wireguard_private_key.txt" "vpn chmod names wireguard key" @@ -108,6 +109,7 @@ assert_contains "$vpn_fn" "wireguard_private_key.txt" "vpn chmod names wireguard test_suite "auth edit writes secrets only after every UI succeeds" auth_fn=$(sed -n '/^_config_edit_auth()/,/^}/p' "$REPO_ROOT/lib/config_edit.sh") fail_at=$(echo "$auth_fn" | grep -n 'fail" -ne 0' | head -1 | cut -d: -f1) +# shellcheck disable=SC2016 write_at=$(echo "$auth_fn" | grep -n 'echo -n "$AUTH_PASSWORD"' | head -1 | cut -d: -f1) assert_true "fail check exists" "[ -n \"$fail_at\" ]" assert_true "password write exists" "[ -n \"$write_at\" ]" @@ -123,6 +125,7 @@ assert_contains "$(grep 'config apply' "$REPO_ROOT/README.md" || true)" "config test_suite "uninstall --force is quiet" un=$(sed -n '/^uninstall_app()/,/^}/p' "$REPO_ROOT/bin/cli.sh") +# shellcheck disable=SC2016 assert_contains "$un" 'if [ "$force" = false ]; then' "inventory only when not --force" assert_not_contains "$un" "Stopping all services" "no step-by-step stop line" assert_not_contains "$un" "Removing config at" "no Removing-config play-by-play" @@ -132,15 +135,21 @@ assert_contains "$un" "Config removed:" "removed config is labeled removed" assert_contains "$un" "Media removed:" "removed media is labeled removed" assert_contains "$un" "Config kept:" "kept config is labeled kept" assert_contains "$un" "Media kept:" "kept media is labeled kept" +# shellcheck disable=SC2016 assert_not_contains "$un" 'echo " Config: $INSTALL_DIR"' "does not print a status-style Config path" +# shellcheck disable=SC2016 assert_not_contains "$un" 'echo " Media: $MEDIA_DIRECTORY"' "does not print a status-style Media path" test_suite "config show survives missing VPN_TYPE/TZ" cli="$REPO_ROOT/bin/cli.sh" +# shellcheck disable=SC2016 assert_contains "$(grep -n 'VPN_TYPE=' "$cli" | head -5)" 'VPN_TYPE="${VPN_TYPE:-openvpn}"' "CLI defaults VPN_TYPE" +# shellcheck disable=SC2016 assert_contains "$(grep -n 'TZ=' "$cli" | head -5)" 'TZ="${TZ:-UTC}"' "CLI defaults TZ" show_fn=$(sed -n '/^show_config()/,/^}/p' "$cli") +# shellcheck disable=SC2016 assert_contains "$show_fn" '${VPN_TYPE:-openvpn}' "show_config defaults VPN type" +# shellcheck disable=SC2016 assert_contains "$show_fn" '${TZ:-UTC}' "show_config defaults timezone" # Reproduce the old set -u crash: print those fields with vars unset. diff --git a/tests/unit/test_core.sh b/tests/unit/test_core.sh index f880eab..2b6a205 100755 --- a/tests/unit/test_core.sh +++ b/tests/unit/test_core.sh @@ -49,6 +49,7 @@ assert_eq "3" "$rc" "propagates exit status" # --- expand_path --- test_suite "expand_path" +# shellcheck disable=SC2088 assert_eq "$HOME/foo" "$(expand_path "~/foo")" "expands leading tilde" assert_eq "/abs/path" "$(expand_path "/abs/path")" "leaves absolute paths alone" assert_eq "relative/path" "$(expand_path "relative/path")" "leaves relative paths alone" diff --git a/tests/unit/test_env_example.sh b/tests/unit/test_env_example.sh index 7462580..74939fb 100755 --- a/tests/unit/test_env_example.sh +++ b/tests/unit/test_env_example.sh @@ -81,8 +81,8 @@ trap 'rm -f "$tmp"' EXIT export PUID=1000 PGID=1000 \ MEDIA_DIRECTORY=/data/media INSTALL_DIRECTORY=/opt/assemblrr \ MEDIA_SERVICE=jellyfin TZ=UTC \ - VPN_ENABLED=n VPN_SERVICE= VPN_TYPE=openvpn \ - WIREGUARD_ADDRESSES= \ + VPN_ENABLED=n VPN_SERVICE='' VPN_TYPE=openvpn \ + WIREGUARD_ADDRESSES='' \ PORT_FORWARD_ONLY=off VPN_PORT_FORWARDING=off \ QBIT_UI=vuetorrent VUETORRENT_ENABLED=y GPU_TRANSCODING=none \ BYPARR_ENABLED=n USENET_ENABLED=n \ diff --git a/tests/unit/test_media_purge_match.sh b/tests/unit/test_media_purge_match.sh index a5ce904..c8355ea 100755 --- a/tests/unit/test_media_purge_match.sh +++ b/tests/unit/test_media_purge_match.sh @@ -167,6 +167,7 @@ assert_false "The Horizon usenet complete dir removed" "[ -d '$MEDIA_ROOT/usenet assert_true "Horizon Chapter Two leftover left alone" "[ -d '$MEDIA_ROOT/torrents/movies/Horizon Chapter Two 2015 1080p' ]" _mp_src=$(cat "$REPO_ROOT/scripts/media-purge.sh") +# shellcheck disable=SC2016 assert_not_contains "$_mp_src" 'exec "$0"' "--tmdb / --tvdb do not re-exec and drop --dry-run" assert_contains "$_mp_src" 'Authorization: MediaBrowser' "notify_jellyfin uses MediaBrowser header" assert_not_contains "$_mp_src" 'X-Emby-Token' "notify_jellyfin does not use legacy X-Emby-Token" diff --git a/tests/unit/test_overlays.sh b/tests/unit/test_overlays.sh index 719f4ec..d52ae17 100755 --- a/tests/unit/test_overlays.sh +++ b/tests/unit/test_overlays.sh @@ -39,10 +39,10 @@ assert_contains "$cat_on" "byparr|Byparr (solver)|||internal" "lists byparr when assert_contains "$cat_on" "gluetun|Gluetun (VPN)|||internal" "lists gluetun when VPN_ENABLED=y" test_suite "qbit_ui_mode & qui payload" -assert_eq "vuetorrent" "$(QBIT_UI= VUETORRENT_ENABLED=y qbit_ui_mode)" "legacy VUETORRENT_ENABLED=y -> vuetorrent" +assert_eq "vuetorrent" "$(QBIT_UI='' VUETORRENT_ENABLED=y qbit_ui_mode)" "legacy VUETORRENT_ENABLED=y -> vuetorrent" assert_eq "qui" "$(QBIT_UI=qui VUETORRENT_ENABLED=y qbit_ui_mode)" "explicit QBIT_UI=qui overrides legacy flag" assert_eq "stock" "$(QBIT_UI=stock VUETORRENT_ENABLED=y qbit_ui_mode)" "explicit QBIT_UI=stock" -assert_eq "stock" "$(QBIT_UI= VUETORRENT_ENABLED=n qbit_ui_mode)" "empty QBIT_UI + n -> stock" +assert_eq "stock" "$(QBIT_UI='' VUETORRENT_ENABLED=n qbit_ui_mode)" "empty QBIT_UI + n -> stock" qui_json=$(qui_build_instance_payload "http://gluetun:8081" "alice" 'p"q') assert_eq "http://gluetun:8081" "$(printf '%s' "$qui_json" | jq -r '.host')" "qui payload sets host" @@ -76,14 +76,14 @@ assert_not_contains "${COMPOSE_ARGS[*]}" "gpu-intel.yaml" "intel overlay exclude test_suite "configure_qbit_ui defaults & picker selection" # shellcheck source=/dev/null source "$REPO_ROOT/lib/prompts.sh" -SETUP_MODE=express QBIT_UI= VUETORRENT_ENABLED= configure_qbit_ui +SETUP_MODE=express QBIT_UI='' VUETORRENT_ENABLED='' configure_qbit_ui assert_eq "vuetorrent" "${qbit_ui:-}" "express mode defaults qbit_ui=vuetorrent" assert_eq "y" "${vuetorrent_enabled:-}" "express mode syncs vuetorrent_enabled=y" # Non-TTY fallback preserves selection cleanly # shellcheck source=/dev/null source "$REPO_ROOT/lib/fzf-tui.sh" -SETUP_MODE=manual QBIT_UI= VUETORRENT_ENABLED= configure_qbit_ui <<< "qui" +SETUP_MODE=manual QBIT_UI='' VUETORRENT_ENABLED='' configure_qbit_ui <<< "qui" assert_eq "qui" "${qbit_ui:-}" "manual picker selects qui" assert_eq "n" "${vuetorrent_enabled:-}" "selecting qui clears vuetorrent_enabled" @@ -97,9 +97,9 @@ log_step() { :; } log_step_fail() { echo "fail: $1" >&2; } mkdir -p "$tmp/secrets" -assert_eq "fallback" "$(INSTALL_DIR="$tmp" QUI_PASSWORD= AUTH_PASSWORD=fallback _qui_login_password)" "falls back to AUTH_PASSWORD when no qui_password.txt" +assert_eq "fallback" "$(INSTALL_DIR="$tmp" QUI_PASSWORD='' AUTH_PASSWORD=fallback _qui_login_password)" "falls back to AUTH_PASSWORD when no qui_password.txt" printf '%s' 'from-secret-file' > "$tmp/secrets/qui_password.txt" -assert_eq "from-secret-file" "$(INSTALL_DIR="$tmp" QUI_PASSWORD= AUTH_PASSWORD=fallback _qui_login_password)" "prefers secrets/qui_password.txt over AUTH_PASSWORD" +assert_eq "from-secret-file" "$(INSTALL_DIR="$tmp" QUI_PASSWORD='' AUTH_PASSWORD=fallback _qui_login_password)" "prefers secrets/qui_password.txt over AUTH_PASSWORD" assert_eq "from-env" "$(INSTALL_DIR="$tmp" QUI_PASSWORD=from-env AUTH_PASSWORD=fallback _qui_login_password)" "prefers QUI_PASSWORD env over secret file" rm -f "$tmp/secrets/qui_password.txt" diff --git a/tests/unit/test_prepare_install_dirs.sh b/tests/unit/test_prepare_install_dirs.sh index 77dfd75..49d6fdf 100755 --- a/tests/unit/test_prepare_install_dirs.sh +++ b/tests/unit/test_prepare_install_dirs.sh @@ -50,6 +50,7 @@ assert_true "sibling exists" "[ -d \"$tmp/config/__test_sibling\" ]" test_suite "ensure_owned prefers Docker chown before sudo" mkdir -p "$tmp/root_owned_sim" ( + # shellcheck disable=SC2032 chown() { return 1; } run_docker() { printf '%s\n' "$*" > "$tmp/docker_called" diff --git a/tests/unit/test_quality.sh b/tests/unit/test_quality.sh index 7d62f52..069d450 100755 --- a/tests/unit/test_quality.sh +++ b/tests/unit/test_quality.sh @@ -134,14 +134,16 @@ assert_not_contains "$recyc" "grep -vE" "does not drop HD or WEB movie packs" assert_contains "$(cat "$REPO_ROOT/templates/recyclarr/recyclarr.yml")" "radarr-1080p-bluray.yml" "root still includes 1080p Bluray + WEB" assert_contains "$(cat "$REPO_ROOT/templates/recyclarr/recyclarr.yml")" "radarr-1080p-web.yml" "root still includes 1080p WEB" -test_suite "sonarr and seerr follow the same flag" +test_suite "sonarr and seerr follow the tier profile while routing single-instance requests" assert_contains "$(sed -n '/^lookup_sonarr_profile()/,/^}/p' "$REPO_ROOT/lib/arr_quality.sh")" \ "lookup_arr_quality_profile" "sonarr uses shared lookup" assert_not_contains "$(cat "$REPO_ROOT/lib/arr_quality.sh")" \ "movies 4K choice does not change this" "old TV hardcode is gone" -sonarr_connect=$(grep -n 'seerr_connect_service "sonarr"' -A2 "$REPO_ROOT/lib/seerr.sh") -assert_not_contains "$sonarr_connect" '"false"' "seerr sonarr is4k is not hardcoded false" -assert_contains "$(cat "$REPO_ROOT/lib/seerr.sh")" 'is_4k=$(quality_seerr_is_4k)' \ - "seerr derives is4k from the tier" +seerr_src=$(cat "$REPO_ROOT/lib/seerr.sh") +assert_contains "$seerr_src" 'is_4k="false"' \ + "single-instance Radarr/Sonarr registers as default non-4K server in Seerr" +# shellcheck disable=SC2016 +assert_not_contains "$seerr_src" 'is_4k=$(quality_seerr_is_4k)' \ + "seerr does not lock sole Radarr/Sonarr behind dual-server is4k flag" test_summary diff --git a/tests/unit/test_setup_restore.sh b/tests/unit/test_setup_restore.sh index 86d01ef..9964826 100755 --- a/tests/unit/test_setup_restore.sh +++ b/tests/unit/test_setup_restore.sh @@ -31,10 +31,12 @@ assert_true "main calls restore_from_backup_wizard" "grep -q 'restore_from_backu mock_archive="$tmp/mock-backup.tar.gz" mock_src="$tmp/mock_src" mkdir -p "$mock_src/config/jellyfin" "$mock_src/secrets" "$mock_src/compose" -echo "INSTALL_DIRECTORY=\"/opt/test-assemblrr\"" > "$mock_src/.env" -echo "MEDIA_DIRECTORY=\"/data/test-media\"" >> "$mock_src/.env" -echo "MEDIA_SERVICE=\"jellyfin\"" >> "$mock_src/.env" -echo "VPN_ENABLED=\"n\"" >> "$mock_src/.env" +{ + echo "INSTALL_DIRECTORY=\"/opt/test-assemblrr\"" + echo "MEDIA_DIRECTORY=\"/data/test-media\"" + echo "MEDIA_SERVICE=\"jellyfin\"" + echo "VPN_ENABLED=\"n\"" +} > "$mock_src/.env" tar -czf "$mock_archive" -C "$mock_src" . mock_dest="$tmp/mock_dest" diff --git a/tests/unit/test_usenet.sh b/tests/unit/test_usenet.sh index 8004942..a7188b2 100755 --- a/tests/unit/test_usenet.sh +++ b/tests/unit/test_usenet.sh @@ -54,6 +54,7 @@ assert_eq "sabkey-2" "$(echo "$schema_json" | jq -r '.fields[] | select(.name==" assert_eq "false" "$(echo "$schema_json" | jq -r '.fields[] | select(.name=="useSsl") | .value')" "disables internal TLS on bridge network" USENET_ENABLED=y +# shellcheck disable=SC2016 assert_success "0-arg arr_configure_sabnzbd handles missing API keys cleanly" \ env -u RADARR_API_KEY -u SONARR_API_KEY bash -c 'source "$1/lib/core.sh"; source "$1/lib/api.sh"; source "$1/lib/usenet.sh"; USENET_ENABLED=y; INSTALL_DIR="$2"; arr_configure_sabnzbd' _ "$REPO_ROOT" "$tmp/install" diff --git a/tests/unit/test_vpn_watchdog.sh b/tests/unit/test_vpn_watchdog.sh index 466d3bd..d3292e8 100755 --- a/tests/unit/test_vpn_watchdog.sh +++ b/tests/unit/test_vpn_watchdog.sh @@ -35,6 +35,11 @@ assert_success "cooldown elapsed allows restart" watchdog_should_restart_vpn 2 0 _wd_src=$(cat "$REPO_ROOT/scripts/vpn-watchdog.sh") assert_not_contains "$_wd_src" 'api_get()' "renamed api_get to avoid collision" assert_contains "$_wd_src" 'WATCHDOG_COOLDOWN_SEC' "cooldown wired" +assert_contains "$_wd_src" 'qbit_watchdog_cookie.txt' "uses persistent cookie jar across ticks" +# shellcheck disable=SC2016 +assert_not_contains "$_wd_src" 'mktemp "${WATCHDOG_STATE_DIR%/}/qbit_watchdog_cookie' "does not allocate a fresh cookie jar every tick" +# shellcheck disable=SC2016 +assert_contains "$_wd_src" 'if ! watchdog_cookie_has_sid "$COOKIE_JAR"' "reuses existing SID cookie before logging in" _jar=$(mktemp) printf '# Netscape HTTP Cookie File\n#HttpOnly_gluetun\tFALSE\t/\tFALSE\t1795288207\tQBT_SID_8081\tabc123\n' > "$_jar"