#!/bin/bash # ----------------------------------------------------------------------------------------------- # --------------------------------- Sonarr Cleanup Script -------------------------------------- # ----------------------------------------------------------------------------------------------- # Removes orphaned TV episode files from the library that Sonarr no longer tracks. # Uses the Sonarr API to build a complete list of tracked episode file paths then compares # against what exists on disk — anything not tracked and older than SONARR_ORPHAN_AGE # days is considered an orphan and deleted. # # File classification: # TRACKED — Sonarr API knows about this exact file path → leave it alone # PROTECTED — matches SONARR_PROTECTED_PATTERNS → never delete (artwork, subtitles, .nfo) # ORPHAN — video file, not tracked, older than SONARR_ORPHAN_AGE days → delete # JUNK — not a video extension, not protected → delete regardless of age # RECENT — not tracked, under SONARR_ORPHAN_AGE days old → skip (may be mid-import) # # Why protected patterns matter: # Sonarr generates show artwork (*.jpg), metadata (*.nfo) and manages subtitles # (*.srt, *.sub, *.ass) but does not include these in its tracked file API response. # Without protection these would be classified as orphans and deleted. # # HOST1 Sonarr manages Tv_Shows. HOST2 Sonarr manages Anime_Shows. # detect_hosts() selects the correct URL, API key, and root path at runtime. # All configuration in Master.conf under Arr Cleanup section. # Supports --dry-run to preview what would be deleted without making changes. # ----------------------------------------------------------------------------------------------- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/../Master.conf" source "$SCRIPT_DIR/../common.sh" parse_args "$@" # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_GEAR Setup ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━ $ICON_GEAR Setup ━━━" if [[ "$EUID" -ne 0 ]]; then error "Must be run as root" exit 1 fi success "Running as root" if ! command -v curl >/dev/null 2>&1; then error "curl not found — required for Sonarr API calls" exit 1 fi if ! command -v jq >/dev/null 2>&1; then error "jq not found — required for JSON parsing" notify "Sonarr cleanup failed on $(hostname) — jq not installed" "Sonarr Cleanup" "warning" exit 1 fi # Select correct Sonarr instance based on which server is running this script detect_hosts if [[ "$LOCAL_SERVER_NAME" == "$HOST1" ]]; then SONARR_URL="$HOST1_SONARR_URL" SONARR_API_KEY="$HOST1_SONARR_API_KEY" SONARR_TV_ROOT="$HOST1_SONARR_TV_ROOT" else SONARR_URL="$HOST2_SONARR_URL" SONARR_API_KEY="$HOST2_SONARR_API_KEY" SONARR_TV_ROOT="$HOST2_SONARR_TV_ROOT" fi # Load path map for this host declare -A PATH_MAP if [[ "$LOCAL_SERVER_NAME" == "$HOST1" ]]; then for key in "${!HOST1_SONARR_PATH_MAP[@]}"; do PATH_MAP["$key"]="${HOST1_SONARR_PATH_MAP[$key]}" done else for key in "${!HOST2_SONARR_PATH_MAP[@]}"; do PATH_MAP["$key"]="${HOST2_SONARR_PATH_MAP[$key]}" done fi info "Sonarr instance: $LOCAL_SERVER_NAME → $SONARR_URL" info "TV root: $SONARR_TV_ROOT" require_var SONARR_URL require_var SONARR_API_KEY require_var SONARR_TV_ROOT if [[ ! -d "$SONARR_TV_ROOT" ]]; then error "TV root not found: $SONARR_TV_ROOT" notify "Sonarr cleanup failed on $(hostname) — TV root not found: $SONARR_TV_ROOT" "Sonarr Cleanup" "warning" exit 1 fi acquire_lock "wait" success "Config validated" # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_SUMMARY Status ━━━ # ----------------------------------------------------------------------------------------------- if [[ "$SHOW_STATUS" == true ]]; then echo "" echo "━━━━━ $ICON_SUMMARY STATUS ━━━━━" echo "$ICON_GEAR Sonarr URL: $SONARR_URL" echo "$ICON_GEAR TV root: $SONARR_TV_ROOT" echo "$ICON_TIME Orphan age: ${SONARR_ORPHAN_AGE} days" echo "$ICON_GEAR Extensions: ${SONARR_EXTENSIONS[*]}" echo "$ICON_GEAR Protected patterns: ${SONARR_PROTECTED_PATTERNS[*]}" echo "$ICON_GEAR Dry Run: $DRY_RUN" echo "━━━━━━━━━━━━━━━━━━━━━━━" exit 0 fi [[ "$DRY_RUN" == true ]] && warn "DRY RUN — no files will be deleted" # ----------------------------------------------------------------------------------------------- # HELPERS # ----------------------------------------------------------------------------------------------- sonarr_api() { local endpoint="$1" local response http_code body response=$(curl -sf \ --max-time 30 \ -H "X-Api-Key: $SONARR_API_KEY" \ -w "\n%{http_code}" \ "${SONARR_URL}/api/v3/${endpoint}" 2>/dev/null) http_code=$(echo "$response" | tail -1) body=$(echo "$response" | head -n -1) if [[ "$http_code" != "200" ]]; then error "Sonarr API returned HTTP $http_code for endpoint: $endpoint" return 1 fi echo "$body" } is_video_file() { local ext="${1##*.}" ext="${ext,,}" for valid_ext in "${SONARR_EXTENSIONS[@]}"; do [[ "$ext" == "$valid_ext" ]] && return 0 done return 1 } is_protected_file() { local filename filename=$(basename "$1") for pattern in "${SONARR_PROTECTED_PATTERNS[@]}"; do # shellcheck disable=SC2254 case "$filename" in $pattern) return 0 ;; esac done return 1 } # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_SYNC Fetching Sonarr Tracked Files ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━ $ICON_SYNC Fetching Sonarr Tracked Files ━━━" check_api "$SONARR_URL" "Sonarr" || { notify "Sonarr cleanup aborted on $(hostname) — API unreachable" "Sonarr Cleanup" "warning" exit 1 } info "Querying Sonarr API: $SONARR_URL" EPISODEFILE_RESPONSE=$(sonarr_api "episodefile") || { error "Failed to fetch episode files from Sonarr — check URL and API key" notify "Sonarr cleanup failed on $(hostname) — API unreachable" "Sonarr Cleanup" "warning" exit 1 } TMP_DIR="/tmp/sonarr_cleanup_$$" mkdir -p "$TMP_DIR" trap "rm -rf $TMP_DIR" EXIT TRACKED_FILE="$TMP_DIR/tracked_paths.txt" while IFS= read -r api_path; do [[ -z "$api_path" ]] && continue translate_path "$api_path" PATH_MAP >> "$TRACKED_FILE" done < <(echo "$EPISODEFILE_RESPONSE" | jq -r '.[].path' 2>/dev/null) sort -u "$TRACKED_FILE" -o "$TRACKED_FILE" TRACKED_COUNT=$(wc -l < "$TRACKED_FILE") success "Sonarr tracks $TRACKED_COUNT episode files" if [[ "$TRACKED_COUNT" -eq 0 ]]; then warn "No tracked files returned — Sonarr may not have scanned yet or library is empty" warn "Aborting to prevent mass deletion" notify "Sonarr cleanup aborted on $(hostname) — no tracked files returned from API" "Sonarr Cleanup" "warning" exit 1 fi # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_CLEAN Scanning TV Root ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━ $ICON_CLEAN Scanning TV Root ━━━" info "Root: $SONARR_TV_ROOT" info "Orphan age: ${SONARR_ORPHAN_AGE} days" info "Protected: ${SONARR_PROTECTED_PATTERNS[*]}" echo "" START=$(date +%s) ORPHAN_COUNT=0 JUNK_COUNT=0 RECENT_COUNT=0 PROTECTED_COUNT=0 ORPHAN_BYTES=0 JUNK_BYTES=0 AGE_SECONDS=$(( SONARR_ORPHAN_AGE * 86400 )) NOW=$(date +%s) while IFS= read -r filepath; do [[ -z "$filepath" ]] && continue if grep -qF "$filepath" "$TRACKED_FILE" 2>/dev/null; then log "TRACKED: $filepath" continue fi if is_protected_file "$filepath"; then log "PROTECTED: $filepath" ((PROTECTED_COUNT++)) continue fi FILE_SIZE=$(stat -c%s "$filepath" 2>/dev/null || echo 0) if is_video_file "$filepath"; then FILE_MTIME=$(stat -c %Y "$filepath" 2>/dev/null || echo 0) FILE_AGE=$(( NOW - FILE_MTIME )) if [[ "$FILE_AGE" -lt "$AGE_SECONDS" ]]; then log "RECENT (skipping): $filepath" ((RECENT_COUNT++)) continue fi warn "$ICON_TRASH ORPHAN: $filepath" if [[ "$DRY_RUN" == false ]]; then rm -f "$filepath" && { ((ORPHAN_COUNT++)) ORPHAN_BYTES=$((ORPHAN_BYTES + FILE_SIZE)) } || error "Failed to delete: $filepath" else ((ORPHAN_COUNT++)) ORPHAN_BYTES=$((ORPHAN_BYTES + FILE_SIZE)) fi else log "JUNK: $filepath" if [[ "$DRY_RUN" == false ]]; then rm -f "$filepath" && { ((JUNK_COUNT++)) JUNK_BYTES=$((JUNK_BYTES + FILE_SIZE)) } || error "Failed to delete: $filepath" else ((JUNK_COUNT++)) JUNK_BYTES=$((JUNK_BYTES + FILE_SIZE)) fi fi done < <( # Scan all host paths defined in PATH_MAP — covers all root folders managed by Sonarr for host_path in "${PATH_MAP[@]}" "$SONARR_TV_ROOT"; do [[ -d "$host_path" ]] && find "$host_path" -type f 2>/dev/null done | sort -u ) if [[ "$DRY_RUN" == false ]]; then echo "" info "Cleaning up empty folders..." for host_path in "${PATH_MAP[@]}" "$SONARR_TV_ROOT"; do [[ -d "$host_path" ]] && \ find "$host_path" -mindepth 1 -type d -empty -delete 2>/dev/null done success "Empty folders removed" fi END=$(date +%s) format_bytes() { local bytes=$1 if (( bytes > 1073741824 )); then awk "BEGIN {printf \"%.1fGB\", $bytes / 1073741824}" elif (( bytes > 1048576 )); then awk "BEGIN {printf \"%.1fMB\", $bytes / 1048576}" else echo "${bytes}B" fi } ORPHAN_HUMAN=$(format_bytes $ORPHAN_BYTES) JUNK_HUMAN=$(format_bytes $JUNK_BYTES) TOTAL_REMOVED=$(( ORPHAN_COUNT + JUNK_COUNT )) # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_SUMMARY Summary ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━━━ $ICON_SUMMARY SONARR CLEANUP SUMMARY ━━━━━" echo "$ICON_SYNC Tracked by Sonarr: $TRACKED_COUNT files" echo "$ICON_SHIELD Protected: $PROTECTED_COUNT files (artwork, subtitles, metadata)" echo "$ICON_TRASH Orphans removed: $ORPHAN_COUNT files ($ORPHAN_HUMAN)" echo "$ICON_TRASH Junk removed: $JUNK_COUNT files ($JUNK_HUMAN)" echo "$ICON_TIME Recent skipped: $RECENT_COUNT files (under ${SONARR_ORPHAN_AGE} days)" echo "$ICON_TIME Duration: $(format_duration $((END - START)))" echo "" if [[ "$DRY_RUN" == true ]]; then echo "$ICON_WARN Status: DRY RUN — no files deleted" elif [[ "$TOTAL_REMOVED" -eq 0 ]]; then echo "$ICON_DONE Status: $ICON_SUCCESS CLEAN — nothing to remove" notify "Sonarr cleanup complete on $(hostname) — library is clean" "Sonarr Cleanup" "normal" else echo "$ICON_DONE Status: $ICON_SUCCESS DONE — $TOTAL_REMOVED files removed" notify "Sonarr cleanup on $(hostname) — removed $TOTAL_REMOVED files (orphans: $ORPHAN_HUMAN junk: $JUNK_HUMAN)" "Sonarr Cleanup" "normal" fi echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"