#!/bin/sh
OUTPUT_FILE="/home/aaron/nginx/rss/data/eztv-filtered-feed.xml"
TEMP_FILE="/tmp/eztv-combined-feed.xml.tmp"
FEEDS_FILE="/opt/rss-filter/eztv-feeds.txt"
LOG_DIR="/var/log/rss"
LOG_FILE="$LOG_DIR/rss-eztv-$(date '+%Y%m%d-%H%M%S').log"

# -----------------------------------------------
# Patterns to match against item titles (grep -E)
# An item is kept if its title matches ANY pattern
# -----------------------------------------------
PATTERNS="
1080p HEVC x265-MeGusta
"

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Start RSS feed
cat > "$TEMP_FILE" << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Combined RSS Feed</title>
    <description>Filtered RSS feed</description>
    <link>http://localhost</link>
EOF
echo "    <lastBuildDate>$(date -R)</lastBuildDate>" >> "$TEMP_FILE"

# Process each feed URL
while IFS= read -r url || [ -n "$url" ]; do
  [ -z "$url" ] && continue
  echo "$url" | grep -q "^#" && continue

  log "Fetching: $url"

  FEED_CONTENT=$(curl -sf --max-time 30 "$url" 2>/dev/null)

  if [ $? -eq 0 ] && [ -n "$FEED_CONTENT" ]; then
    echo "$FEED_CONTENT" | grep -v '<[a-zA-Z0-9_-]*:' | awk -v patterns="$PATTERNS" '
      /<item>/ { in_item=1; buf="" }
      in_item  { buf = buf $0 "\n" }
      /<\/item>/ {
        in_item=0
        title = buf
        gsub(/.*<title>/, "", title)
        gsub(/<\/title>.*/, "", title)
        n = split(patterns, pats, "\n")
        for (i=1; i<=n; i++) {
          if (pats[i] != "" && tolower(title) ~ tolower(pats[i])) {
            printf "%s", buf
            break
          }
        }
      }
    ' >> "$TEMP_FILE"
  else
    log "Failed to fetch: $url"
  fi

  sleep 2

done < "$FEEDS_FILE"

# Close RSS feed
cat >> "$TEMP_FILE" << 'EOF'
  </channel>
</rss>
EOF

mv -f "$TEMP_FILE" "$OUTPUT_FILE"
log "RSS aggregation complete: $OUTPUT_FILE"
