#!/bin/sh
#
# Usage: fetchnews [FILE]
# Saves in maildir posts from RSS/Atom feeds listed in FILE (~/.news by default).
# Depends on curl, sfeed, mblaze, moreutils' ifne, and UNIX utils (grep, awk, etc).
#
# © 2025 Lucas de Sena <lucas at seninha dot org>.  No rights reserved.
# THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY (Works On My Machine).

usage() {
	printf "usage: %s [file]\n" "${0##*/}" >&2
	exit 2
}

err() {
	fmt="$1"
	shift
	printf "%s: $fmt\n" "${0##*/}" "$@" >&2
	exit 1
}

info() {
	printf "$@" >&2
}

test "$#" -le 1 || usage

newsdir="${NEWSDIR:-$HOME/var/news}"
newsfile="${1:-$HOME/.news}"
newstime=0

test -r "$newsfile" || err "could not read news file"
mmkdir "$newsdir" || err "could not make news mail box"
test -r "$newsdir/newstime" && newstime="$(stat -f %m "$newsdir/newstime")"
case "$newstime" in (*[!0-9]*) err "could not get time of last update" ;; esac
touch "$newsdir/newstime"

grep -E -v '^[[:space:]]*(#.*)?$' <"${newsfile}" | while read -r source url
do
	info '%s: ' "$source"
	case "$url" in
	("")
		echo "could not fetch from this source (no url given)"
		continue
		;;
	(*)
		postfilter="sfeed"
		;;
	esac
	{
		curl --location --silent --show-error --http1.1 --fail \
		--connect-timeout 8 --max-filesize 10M "$url" && \
		info "OK\n"
	} | {
		"$postfilter" "${url%%/*}" |\
		awk -v newstime="$newstime" -v author="$source" '
		BEGIN {
			FS = OFS = "\t"
		}
		$1 >= newstime {
			if ($7 ~ /^[[:space:]]*$/)
				$7 = author
			print
		}' |\
		SFEED_MBOX_CONTENT=1 sfeed_mbox |\
		mdeliver -M "$newsdir" 2>/dev/null
	} 2>&1 >/dev/null
done
exit 0
