#!/bin/bash # ----------------------------------------------------------------------------------------------- # --------------------------------- Radarr Cleanup Script -------------------------------------- # ----------------------------------------------------------------------------------------------- # Removes orphaned movie files from the library that Radarr no longer tracks. # Uses the Radarr API to build a complete list of tracked movie file paths then compares # against what exists on disk — anything not tracked and older than RADARR_ORPHAN_AGE # days is considered an orphan and deleted. # # File classification: # TRACKED — Radarr API knows about this exact file path → leave it alone # PROTECTED — matches RADARR_PROTECTED_PATTERNS → never delete (artwork, subtitles, .nfo) # ORPHAN — video file, not tracked, older than RADARR_ORPHAN_AGE days → delete # JUNK — not a video extension, not protected → delete regardless of age # RECENT — not tracked, under RADARR_ORPHAN_AGE days old → skip (may be mid-import) # # Why protected patterns matter: # Radarr generates movie 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 Radarr manages Movies. HOST2 Radarr manages Anime_Movies. # 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" # Check for --i-know-what-im-doing and --skip-strike-list flags before parse_args I_KNOW=false SKIP_STRIKES=false FILTERED_ARGS=() for arg in "$@"; do if [[ "$arg" == "--i-know-what-im-doing" ]]; then I_KNOW=true elif [[ "$arg" == "--skip-strike-list" ]]; then SKIP_STRIKES=true else FILTERED_ARGS+=("$arg") fi done parse_args "${FILTERED_ARGS[@]}" # Nuclear mode disclaimer if [[ "$I_KNOW" == true ]] && [[ "$SKIP_STRIKES" == true ]] && [[ "$DRY_RUN" != true ]]; then echo "" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "⚠️ WARNING — NUCLEAR MODE ACTIVE" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo " Flags: --i-know-what-im-doing --skip-strike-list" echo " Strike system: BYPASSED — deletes on first pass" echo " Size threshold: BYPASSED — no GB limit" echo " Data recovery: NOT POSSIBLE after deletion" echo "" echo " The script author takes no responsibility for data" echo " loss when both flags are used together. This is a" echo " 100% intentional action by the user." echo "" echo " Review the dry run output before proceeding." echo " You have 10 seconds to cancel (Ctrl+C)..." echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" sleep 10 echo " Proceeding..." echo "" fi # ----------------------------------------------------------------------------------------------- # ━━━ $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 Radarr API calls" exit 1 fi if ! command -v jq >/dev/null 2>&1; then error "jq not found — required for JSON parsing" notify "Radarr cleanup failed on $(hostname) — jq not installed" "Radarr Cleanup" "warning" exit 1 fi # Select correct Radarr instance based on which server is running this script detect_hosts if [[ "$LOCAL_SERVER_NAME" == "$HOST1" ]]; then RADARR_URL="$HOST1_RADARR_URL" RADARR_API_KEY="$HOST1_RADARR_API_KEY" RADARR_MOVIES_ROOT="$HOST1_RADARR_MOVIES_ROOT" else RADARR_URL="$HOST2_RADARR_URL" RADARR_API_KEY="$HOST2_RADARR_API_KEY" RADARR_MOVIES_ROOT="$HOST2_RADARR_MOVIES_ROOT" fi # Load path map for this host declare -A ARR_PATH_MAP if [[ "$LOCAL_SERVER_NAME" == "$HOST1" ]]; then for key in "${!HOST1_RADARR_PATH_MAP[@]}"; do ARR_PATH_MAP["$key"]="${HOST1_RADARR_PATH_MAP[$key]}" done else for key in "${!HOST2_RADARR_PATH_MAP[@]}"; do ARR_PATH_MAP["$key"]="${HOST2_RADARR_PATH_MAP[$key]}" done fi info "Radarr instance: $LOCAL_SERVER_NAME → $RADARR_URL" info "Movies root: $RADARR_MOVIES_ROOT" require_var RADARR_URL require_var RADARR_API_KEY require_var RADARR_MOVIES_ROOT if [[ ! -d "$RADARR_MOVIES_ROOT" ]]; then error "Movies root not found: $RADARR_MOVIES_ROOT" notify "Radarr cleanup failed on $(hostname) — movies root not found: $RADARR_MOVIES_ROOT" "Radarr 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 Radarr URL: $RADARR_URL" echo "$ICON_GEAR Movies root: $RADARR_MOVIES_ROOT" echo "$ICON_TIME Orphan age: ${RADARR_ORPHAN_AGE} days" echo "$ICON_GEAR Extensions: ${RADARR_EXTENSIONS[*]}" echo "$ICON_GEAR Protected patterns: ${RADARR_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 # ----------------------------------------------------------------------------------------------- radarr_api() { local endpoint="$1" local response http_code body response=$(curl -sf \ --max-time 30 \ -H "X-Api-Key: $RADARR_API_KEY" \ -w "\n%{http_code}" \ "${RADARR_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 "Radarr 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 "${RADARR_EXTENSIONS[@]}"; do [[ "$ext" == "$valid_ext" ]] && return 0 done return 1 } is_protected_file() { local filename filename=$(basename "$1") for pattern in "${RADARR_PROTECTED_PATTERNS[@]}"; do # shellcheck disable=SC2254 case "$filename" in $pattern) return 0 ;; esac done return 1 } # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_SYNC Fetching Radarr Tracked Files ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━ $ICON_SYNC Fetching Radarr Tracked Files ━━━" check_api "$RADARR_URL" "Radarr" || { notify "Radarr cleanup aborted on $(hostname) — API unreachable" "Radarr Cleanup" "warning" exit 1 } info "Querying Radarr API: $RADARR_URL" MOVIEFILE_RESPONSE=$(radarr_api "moviefile") || { error "Failed to fetch movie files from Radarr — check URL and API key" notify "Radarr cleanup failed on $(hostname) — API unreachable" "Radarr Cleanup" "warning" exit 1 } TMP_DIR="/tmp/radarr_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" >> "$TRACKED_FILE" done < <(echo "$MOVIEFILE_RESPONSE" | jq -r '.[].path' 2>/dev/null) sort -u "$TRACKED_FILE" -o "$TRACKED_FILE" TRACKED_COUNT=$(wc -l < "$TRACKED_FILE") success "Radarr tracks $TRACKED_COUNT movie files" if [[ "$TRACKED_COUNT" -eq 0 ]]; then warn "No tracked files returned — Radarr may not have scanned yet or library is empty" warn "Aborting to prevent mass deletion" notify "Radarr cleanup aborted on $(hostname) — no tracked files returned from API" "Radarr Cleanup" "warning" exit 1 fi # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_CLEAN Scanning Movies Root ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━ $ICON_CLEAN Scanning Movies Root ━━━" info "Root: $RADARR_MOVIES_ROOT" info "Orphan age: ${RADARR_ORPHAN_AGE} days" info "Protected: ${RADARR_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=$(( RADARR_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 "$ICON_PROTECTED 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" ]] && [[ "$SKIP_STRIKES" != true ]]; 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 ARR_PATH_MAP — covers all root folders managed by Radarr for host_path in "${ARR_PATH_MAP[@]}" "$RADARR_MOVIES_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 "${ARR_PATH_MAP[@]}" "$RADARR_MOVIES_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 )) TOTAL_DELETE_BYTES=$(( ORPHAN_BYTES + JUNK_BYTES )) MAX_DELETE_BYTES=$(awk "BEGIN {printf \"%d\", ${RADARR_MAX_DELETE_GB:-1} * 1073741824}") # Size threshold check if [[ "$TOTAL_DELETE_BYTES" -gt "$MAX_DELETE_BYTES" ]]; then TOTAL_HUMAN=$(awk "BEGIN {printf \"%.1fGB\", $TOTAL_DELETE_BYTES / 1073741824}") if [[ "$I_KNOW" != true ]]; then echo "" error "Deletion would exceed ${RADARR_MAX_DELETE_GB:-1}GB threshold — $TOTAL_HUMAN would be deleted" error "Review the ORPHAN lines above carefully before proceeding" error "If this is expected, rerun with: --i-know-what-im-doing" error "To also bypass age check and delete on first pass: add --skip-strike-list" notify "Radarr cleanup halted on $(hostname) — ${TOTAL_HUMAN} deletion requires --i-know-what-im-doing" "Radarr Cleanup" "warning" exit 1 else warn "OVERRIDE — deletion is ${TOTAL_HUMAN} — proceeding because --i-know-what-im-doing" fi fi # ----------------------------------------------------------------------------------------------- # ━━━ $ICON_SUMMARY Summary ━━━ # ----------------------------------------------------------------------------------------------- echo "" echo "━━━━━ $ICON_SUMMARY RADARR CLEANUP SUMMARY ━━━━━" echo "$ICON_SYNC Tracked by Radarr: $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 ${RADARR_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 "Radarr cleanup complete on $(hostname) — library is clean" "Radarr Cleanup" "normal" else echo "$ICON_DONE Status: $ICON_SUCCESS DONE — $TOTAL_REMOVED files removed" notify "Radarr cleanup on $(hostname) — removed $TOTAL_REMOVED files (orphans: $ORPHAN_HUMAN junk: $JUNK_HUMAN)" "Radarr Cleanup" "normal" fi # Write stats for sunday_morning_coffee_report.sh if [[ "$DRY_RUN" == false ]] && [[ -n "${ARR_CLEANUP_STATS:-}" ]]; then DATE=$(date '+%Y-%m-%d') echo "${DATE}|radarr|${ORPHAN_COUNT}|${ORPHAN_BYTES}|${JUNK_COUNT}|${JUNK_BYTES}|${RECENT_COUNT}|${TRACKED_COUNT}" \ >> "$ARR_CLEANUP_STATS" 2>/dev/null || true fi echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"