Skip to content

Instantly share code, notes, and snippets.

@fryfrog
Last active April 13, 2024 11:06
Show Gist options
  • Save fryfrog/94716e7e27ba38dff57c7631d9f58bed to your computer and use it in GitHub Desktop.
Save fryfrog/94716e7e27ba38dff57c7631d9f58bed to your computer and use it in GitHub Desktop.
A Sonarr post processing script to remove the video file from packed torrents, modified version of subzero79/87a347a07964390884c9
#!/bin/bash
# Examples for testing
# sonarr_episodefile_sourcefolder="/data/torrent/tv/Penny.Dreadful.S01E01.720p.HDTV.x264-2HD" sonarr_episodefile_sourcepath="/data/torrent/tv/Penny.Dreadful.S01E01.720p.HDTV.x264-2HD/penny.dreadful.s01e01.720p.hdtv.x264-2hd.mkv"
# Instructions
# Put this script somewhere on your file system like /usr/local/bin and make it executable.
#
# In Sonarr, Settings -> Connect add a Custom Script
# On Grab: No
# On Download: Yes
# On Upgrade: Yes
# On Rename: No
# Path: /path/to/where/script/is/sonarr_cleanup_packed_torrent.sh
# Arguments:
# Tune values below to protect your torrents w/ small rar files or non-torrent download client.
# In *bytes*, the biggest rar file size limit to prevent video deletion from torrents with unrelated rar files (like subs)
# 25 * 1024 * 1024
rar_min_size=26214400
# Seconds to wait between size checks for in progress unpack
unpack_time=5
# The final base directory torrents end up in, for example "tv" from /data/torrents/tv
sonarr_final_dir="tv"
# Identifiable portion of path to torrents, so it will only run on torrents.
# For example, a path of "/data/torrents/tv", "torrents" is a good choice.
torrent_path_portion="torrents"
# Test that this is a download event, so we don't run on grab or rename.
# shellcheck disable=SC2154
if [[ "${sonarr_eventtype}" != "Download" ]]; then
echo "[Torrent Cleanup] Sonarr Event Type is NOT Download, exiting."
exit
fi
# Test this file exists, no point running on a file that isn't there.
# shellcheck disable=SC2154
if ! [[ -f "${sonarr_episodefile_sourcepath}" ]]; then
echo "[Torrent Cleanup] File ${sonarr_episodefile_sourcepath} does not exist, exiting."
exit
fi
# Test that this is a torrent, so we don't run on usenet downloads.
# shellcheck disable=SC2154
if ! [[ "${sonarr_episodefile_sourcepath}" =~ ${torrent_path_portion} ]]; then
echo "[Torrent Cleanup] Path ${sonarr_episodefile_sourcepath} does not contain \"torrent\", exiting."
exit
fi
# Test that this is a multi-file torrent, so we don't run on single file torrents.
# shellcheck disable=SC2154
base_dir=$( basename "${sonarr_episodefile_sourcefolder}" )
if [[ "${base_dir}" == "${sonarr_final_dir}" ]]; then
echo "[Torrent Cleanup] Single file torrent, exiting."
exit
fi
# We might run while the unpack is still happening, so wait for that before removing.
echo "[Torrent Cleanup] Starting wait for ${sonarr_episodefile_sourcepath} unpacking..."
file_size_start=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
sleep ${unpack_time}
file_size_end=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
until [[ ${file_size_start} -eq ${file_size_end} ]]; do
file_size_start=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
sleep ${unpack_time}
file_size_end=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
done
echo "[Torrent Cleanup] Finished wait for ${sonarr_episodefile_sourcepath} unpacking..."
# Test for rar and r## files and check the *size* of the biggest one so we don't run due to packed subs or something.
# shellcheck disable=SC2154
if find "${sonarr_episodefile_sourcefolder}" -type f -iregex '.*\.r[0-9a][0-9r]$' | grep -Eq '.*'; then
# shellcheck disable=SC2154
rar_size="$( find "${sonarr_episodefile_sourcefolder}" -type f -iregex '.*\.r[0-9a][0-9r]$' -ls | sort -nk 7 | tail -1 | awk '{ print $7 }' )"
if [[ ${rar_size} -gt ${rar_min_size} ]]; then
echo "[Torrent Cleanup] Rar file size ${rar_size} exceeds minimum of ${rar_min_size}, deleting video file."
rm "${sonarr_episodefile_sourcepath}"
else
echo "[Torrent Cleanup] Rar file size ${rar_size} DOES NOT MEET minimum of ${rar_min_size}, skipping deletion of video file."
fi
else
echo "[Torrent Cleanup] No rar files, exiting."
fi
@fryfrog
Copy link
Author

