#!/bin/bash

# --- Configuration ---
serverHost=localhost
serverPort=9091
userName=downloader
userPassword=downloader
export PATH="/bin:${PATH}"

# Define the transmission states that indicate a torrent is no longer actively downloading
DONE_STATES=("Seeding" "Stopped" "Finished" "Idle")

# Base command to interact with the Transmission RPC interface
tcli="/usr/bin/transmission-remote ${serverHost}:${serverPort} -n ${userName}:${userPassword}"

# This variable will hold a comma-separated list of torrent IDs that need to be deleted
radList=''

# Step 1: Get a list of ALL torrent IDs currently in Transmission.
# The grep/sed pipeline extracts just the numeric ID from the beginning of each line.
for tId in $(${tcli} --list | grep -e '^[[:blank:]]*[0-9]' | sed 's|^[[:blank:]]*\([0-9]\+\).*|\1|g'); do

    # Fetch detailed information for this specific torrent ID
    info=$(${tcli} -t ${tId} -i)

    # Extract the "Date finished" string
    endDate=$(echo "${info}" | grep 'Date finished:' | sed 's|^[[:blank:]]*Date finished:[[:blank:]]*||g')

    # If the torrent hasn't finished downloading yet, skip it and move to the next one
    if [ "$endDate" = "Unknown" ] || [ -z "$endDate" ]; then
        continue
    fi

    # Convert the finish date into a Unix timestamp (seconds since 1970) for math comparisons
    endDateT=$(date -d "${endDate}" +%s 2>/dev/null || echo 0)

    # Calculate what the timestamp was exactly 10 days ago (10 days * 24 hours * 60 min * 60 sec = 864000)
    tenDayBefore=$(expr $(date +%s) - 864000)

    # Extract the current state of the torrent (e.g., "Seeding", "Downloading")
    STATE=$(echo "$info" | sed -n 's/.*State: \(.*\)/\1/p')

    # Check if the current state matches one of our allowed "DONE_STATES"
    if [[ "${DONE_STATES[@]}" =~ "$STATE" ]] || echo '' >/dev/null; then

        # Extract the current upload/download ratio
        ratio=$(echo "$info" | sed -n 's/.*Ratio: \(.*\)/\1/p')

        # Remove decimals to get a whole number for easier comparison
        ratioMajor=$(echo "${ratio}" | sed 's|.[0-9]\+||g')

        # If the ratio is Infinity (meaning we seeded but downloaded 0 bytes), treat it as 0
        if [[ ${ratioMajor} = "Inf" ]]; then
            ratioMajor=0
        fi

        # Evaluation Condition 1: Is the torrent finished AND older than 10 days?
        if [ ${endDateT} -ne 0 ] && [ ${endDateT} -lt ${tenDayBefore} ]; then
            # Append this ID to our deletion list (with a comma if the list isn't empty)
            radList="${radList:+$radList,}${tId}"

        # Evaluation Condition 2: Is the sharing ratio 10 or greater?
        elif [ ${ratioMajor} -ge 10 ]; then
            # Append this ID to our deletion list
            radList="${radList:+$radList,}${tId}"
        fi
    fi
done

# Step 2: Execution
# If our deletion list is not empty, send the command to Transmission.
# The '-rad' flag tells Transmission to Remove And Delete data.
if [[ -n ${radList} ]]; then
    ${tcli} -t ${radList} -rad
fi
