#!/bin/bash
#
# ---
# see: https://yobibyte.github.io/yr.html

MAX_ITEMS=150
MAX_CHARS=1000
DOWNLOADED_PATH="$HOME/dev/yr/downloaded.txt"
FILTERS_PATH="$HOME/dev/yr/filters.txt"
touch "$DOWNLOADED_PATH"

# filters syntax: URL,type,REGEX
# if * is used for URL, then it is applied to all urls.
# types: title/url/content
# grep will do negative match! E.g. if I hit a find, I will skip an item.

new_hashes=""

match_against_filters() {
  local link="$1"
  local type="$2"

  while IFS=',' read -r feed type regex; do
    if ! echo "$link" | grep -Eq "$regex"; then
      return 1
    fi
  done < <(grep "^\*,${type}" "$FILTERS_PATH")

  while IFS=',' read -r feed type regex; do
    if ! echo "$link" | grep -Eq "$regex"; then
      return 1
    fi
  done < <(grep "${url},${type}" "$FILTERS_PATH")

  return 0
}

url="$1"
mapfile -t items < <(curl -s "$url" | awk 'BEGIN{RS="</(item|entry)>"; ORS=""} NR>0 {
    gsub(/\n/," ");       # replace newlines with spaces
    gsub(/[[:space:]]+/," "); # collapse multiple spaces
    print $0 RS "\n"
}' | head -n $MAX_ITEMS)

for item in "${items[@]}"; do
  link1=$(echo "$item" | grep -oP '<link\b[^>]*>\K.*?(?=</link>)')
  link2=$(echo "$item" | grep -oP '<link\b[^>]*\bhref="\K[^"]+')
  title=$(echo "$item" | grep -oP '<title[^>]*>\K.*?(?=</title>)')

  hash=$(echo -n "${link1}${link2}${title}" | md5sum | awk '{print $1}')
  if ! grep -Fxq "$hash" "$DOWNLOADED_PATH"; then

    content1=$(echo "$item" | grep -oP '<description[^>]*>\K.*?(?=</description>)' | cut -c1-$MAX_CHARS | w3m -T text/html -dump)
    content2=$(echo "$item" | grep -oP '<summary[^>]*>\K.*?(?=</summary>)' | cut -c1-$MAX_CHARS | w3m -T text/html -dump)
    [[ -n $link1 ]] && [[ $(match_against_filters "$link1" "url") -eq 1 ]] && continue
    [[ -n $link2 ]] && [[ $(match_against_filters "$link2" "url") -eq 1 ]] && continue
    [[ -n $title ]] && [[ $(match_against_filters "$title" "title") -eq 1 ]] && continue
    [[ -n $content1 ]] && [[ $(match_against_filters "$content1" "content") -eq 1 ]] && continue
    [[ -n $content2 ]] && [[ $(match_against_filters "$content2" "content") -eq 1 ]] && continue

    echo "--- $1"
    [[ -n $link1 ]] && echo "$link1"
    [[ -n $link2 ]] && echo "$link2"
    [[ -n $title ]] && echo "$title"
    [[ -n $content1 ]] && echo "$content1"
    [[ -n $content2 ]] && echo "$content2"
    echo

    new_hashes+=$'\n'"$hash"

  fi
done

# TODO think on how to clean that file later
{
  flock 9
  printf "%s" "$new_hashes" >&9
} 9>>"$DOWNLOADED_PATH"
