#!/usr/bin/env bash
set -euo pipefail

TARGET_DIR="${1:-}"
BASE_DIR="/srv/mirror"
WATCH_DIR_BIGLY="$BASE_DIR/.bigly_watch"

if [[ -z "$TARGET_DIR" || ! -d "$TARGET_DIR" ]]; then
    echo "Usage: $0 /path/to/release_folder (e.g. /srv/mirror/2.10.0)"
    exit 1
fi

TRACKERS=(
    "udp://tracker.opentrackr.org:1337/announce"
    "udp://tracker.openbittorrent.com:6969/announce"
    "udp://tracker.torrent.eu.org:451/announce"
    "http://tracker2.postman.i2p/announce"
    "http://opentracker.simp.i2p/a"
    "http://opentracker.skank.i2p/a"
    "http://opentracker.dg2.i2p/a"
    "udp://dht.transmissionbt.com:6881"
    "udp://dht.aelitis.com:6881"
    "udp://router.bittorrent.com:6881"
)
TRACKER_STRING=$(IFS=,; echo "${TRACKERS[*]}")

mkdir -p "$WATCH_DIR_BIGLY"
cd "$BASE_DIR"

echo "🌀 Generating torrents for $TARGET_DIR"
for FILE in "$TARGET_DIR"/*; do
    [[ -f "$FILE" ]] || continue
    case "$FILE" in
        *.sig|*.torrent) continue ;;
    esac

    RELPATH=$(realpath --relative-to="$BASE_DIR" "$FILE")
    OUTPUT="$TARGET_DIR/$(basename "$FILE").torrent"

    echo "📦 Creating torrent for $RELPATH ..."
    mktorrent -a "$TRACKER_STRING" -l 21 -o "$OUTPUT" "$RELPATH"

    cp -f "$OUTPUT" "$WATCH_DIR_BIGLY/"
done

echo "✅ Torrents created and copied to $WATCH_DIR_BIGLY"