fryfrog commented Nov 13, 2018

Access denied sounds like permissions. Sonarr/Radarr copy, so that only requires read. To delete, they'd need write which you may not be giving. Check and then fix it, you'd probably need to change the umask for your torrent client.

@diablc
Copy link

diablc commented Dec 11, 2018

Bit confused on how I need to set this up. I have all my torrents syncing locally from a seedbox. The completed torrents are in "/sync" All the torrents are decompressed on the seedbox side. When I delete the decompress file on my side, it will also delete the file on the seedbox side when it syncs.

@BlindByrd
Copy link

BlindByrd commented Jan 17, 2019

FIXED: This error is caused by Sonarr not having permission to execute the script. In windows, navigate to the file, right click > properties > security tab > edit -- Check Allow for Read & execute for all users. My user names were: "Everyone" "nobody (Unix User\nobody)" and "users (Unix group\users)". Then hit "Okay"

I'm having a similar error, I'm not sure what I'm doing wrong, but I have my Sonarr docker permissions set to read/write. I have deluge extract to the torrent's own folder in /data/Complete (which is located at /mnt/user/Downloads/Complete). Sonarr and Deluge are both directed to /mnt/user/Downloads for /data. Therefore, I changed the script to have

# The final base directory torrents end up in, for example "tv" from /data/torrents/tv
sonarr_final_dir="Complete"

# Identifiable portion of path to torrents, so it will only run on torrents.
# For example, a path of "/data/torrents/tv", "torrents" is a good choice.
torrent_path_portion="Complete"

I've been fiddling with it for a while now, and still can't figure out what's going wrong. I am not very familiar with code, so forgive any ignorance. This is also on unRAID, if that helps.

[v2.0.0.5252] System.ComponentModel.Win32Exception (0x80004005): ApplicationName='/scripts/sonarr_cleanup_packed_torrent.sh', CommandLine='', CurrentDirectory='', Native error= Access denied
at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x002dc] in /build/mono/src/mono/mcs/class/System/System.Diagnostics/Process.cs:775
at System.Diagnostics.Process.Start () [0x0003a] in /build/mono/src/mono/mcs/class/referencesource/System/services/monitoring/system/diagnosticts/Process.cs:2005
at (wrapper remoting-invoke-with-check) System.Diagnostics.Process.Start()
at NzbDrone.Common.Processes.ProcessProvider.Start (System.String path, System.String args, System.Collections.Specialized.StringDictionary environmentVariables, System.Action1[T] onOutputDataReceived, System.Action1[T] onErrorDataReceived) [0x00194] in C:\BuildAgent\work\5d7581516c0ee5b3\src\NzbDrone.Common\Processes\ProcessProvider.cs:186
at NzbDrone.Common.Processes.ProcessProvider.StartAndCapture (System.String path, System.String args, System.Collections.Specialized.StringDictionary environmentVariables) [0x00011] in C:\BuildAgent\work\5d7581516c0ee5b3\src\NzbDrone.Common\Processes\ProcessProvider.cs:218
at NzbDrone.Core.Notifications.CustomScript.CustomScript.ExecuteScript (System.Collections.Specialized.StringDictionary environmentVariables) [0x0001b] in C:\BuildAgent\work\5d7581516c0ee5b3\src\NzbDrone.Core\Notifications\CustomScript\CustomScript.cs:139
at NzbDrone.Core.Notifications.CustomScript.CustomScript.OnDownload (NzbDrone.Core.Notifications.DownloadMessage message) [0x003f8] in C:\BuildAgent\work\5d7581516c0ee5b3\src\NzbDrone.Core\Notifications\CustomScript\CustomScript.cs:103
at NzbDrone.Core.Notifications.NotificationService.Handle (NzbDrone.Core.MediaFiles.Events.EpisodeImportedEvent message) [0x000e1] in C:\BuildAgent\work\5d7581516c0ee5b3\src\NzbDrone.Core\Notifications\NotificationService.cs:144

