#!/usr/bin/env bash

set -e
function die() {
    echo Error: "$@"
    exit -1
}

mkdir -p ~/.cache/system-config/weekly
cd ~/.cache/system-config/weekly
if test -e .weeklyrc; then
    . .weeklyrc
fi

friday=Fri
monday="Last Mon"

if test "$(today-weekday)" != Friday; then
    friday="last fri"
fi

if test $# = 1; then
    monday="$monday $1"
fi

monday=$(today "$monday")
friday=$(today "$friday")

bhj_page=$PWD/bhj_$(date +%Y.%m.%d -d "$friday")
set -x
do_overwrite=false
if test -e $bhj_page; then
    yes-or-no-p "overwrite existing $bhj_page?" && do_overwrite=true
fi

function separate() {
    perl -a -F: -npe 'if ($F[0] ne $saved_f0) {print "\n"; $saved_f0 = $F[0]}'
}

{ test $do_overwrite = true || ! test -e $bhj_page; }  && (
    echo 本周：
    emacsclient -e "$(bash do-weekly.help '+CLOSED>=\"['$monday']\"' $bhj_page.1)" >/dev/null 2>&1
    cat $bhj_page.1 | separate
    rm $bhj_page.1

    echo
    echo
    echo 下周（未完成）：

    emacsclient -e "$(bash do-weekly.help '+TODO=\"TODO\"' $bhj_page.1)" >/dev/null 2>&1
    cat $bhj_page.1 | separate
    rm $bhj_page.1
) > $bhj_page

gnus-mailx -s "包昊军周报 （"$monday" - "$friday"）" \
    -c $(for x in ~/external/etc/weekly.receipts/cc/*; do basename "$x,"; done) \
    -t $(for x in ~/external/etc/weekly.receipts/to/*; do basename "$x"; done) \
    -m "$(cat $bhj_page)"
