#!/bin/sh
# $Id: kcrm-learn,v 1.5 2018/12/02 22:32:01 karl Exp $
# CRM training --good|--spam FILE
# Splits into maildir files.
# Must be run in directory with mailreaver.crm,
# so files must (in practice) be absolute.
# (Or could use crm --fileprefix.)

renice 20 $$ >/dev/null 2>&1

origdir=`pwd`
cd $HOME/.crm || exit 1

if test ! -s mailreaver.crm; then
  echo "$0: no mailreaver.crm in `pwd`, goodbye." >&2
  exit 1
fi

crmprog=/usr/local/crm/bin/crm
if test ! -x $crmprog; then
  echo "$0: No crm program in $crmprog, goodbye." >&2
  exit 1
fi

how=$1
if test x$how != x--spam && test x$how != x--good; then
  echo "$0: first arg must be --spam or --good, not $how, goodbye." >&2
  exit 1
fi

if echo "$2" | grep ^/ >/dev/null; then
  file=$2
else
  file=$origdir/$2
fi
if test ! -r "$file"; then
  echo "$0: unreadable file $file, goodbye." >&2
  exit 1
fi
if test ! -s "$file"; then
  echo "$0: empty file $file, doing nothing." >&2
  exit 0
fi

if test $# -ne 2; then
  echo "$0: must have exactly two args, not $*, goodbye." >&2
  exit 1
fi
test -s "$file" || exit 0 # empty file, nothing to do

# have to split up (likely, for me) mbox.
maildir=`mktemp -d`
cat "$file" | formail -ds sh -c "cat >$maildir"'/msg.$FILENO'

for f in $maildir/msg.*; do
  $crmprog mailreaver.crm $how <$f
done >>$HOME/.crm/learn$how.out 2>>$HOME/.crm/learn$how.err
rm -rf $maildir
