#!/usr/bin/env bash
# qBittorrent external-program-on-event hook template.
#
# Install via qBittorrent UI:
#   Tools → Options → Downloads → "Run external program on torrent finished"
#
# Set the command to:
#   /path/to/qbit-hook-template.sh completed "%I" "%N" "%G" "%T" "%F"
#
# qBittorrent macros (most useful subset):
#   %I  info_hash
#   %N  torrent name
#   %G  tags
#   %T  current tracker
#   %F  content path
#   %D  save path
#   %L  category
#
# Configure CC_WEBHOOK_URL and CC_WEBHOOK_TOKEN below (or set them as env
# vars in the qBittorrent launch environment).

set -euo pipefail

CC_WEBHOOK_URL="${CC_WEBHOOK_URL:-https://127.0.0.1:8443/webhook/qbit/qbit-default}"
CC_WEBHOOK_TOKEN="${CC_WEBHOOK_TOKEN:-PUT-TOKEN-HERE}"

KIND="${1:-completed}"
INFO_HASH="${2:-}"
NAME="${3:-}"
TAGS="${4:-}"
TRACKER="${5:-}"
CONTENT_PATH="${6:-}"

# JSON-escape via jq if available, otherwise a small awk filter.
escape() {
  if command -v jq >/dev/null 2>&1; then
    printf '%s' "$1" | jq -Rs .
  else
    printf '%s' "$1" | awk 'BEGIN{ORS=""}{gsub(/\\/,"\\\\");gsub(/"/,"\\\"");gsub(/\n/,"\\n");print}' | sed 's/^/"/; s/$/"/'
  fi
}

BODY=$(cat <<EOF
{
  "kind": $(escape "$KIND"),
  "info_hash": $(escape "$INFO_HASH"),
  "name": $(escape "$NAME"),
  "tags": $(escape "$TAGS"),
  "tracker": $(escape "$TRACKER"),
  "save_path": $(escape "$CONTENT_PATH")
}
EOF
)

curl -sS -m 10 \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Token: $CC_WEBHOOK_TOKEN" \
  --data-raw "$BODY" \
  "$CC_WEBHOOK_URL" >/dev/null || true