@BlindByrd
Copy link

This script can also be modified to work with Radarr, I just changed all the instances of sonarr in the script to radarr and it worked after fixing the permission issue noted in my comment above.

Thanks for the great script fryfrog!

@BinsonBuzz
Copy link

Hi

Does this work with V3 which looks for an exit code of 0 when sonarr_eventtype Test is sent. I've tried adding:

if [[ "${sonarr_eventtype}" == "Test" ]]; then
  exit 0
fi

But it still says in Sonarr "Script exited with code: 255" when I hit test?

Any ideas?

Thanks in advance

@fryfrog
Copy link
Author

fryfrog commented Mar 6, 2020

I'll give it a test when I can, I've been using it w/ v3, but maybe that pre-dates the test.

@BinsonBuzz
Copy link

Thanks - let me know how you get on

@BinsonBuzz
Copy link

How did you get on?

@fryfrog
Copy link
Author

fryfrog commented Mar 20, 2020

Hey, sorry for the delay... but you don't need to modify it at all. It already knows it isn't a download event type and exits cleanly. Turn logging up to debug and see what is going on.

20-3-20 08:45:36.8|Debug|CustomScript|Executing external script: /usr/local/bin/sonarr_cleanup_packed_torrent.sh
20-3-20 08:45:36.8|Debug|sonarr_cleanup_packed_torrent.sh|Starting /usr/local/bin/sonarr_cleanup_packed_torrent.sh
20-3-20 08:45:36.8|Debug|sonarr_cleanup_packed_torrent.sh|[Torrent Cleanup] Sonarr Event Type is NOT Download, exiting.
20-3-20 08:45:36.8|Debug|CustomScript|Executed external script: /usr/local/bin/sonarr_cleanup_packed_torrent.sh - Status: 0
20-3-20 08:45:36.8|Debug|CustomScript|Script Output:
3/20/2020 3:45:36 PM - Standard - [Torrent Cleanup] Sonarr Event Type is NOT Download, exiting.

@BinsonBuzz
Copy link

What am I doing wrong? This is what I get in the logs when I try and add the script and hit 'test':

20-3-20 22:52:05.5|Debug|Api|[GET] /api/v3/filesystem?path=%2Fuser%2Fappdata%2Fother%2Fscripts%2Funrar_cleanup%2Fsonarr.sh&allowFoldersWithoutTrailingSlashes=false&includeFiles=true: 200.OK (21 ms)
20-3-20 22:52:07.4|Debug|CustomScript|Executing external script: /user/appdata/other/scripts/unrar_cleanup/sonarr.sh
20-3-20 22:52:07.4|Debug|sonarr.sh|Starting /user/appdata/other/scripts/unrar_cleanup/sonarr.sh 
20-3-20 22:52:07.5|Debug|CustomScript|Executed external script: /user/appdata/other/scripts/unrar_cleanup/sonarr.sh - Status: 255
20-3-20 22:52:07.5|Debug|CustomScript|Script Output: 

20-3-20 22:52:07.5|Warn|SonarrErrorPipeline|Invalid request Validation failed: 
 -- : Script exited with code: 255
