#!/usr/bin/env bash
#
# Armbian torrents seed script
#
# This script will download Armbian torrent files and add them to a qBittorrent
# instance. It's intended to be run under /etc/cron.weekly.
#
# Based on https://docs.armbian.com/Community_Torrent/

set -euo pipefail

# Dependency check
missing_deps=()
for bin in "wget" "unzip" "jq" "parallel" "qbt"; do
    if ! test -x "$(command -v $bin)"; then
        missing_deps+=("$bin")
    fi
done

if (( "${#missing_deps[@]}" != 0 )); then
    echo "Missing dependencies:" "${missing_deps[@]}"
    exit
fi

TEMP_DIR=$(mktemp -d || echo "Failed to make temp dir; exit 1")
chmod 700 "${TEMP_DIR}"
trap 'rm -rf "${TEMP_DIR}" ; exit 0' 0 1 2 3 15

wget -qO- -O "${TEMP_DIR}/armbian-torrents.zip" https://dl.armbian.com/torrent/all-torrents.zip

# Test zip file for corruption
if ! unzip -t "${TEMP_DIR}/armbian-torrents.zip" >/dev/null 2>&1; then
    echo "Error in armbian-torrents.zip"
    exit
fi

# Extract torrent files from zip
unzip -o "${TEMP_DIR}/armbian-torrents.zip" -d "${TEMP_DIR}/torrent-tmp" >/dev/null 2>&1

# Get list of Armbian torrents active on qBittorrent instance
active_torrents=$(qbt torrent list -F json | jq '.[].hash' | tr -d '"')

# Remove active old Armbian torrents to make room for new/updated ones
echo "$active_torrents" | parallel 'qbt torrent delete -f {}'

# Add new/updated Armbian torrent files
new_torrents=$(find "${TEMP_DIR}/torrent-tmp" -type f -name "*.torrent")
echo "$new_torrents" | parallel 'qbt torrent add file {}'

exit 0