#!/bin/sh

# sfeed_read
# author: gearsix
# description: sfeed_update; generate $FOUT && xdg-open $FEEDS (xdg-user-dir DOCUMENTS or ~/Documents)
# usage: "sfeed_read [ENGINE]" ENGINE (optional) sets the sfeed_X tool to use (default is sfeed_html)

TIMESTAMP=$(date +%F)
ENGINE=
EXT=
SFEED=
FEEDS=

# determine ENGINE & EXT values
if [ -n "$1" ]; then
	case "$1" in
		"html" | "HTML" | "sfeed_html")
			EXT=".html"
			ENGINE=sfeed_html
			;;
		"atom" | "sfeed_atom")
			EXT=".atom"
			ENGINE=sfeed_atom
			;;
		"plain" | "txt" | "plain-text" | "sfeed_plain")
			EXT=".txt"
			ENGINE=sfeed_plain
			;;
		"frame" | "frames" | "sfeed_frames")
			EXT=".html"
			ENGINE=sfeed_frames
			;;
		"mbox" | "mail" | "mailbox" | "feed_mbox")
			ENGINE=sfeed_mbox
			;;
		"twtxt" | "sfeed_twtxt")
			EXT=".txt"
			ENGINE=sfeed_twtxt
			;;
		"gopher" | "sfeed_gopher")
			EXT=".gopher"
			ENGINE=sfeed_gopher
			;;
		*)
			echo "invalid ENGINE \"$1\""
			printf "\nsfeed_read [ENGINE]\n\n"
			echo "ENGINE:"
			echo " html, HTML, sfeed_html"
			echo " atom, sfeed_atom"
			echo " plain, txt, plain-text, sfeed_plain"
			echo " frame, frames, sfeed_frames"
			echo " mbox, mail, mailbox, sfeed_mbox"
			echo " twtxt, sfeed_twtxt"
			echo "gopher, sfeed_gopher"
			exit
			;;
	esac
else
	EXT=".html"
	ENGINE=sfeed_html
fi

# determine SFEED location
SFEED=~/.sfeed/feeds
if [ -n "$SFEED" ]; then SFEED=$SFEED; fi

# determine FEEDS location
if [ -n "$FEEDS" ]; then
	FEEDS=$FEEDS
elif [ -n "$(command -v xdg-user-dir)" ]; then
	FEEDS=$(xdg-user-dir DOCUMENTS)/feeds
else
	FEEDS=~/Documents/feeds
fi
if [ -n "$(dirname $FEEDS)" ]; then mkdir -pv $FEEDS; fi

# main actions
sfeed_update
$ENGINE $SFEED/* > "$FEEDS/$TIMESTAMP$EXT"
xopen "$FEEDS/$TIMESTAMP$EXT"