20-3-20 22:52:07.5|Debug|Api|[POST] /api/v3/notification/test: 400.BadRequest (86 ms)
20-3-20 22:52:12.6|Debug|Api|[GET] /api/v3/filesystem?path=%2Fuser%2Fappdata%2Fother%2Fscripts%2Funrar_cleanup%2Fsonarr.sh&allowFoldersWithoutTrailingSlashes=false&includeFiles=true: 200.OK (4 ms)
20-3-20 22:52:14.9|Debug|Api|[GET] /api/v3/filesystem?path=%2Fuser%2Fappdata%2Fother%2Fscripts%2Funrar_cleanup%2Fsonarr.sh&allowFoldersWithoutTrailingSlashes=true&includeFiles=true: 200.OK (7 ms)
20-3-20 22:52:16.9|Debug|Api|[GET] /api/v3/filesystem?path=%2Fuser%2Fappdata%2Fother%2Fscripts%2Funrar_cleanup%2Fsonarr.sh&allowFoldersWithoutTrailingSlashes=true&includeFiles=true: 200.OK (6 ms)
20-3-20 22:52:24.3|Debug|CustomScript|Executing external script: /user/appdata/other/scripts/unrar_cleanup/sonarr.sh
20-3-20 22:52:24.3|Debug|sonarr.sh|Starting /user/appdata/other/scripts/unrar_cleanup/sonarr.sh 
20-3-20 22:52:24.4|Debug|CustomScript|Executed external script: /user/appdata/other/scripts/unrar_cleanup/sonarr.sh - Status: 255

@pnguyencong
Copy link

pnguyencong commented Apr 7, 2020

Hi! I'm getting an error when the script is trying to delete : It looks like it's running too early?

OMV5
Docker/Portainer Sonarr 2.0.0.5344 and Deluge V1.x /w LCExtractor-0.6.2-py2.7.egg

  | DownloadedEpisodesImportService | RAR file detected, will require manual cleanup | 8:04pm
  | sonarr_cleanup_packed_torrent.sh | rm: cannot remove '/downloads/FILE.720p.HDTV.x264-KILLERS/FILE.720p.HDTV.x264-KILLERS.mkv': No such file or directory | 8:04pm
  | sonarr_cleanup_packed_torrent.sh | stat: cannot stat '/downloads/FILE.720p.HDTV.x264-KILLERS/FILE.720p.HDTV.x264-KILLERS.mkv': No such file or directory | 8:04pm
  | sonarr_cleanup_packed_torrent.sh | stat: cannot stat '/downloads/FILE.720p.HDTV.x264-KILLERS/FILE.720p.HDTV.x264-KILLERS.mkv': No such file or directory | 8:04pm


Hopefully I'm just doing something simple wrong! @fryfrog

@fryfrog
Copy link
Author

fryfrog commented Apr 7, 2020

It is a Sonarr post processing script, it gets run after import. There is no way for it to run too early. The file/path comes from Sonarr and when the script tries to remove it, it is already gone. Any idea why? Do you have Remove enabled w/ Complete and Failed Download Handler? Do you have your seed time/ratio goals set low enough that they're met at import?

@fryfrog
Copy link
Author

fryfrog commented Apr 7, 2020

But I think I'll add a file check, seems reasonable. :)

@pnguyencong
Copy link

pnguyencong commented Apr 7, 2020

Hmmm. I'm trying to have the file moved the moment it finishes unpacking.

What should i have seed time/ratio set to to achieve that? I have everything at 0 with "Stop seeding when share reaches 0" enabled along with "remove torrent when share ratio is reached" enabled.

It's almost like the script is running while the file is still moving from one drive to the next. Which since it's one device to another - it isn't instant like it would be if it was on the same device? idk - just spit balling - maybe my situation is unique @fryfrog

@fryfrog
Copy link
Author

fryfrog commented Apr 7, 2020

