#!/usr/bin/env bash

# Set strict error handling to stop execution on failures.
set -euo pipefail

# Define configuration variables.
readonly CONFIG_DIR="${HOME}/.config"
readonly CONFIG_FILE="${CONFIG_DIR}/torrent-automator.conf"
readonly LOG_DIR="${HOME}/.cache/aria2_logs"

# Global placeholders for credentials loaded at runtime.
TELEGRAM_BOT_TOKEN=""
TELEGRAM_CHAT_ID=""

# Securely load credentials from the configuration file or prompt to create it.
load_or_create_config() {
    # Check if the configuration directory exists.
    if [[ ! -d "${CONFIG_DIR}" ]]; then
        mkdir -p "${CONFIG_DIR}"
    fi

    # Initialize the configuration file with secure permissions if missing.
    if [[ ! -f "${CONFIG_FILE}" ]]; then
        echo "Configuration file not found. Let's set up your secure credentials."
        
        read -r -p "Enter your Telegram Bot Token: " input_token
        read -r -p "Enter your Telegram Chat ID: " input_chat_id
        
        # Write the credentials to the secure configuration file.
        cat << EOF > "${CONFIG_FILE}"
TELEGRAM_BOT_TOKEN="${input_token}"
TELEGRAM_CHAT_ID="${input_chat_id}"
EOF
        # Restrict file access strictly to the owner.
        chmod 600 "${CONFIG_FILE}"
        echo "Configuration saved securely to ${CONFIG_FILE}."
    fi

    # Source the configuration file to load variables.
    # shellcheck source=/dev/null
    source "${CONFIG_FILE}"
}

# Verify that all necessary system dependencies are installed.
check_dependencies() {
    # Check if aria2c is available on the system path.
    if ! command -v aria2c &> /dev/null; then
        echo "Error: aria2c is not installed. Please run 'sudo apt install aria2'."
        exit 1
    fi

    # Check if curl is available for sending Telegram notifications.
    if ! command -v curl &> /dev/null; then
        echo "Error: curl is not installed. Please run 'sudo apt install curl'."
        exit 1
    fi
}

# Escape HTML special characters to prevent Telegram API parsing errors.
escape_html() {
    local input="$1"
    input="${input//&/&amp;}"
    input="${input//</&lt;}"
    input="${input//>/&gt;}"
    echo -n "${input}"
}

# Dispatch a notification message to the configured Telegram chat.
send_telegram_notification() {
    local message_text="$1"
    
    # Send the HTTP POST request to the Telegram Bot API safely using URL encoding.
    local response
    response=$(curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
        -d "chat_id=${TELEGRAM_CHAT_ID}" \
        -d "parse_mode=HTML" \
        --data-urlencode "text=${message_text}")

    # Validate if the message was accepted by Telegram.
    if [[ "$response" != *"\"ok\":true"* ]]; then
        echo "Warning: Failed to send Telegram notification. API Response: ${response}"
    fi
}

# Prompt the user interactively to obtain and validate the scan directory path.
get_scan_directory() {
    local default_dir
    default_dir=$(pwd)
    
    read -r -p "Enter the directory path to scan for torrent files [default: ${default_dir}]: " target_dir
    
    # Use current working directory if user leaves the prompt blank.
    target_dir="${target_dir:-$default_dir}"

    # Verify that the designated folder actually exists.
    if [[ ! -d "${target_dir}" ]]; then
        echo "Error: The directory '${target_dir}' does not exist."
        exit 1
    fi

    # Resolve and output the absolute path format.
    cd "${target_dir}" && pwd
}

# Display the usage manual for this utility.
show_help() {
    echo "Usage: $0 [OPTION]"
    echo ""
    echo "An automated, background torrent downloader using aria2c with Telegram notifications."
    echo ""
    echo "Options:"
    echo "  -c, --cancel   Terminate all active background aria2c download sessions."
    echo "  -h, --help      Display this interactive helper menu."
    echo ""
    echo "Default (No Arguments):"
    echo "  Prompts for a target directory, scans it for torrents, and triggers background downloads."
}

