#!/bin/sh
# mblaze.env
# Written in 2020 by Lucas
# CC0 1.0 Universal/Public domain - No rights reserved
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty. You should have received a copy of the CC0 Public Domain
# Dedication along with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

usage()
{
	cat - <<. >&2
Usage:
	${0##*/} f|fetch
	${0##*/} l|list [dirs...]
	${0##*/} r|read dir [dirs...]
	${0##*/} s|scan [-a] dir [dirs...]
.
	exit 1
}

_mlist_i_rec_ln()
{
	if [ $# -eq 4 ]; then
		printf "%6d unseen  %3d flagged  %6d msg  %s\n" "$@"
	else
		printf "%6d unseen  %3d flagged  %6d msg\n" "$@"
	fi
}

_mlist_i_rec()
{
	tuc=0
	tfc=0
	tmc=0
	entries=0
	while IFS= read -r dir; do
		IFS=" " read -r uc ut fc ft mc mt dummy <<EOF
$(mdirs "$dir" | mlist -i | tail -n 1)
EOF
		_mlist_i_rec_ln "$uc" "$fc" "$mc" "$dir"
		tuc=$((tuc + uc))
		tfc=$((tfc + fc))
		tmc=$((tmc + mc))
		entries=$((entries + 1))
	done
	if [ $entries -gt 1 ]; then
		_mlist_i_rec_ln "$tuc" "$tfc" "$tmc"
	fi
}

m_fetch_usage()
{
	printf "Usage: %s f|fetch\n" "${0##*/}" >&2
	exit 1
}

m_read_usage()
{
	printf "Usage: %s r|read dir [dirs...]\n" "${0##*/}" >&2
	exit 1
}

m_scan_usage()
{
	printf "Usage: %s s|scan [-a] dir [dirs...]\n" "${0##*/}" >&2
	exit 1
}

m_fetch()
{
	if [ $# -ne 0 ]; then
		m_fetch_usage
	fi
	printf "%s: fetch TBD.\n" >&2
	exit 1
}

m_list()
{
	pwd=$(pwd)
	# cut(1) lists are 1-based, and +1 for leading slash
	pwd_offset=$((${#pwd} + 2))
	if [ $# -eq 0 ] && [ -n "$M_LIST_PATH" ]; then
		oldIFS=$IFS
		IFS=:
		set -- $M_LIST_PATH
		IFS=$oldIFS

		printf "%s\n" "$@" | sort -t / | cut -c $pwd_offset- |
		    _mlist_i_rec
	else
		mdirs "${@:-.}" | sort -t / | cut -c $pwd_offset- | mlist -i
	fi
}

m_read()
{
	if [ $# -eq 0 ]; then
		m_read_usage
	fi

	mdirs "$@" | mlist -s | msort -d | mthread | mless
}

m_scan()
{
	mlist_flags=-s
	while getopts a flag; do
		case $flag in
		a)
			mlist_flags=
			;;
		*)
			m_scan_usage
			;;
		esac
	done
	shift $(($OPTIND - 1))

	if [ $# -eq 0 ]; then
		m_scan_usage
	fi

	mdirs "$@" | mlist $mlist_flags | msort -d | mthread | mseq -S | mscan
}

if [ $# -lt 1 ]; then
	usage
fi
cmd=$1
shift

case $cmd in
f|fetch)
	m_fetch "$@"
	;;
l|list)
	m_list "$@"
	;;
r|read)
	m_read "$@"
	;;
s|scan)
	m_scan "$@"
	;;
*)
	usage
	;;
esac