Only assholes don't seed public torrents to 1.0. I think some clients interpret 0 as unlimited, so try something besie that. Sonarr doesn't call post processing scripts until after the import is done. Turn logging up to trace and watch an import.

@pnguyencong
Copy link

hey hey hey - it's a private tracker that I pay for access to. @fryfrog otherwise I'd agree with you

@fryfrog
Copy link
Author

fryfrog commented Apr 7, 2020

So try 1 min and 0.1 ratio, that should be met fairly quickly. :)

@pnguyencong
Copy link

20-4-6 20:45:08.1|Trace|ProcessProvider|Setting environment variable 'sonarr_series_tvmazeid' to '5'
20-4-6 20:45:08.1|Trace|ProcessProvider|Setting environment variable 'sonarr_episodefile_relativepath' to 'Season 3/filename.mkv'
20-4-6 20:45:08.1|Debug|sonarr_cleanup_packed_torrent.sh|Starting /config/sonarr_cleanup_packed_torrent.sh 
20-4-6 20:45:08.6|Debug|sonarr_cleanup_packed_torrent.sh|[Torrent Cleanup] Starting wait for /downloads/filename/filename.mkv unpacking...
20-4-6 20:45:08.6|Error|sonarr_cleanup_packed_torrent.sh|stat: cannot stat '/downloads/filename/filename.mkv': No such file or directory
20-4-6 20:45:13.6|Debug|sonarr_cleanup_packed_torrent.sh|[Torrent Cleanup] Finished wait for /downloads/filename/filename.mkv unpacking...
20-4-6 20:45:13.6|Error|sonarr_cleanup_packed_torrent.sh|stat: cannot stat '/downloads/filename/filename.mkv': No such file or directory
20-4-6 20:45:13.6|Debug|sonarr_cleanup_packed_torrent.sh|[Torrent Cleanup] No rar files, exiting.
20-4-6 20:45:13.6|Debug|CustomScript|Executed external script: /config/sonarr_cleanup_packed_torrent.sh - Status: 0
20-4-6 20:45:13.6|Debug|CustomScript|Script Output: 
4/7/2020 1:45:08 AM - Standard - [Torrent Cleanup] Starting wait for /downloads/filename/filename.mkv unpacking...
4/7/2020 1:45:08 AM - Error - stat: cannot stat '/downloads/filename/filename.mkv': No such file or directory
4/7/2020 1:45:13 AM - Standard - [Torrent Cleanup] Finished wait for /downloads/filename/filename.mkv unpacking...
4/7/2020 1:45:13 AM - Error - stat: cannot stat '/downloads/filename/filename.mkv': No such file or directory
4/7/2020 1:45:13 AM - Standard - [Torrent Cleanup] No rar files, exiting.

@fryfrog
Copy link
Author

fryfrog commented Apr 7, 2020

Did you use the version I just uploaded, w/ the file check? If the file doesn't exist, it should have bailed earlier.

Do you have your torrent client setup to remove the torrent when seed time/ratio goals are met? I bet you do. Don't do that. Set it to pause or stop, enable Remove in Sonarr/Radarr's CDH and FDH.

@pnguyencong
Copy link

@fryfrog before I check all that . THANK YOU for being super responsive and helpful. I really appreciate it.

@pnguyencong
Copy link

Did you use the version I just uploaded, w/ the file check? If the file doesn't exist, it should have bailed earlier.

^ installed that version

Do you have your torrent client setup to remove the torrent when seed time/ratio goals are met? I bet you do. Don't do that. Set it to pause or stop, enable Remove in Sonarr/Radarr's CDH and FDH.

^i don't think Deluge has that option - because the torrents stay listed even after they get deleted - but I did disable "remove torrent when share ratio is reached"

have to find another torrent to test - the one i just tried didn't get data back from deluge for the "ACTIVITY" screen

@darkcloud784
Copy link

Sonarr V3 doesn't have On Download as a firing event. Looks like it was replaced with On Import.

@Bishop-trevorstuart
Copy link

