set quiet

conf:="config.rec"
email:="pooper@bigpoop.com"

# list all recipes
default:
  just --list --unsorted

# add new book
new:
  #!/usr/bin/env sh
  read -p "Title: " title
  read -p "File: " file
  recins {{conf}} -t doc -f title -v "$title" -f file -v "$file"
alias n:= new

# process books
process:
  #!/usr/bin/env sh
  WPM=240
  recs=$(recsel {{conf}} -c)
  for rec in $(seq 0 $(($recs - 1)))
  do
    deliver=$(recsel {{conf}} -P delivery -n "$rec" | jq --arg today $(gdate +'%A') 'any(. == $today))
    if ! $deliver; then continue; fi
    idx=$(recsel {{conf}} -P progress -n "$rec")
    minutes=$(recsel {{conf}} -P minutes -n "$rec")
    words=$((minutes * WPM))
    file=$(recsel {{conf}} -P file -n "$rec")
    title=$(recsel {{conf}} -P title -n "$rec")
    author=$(recsel {{conf}} -P author -n "$rec")
    iter=$(recsel {{conf}} -P iter -n "$rec")
    awk -v start="$idx" -v rec="$rec" -v title="$title" -v author="$author" -v iter="$iter" 'BEGIN {
      RS="\n\n"; ORS="\n\n"; Limit=1200
    }
    NR >= start && total < Limit {
      out = out "\n\n" $0;
      total = total + NF; par = NR; 
    }
    END {
      cmd = "recset {{conf}} -n " rec " -f progress -s " par + 1;
      cmd | getline
      print out
    }' "$file" \
    | mail -s "$title, by $author Part $iter" {{email}}
    recset {{conf}} -n "$rec" -f iter -s $((iter + 1))
    recset {{conf}} -n "$rec" -f updated -s $(gdate -I)
  done