# Terminate all running aria2c background processes.
cancel_downloads() {
    # Check if any active aria2c operations exist.
    if pgrep -x aria2c > /dev/null; then
        echo "Terminating active background download processes..."
        
        # Send a graceful termination signal first.
        if pkill -15 aria2c; then
            sleep 2
        else
            # Fallback to force kill if processes persist.
            pkill -9 aria2c
        fi

        # Construct the cancellation alert with actual newlines.
        local telegram_message
        telegram_message="<b>[Pi 5] Torrent Downloads Terminated</b>
Status: <pre>All background aria2c jobs stopped by manual directive.</pre>"
        
        send_telegram_notification "${telegram_message}"
        echo "All download processes stopped successfully."
    else
        echo "No active background downloads detected."
    fi
}

# Initiate the background download process for a specific torrent file.
download_torrent() {
    local torrent_file="$1"
    local scan_dir="$2"
    local torrent_name
    torrent_name=$(basename "${torrent_file}")
    
    # Generate a unique log file path inside the centralized cache folder.
    local log_file="${LOG_DIR}/${torrent_name}.log"

    echo "Initiating background download for: ${torrent_name}"

    # Escape HTML special characters for safe notification parsing.
    local escaped_name
    escaped_name=$(escape_html "${torrent_name}")
    local escaped_log
    escaped_log=$(escape_html "${log_file}")

    # Construct and send the start notification payload.
    local start_message
    start_message="<b>[Pi 5] Torrent Download Started</b>
File: <pre>${escaped_name}</pre>
Log: <code>${escaped_log}</code>"
    send_telegram_notification "${start_message}"

    # Execute aria2c inside an asynchronous subshell block to track its lifecycle.
    # This replaces the flat 'nohup' execution pattern and registers finished states.
    (
        # Ignore terminal disconnect signals to allow execution persistent in background.
        trap '' HUP

        # Disable strict error checking in subshell to trap exit status gracefully.
        set +e

        # Run aria2c pointing explicitly to the selected scan directory destination.
        aria2c \
            --dir="${scan_dir}" \
            --disk-cache=16M \
            --disable-ipv6=true \
            --log="${log_file}" \
            --log-level=notice \
            --quiet=true \
            "${torrent_file}" > /dev/null 2>&1

        local exit_code=$?

        # Send corresponding success or failure payload based on the process exit code.
        if [[ ${exit_code} -eq 0 ]]; then
            local success_message
            success_message="<b>[Pi 5] Torrent Download Completed Successfully!</b>
File: <pre>${escaped_name}</pre>"
            send_telegram_notification "${success_message}"
        else
            local error_message
            error_message="<b>[Pi 5] Torrent Download Failed!</b>
File: <pre>${escaped_name}</pre>
Exit Code: <code>${exit_code}</code>
Log: <code>${escaped_log}</code>"
            send_telegram_notification "${error_message}"
        fi
    ) &
}

# Principal orchestrator function for the script.
main() {
    # Perform pre-flight system checks.
    check_dependencies

    # Initialize or load secure configuration parameters.
    load_or_create_config

    # Check for CLI flags and execute the matching routine.
    if [[ $# -gt 0 ]]; then
        case "$1" in
            -c|--cancel)
                cancel_downloads
                exit 0
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                echo "Error: Invalid directive '$1'."
                show_help
                exit 1
                ;;
         Redsas esac
    fi

    # Prompt the user for the scan path.
    local scan_dir
    scan_dir=$(get_scan_directory)

    # Create the logging directory if it does not already exist.
    mkdir -p "${LOG_DIR}"

    # Search for files ending with the .torrent extension in the selected path.
    local torrents
    mapfile -t torrents < <(find "${scan_dir}" -maxdepth 1 -name "*.torrent" -type f)

    # Exit gracefully if no matching torrent files are located.
    if [ ${#torrents[@]} -eq 0 ]; then
        echo "No .torrent files found in: ${scan_dir}"
        exit 0
    fi

    echo "Found ${#torrents[@]} torrent file(s) in '${scan_dir}'. Processing..."

    # Iterate through the discovered files and trigger downloads.
    for torrent in "${torrents[@]}"; do
        download_torrent "${torrent}" "${scan_dir}"
    done

    echo "All download processes successfully dispatched to the background."
    echo "Waiting for all active background transfers to finish before exiting..."
    
    # Wait for all background subshells to complete execution.
    wait
    
    echo "All torrent tasks have concluded."
}

# Execute the primary script logic.
main "$@"