Still learning many basics, so forgive anything I'm "missing".
I've put the script on the same linux machine as sonarr, in the suggested /usr/local/bin folder. Granted the execute permissions.
From the cli when I run the script it says "[Torrent Cleanup] Sonarr Event Type is NOT Download, exiting."
I do have a downloaded torrent and it's folder is full of rar files. In Sonarr activity it shows this torrent and isn't doing anything because it's still rar'd.
When I put the script into sonarr, and ran test it said successful. But I left it overnight and nothing appeared to happen. I set sonarr to debugging too. Searching for the words "custom" or "script" I'm not finding any entries in the debug log so it's as if Sonarr isn't trying to run the script at all.
How do I force the script to run from within sonarr so I can start checking for log entries.

@fryfrog
Copy link
Author

fryfrog commented Aug 5, 2020

This isn't an unrar script, all it does is remove the extracted video file from a packed torrent folder after it is imported because sonarr/radarr copy or hard link from torrents that are still seeding, but that video file isn't needed for seeding. If you need help, hop on Discord or /r/sonarr. You probably just need to google for "unpack ".

@moly
Copy link

moly commented Sep 14, 2020

An alternative way to do this is to use the unrar tool to list which files have been extracted and then delete them. This has the advantage of also cleaning up any subs, nfo etc that were also in the rar. Here's the script I've been using.

#! /bin/sh

if [ "${sonarr_eventtype}" != "Download" ]; then
  exit
fi

# don't run if this is a single file torrent. change "/disk0/downloads/sonarr" to your download directory
if [ "${sonarr_episodefile_sourcefolder}" = "/disk0/downloads/sonarr" ]; then
  exit
fi

find "${sonarr_episodefile_sourcefolder}" -name '*.rar' -execdir sh -c "unrar lb {} | xargs -rd '\n' rm -rf" \;

You will need to make sure your unraring script uses 'unrar x' and not 'unrar e' so that the file paths are preserved when extracting.

@fryfrog
Copy link
Author

fryfrog commented Sep 14, 2020

@moly, that is a cool idea. :)

@absywabsy
Copy link

Hi,

This is a great script - is there any way to adapt this so that all the files are deleted not just the extracted files? I'm still seeding on my remote server, just want all the files off my local storage.

@fryfrog
Copy link
Author

fryfrog commented Mar 22, 2021

Sure, just make it less restrictive about what it deletes.

@absywabsy
Copy link

Sure, just make it less restrictive about what it deletes.

Hi, thanks, I've been trying to get this to work, I edited just one line at the bottom to change it to:

rm -r "${sonarr_episodefile_sourcefolder}"

and I'm embarassed to say I was trying it on Synology and ran into some permissions issues with Seedsync and while I got rid of those issues by switching over to unRAID - I am still not able to accomplish this.

I'm an absolute noob by the way, don't know any languages and new to all this but would love to get this to work.

When trying:
rm "${sonarr_episodefile_sourcefolder}"

I get the error: rm: cannot remove 'source folder': Is a directory

When trying it with -r, I don't even get a message. Any ideas on how to get this to work?

@absywabsy
Copy link

absywabsy commented Apr 13, 2021

Sorry for the double post, I got it working now! Thanks so much for this script, it really is a lifesaver as I don't have to manually delete things copied over from my seedbox now. I will share my edit but be warned...I may have made it so that it pretty much deletes the folder regardless of the checks you put in place, which in the case of sonarr/radarr for me, if it successfully imports the video file, I want it to do that anyway.

#!/bin/bash

# Examples for testing
# sonarr_episodefile_sourcefolder="/data/torrent/tv/Penny.Dreadful.S01E01.720p.HDTV.x264-2HD" sonarr_episodefile_sourcepath="/data/torrent/tv/Penny.Dreadful.S01E01.720p.HDTV.x264-2HD/penny.dreadful.s01e01.720p.hdtv.x264-2hd.mkv"

