#!/bin/bash
set -eo pipefail
# This is a quick prototype to see if a simple blog facility is of
# interest, or can be made of interest.  Some improvements that can
# be made:
# - make it not fail when run the first time on a new host (no such file)
# - pull posts from URLs listed in $HOME/blogsuchin/subscriptions/*,
#   mirroring them locally, permitting post sharing over HTTP
# - strip out most control characters to prevent obnoxious markup
# - get rid of "xargs: more: terminated by signal 13" error
# - format output without two entire lines of colons around each message-ID
# - abbreviate SHA-256 message-IDs
# - validate the SHA256 of each post
# - only prompt you for a post if you are a tty ([ -t 0 ])
# - add hashcash to each post to support prioritization in aggregators
# - add read tracking so you can see unread posts
# - filter posts by hashtags, make replies cite original message-ID

bn=$(basename "$0")
base=~/blogsuchin            # Blogsuchin directory
nomotd=~/.blogsuchin_nomotd  # File that disables blogsuchin motd
posting=false                # Are we going to post?
reading=true                 # Are we going to display the blog?
full=false                   # If so, the *whole* blog?
motd=false                   # Are we just displaying the motd?

usage() {
    echo "Usage: $bn [-q] [-v] [post|motd|on|off]" >&2
    exit 1
}

motdsetup() {
    if [ -e "$nomotd" ]; then exit 0; fi
    posting=false
    reading=true
    motd=true
}

enable_motd() {
    rm -f "$nomotd"
    echo "'$bn motd' will show recent posts."
    exit 0
}

disable_motd() {
    touch "$nomotd"
    echo "'$bn motd' will not show recent posts."
    echo "Type '$bn on' to enable, '$bn' to see them."
    exit 0
}

while [ $# -gt 0 ] ; do
    arg=$1
    shift
    case "$arg" in
	help) usage ;;
	-h) usage ;;
        -v) full=true ;;
	-q) reading=false ;;
        post) posting=true ;;
	motd) if $posting; then usage; else motdsetup; fi ;;
	on) enable_motd ;;
	off) disable_motd ;;
        *) usage ;;
    esac
done


if $reading ; then
    ls -t /home/*/blogsuchin/posts/*/* | 
    if $full; then
        (xargs more ||:) | ${PAGER-less}
    else
        head | (xargs more 2>/dev/null ||:) | head -16
    fi
fi

if $posting ; then
    mkdir -p "$base"/posts
    echo -n "Subject: "
    read subject
    echo "Hit ^D when your message is done."
    nf="$base"/newpost."$$"
    (echo "From $(whoami) on $(date): $subject"; echo; cat) > "$nf"
    hd=$(< "$nf" openssl sha256 | awk '{print $2}')
    dir=$base/posts/$(echo "$hd" | head -c 2)
    basename=$(echo "$hd" | tail -c +3)
    mkdir -p "$dir"
    mv "$nf" "$dir"/"$basename"
    echo "Posted as $dir/$basename."
else
    echo -n "Type "
    if $motd ; then echo -n "'$bn off' to disable, "; fi
    echo "'$bn post' to post, '$bn -v' to read more."
fi