# Instructions
# Put this script somewhere on your file system like /usr/local/bin and make it executable.
#
# In Sonarr, Settings -> Connect add a Custom Script
# On Grab: No
# On Download: Yes
# On Upgrade: Yes
# On Rename: No
# Path: /path/to/where/script/is/sonarr_cleanup_packed_torrent.sh
# Arguments:

# Tune values below to protect your torrents w/ small rar files or non-torrent download client.

# In *bytes*, the biggest rar file size limit to prevent video deletion from torrents with unrelated rar files (like subs)
# 25 * 1024 * 1024
rar_min_size=26214400

# Seconds to wait between size checks for in progress unpack
unpack_time=5

# The final base directory torrents end up in, for example "tv" from /data/torrents/tv
sonarr_final_dir="tv"

# Identifiable portion of path to torrents, so it will only run on torrents.
# For example, a path of "/data/torrents/tv", "torrents" is a good choice.
torrent_path_portion="torrents"

# Test that this is a download event, so we don't run on grab or rename.
# shellcheck disable=SC2154
if [[ "${sonarr_eventtype}" != "Download" ]]; then
  echo "[Torrent Cleanup] Sonarr Event Type is NOT Download, exiting."
  exit
fi

# Test this file exists, no point running on a file that isn't there.
# shellcheck disable=SC2154
if ! [[ -f "${sonarr_episodefile_sourcepath}" ]]; then
  echo "[Torrent Cleanup] File ${sonarr_episodefile_sourcepath} does not exist, exiting."
  exit
fi

# Test that this is a torrent, so we don't run on usenet downloads.
# shellcheck disable=SC2154
if ! [[ "${sonarr_episodefile_sourcepath}" =~ ${torrent_path_portion} ]]; then
  echo "[Torrent Cleanup] Path ${sonarr_episodefile_sourcepath} does not contain \"torrent\", exiting."
  exit
fi

# Test that this is a multi-file torrent, so we don't run on single file torrents.
# shellcheck disable=SC2154
base_dir=$( basename "${sonarr_episodefile_sourcefolder}" )
if [[ "${base_dir}" == "${sonarr_final_dir}" ]]; then
  echo "[Torrent Cleanup] Single file torrent, exiting."
  exit
fi

# We might run while the unpack is still happening, so wait for that before removing.
echo "[Torrent Cleanup] Starting wait for ${sonarr_episodefile_sourcepath} unpacking..."
file_size_start=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
sleep ${unpack_time}
file_size_end=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
until [[ ${file_size_start} -eq ${file_size_end} ]]; do
  file_size_start=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
  sleep ${unpack_time}
  file_size_end=$( stat --printf="%s" "${sonarr_episodefile_sourcepath}" )
done
echo "[Torrent Cleanup] Finished wait for ${sonarr_episodefile_sourcepath} unpacking..."

# Test for rar and r## files and check the *size* of the biggest one so we don't run due to packed subs or something.
# shellcheck disable=SC2154
if find "${sonarr_episodefile_sourcefolder}" -type f -iregex '.*\.r[0-9a][0-9r]$' | grep -Eq '.*'; then
  # shellcheck disable=SC2154
  rar_size="$( find "${sonarr_episodefile_sourcefolder}" -type f -iregex '.*\.r[0-9a][0-9r]$' -ls | sort -nk 7 | tail -1 | awk '{ print $7 }' )"
  if [[ ${rar_size} -gt ${rar_min_size} ]]; then
    echo "[Torrent Cleanup] Rar file size ${rar_size} exceeds minimum of ${rar_min_size}, deleting folder."
    rm -r "${sonarr_episodefile_sourcefolder}"
  else
    echo "[Torrent Cleanup] Rar file size ${rar_size} DOES NOT MEET minimum of ${rar_min_size}, skipping deletion of video file."
  fi
else
  rm -r "${sonarr_episodefile_sourcefolder}"
  echo "[Torrent Cleanup] No rar files, deleting folder."
fi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment