#!/bin/bash

# Move old chores from plan.txt to past.txt,
# then show plan.txt.
# This is like the previous chores.sh, but with automatic archiving.
# Requires date, test, expr, and sed.
# BUG: Some versions of the date command do not do arithmetic.

unset LIMITER BEYOND STARTER ENDER

if date -d"1 days" &>/dev/null
then # echo OK
  USAGE="archive.sh [[-]n|startdate]"
else # echo NO
  USAGE="archive.sh [startdate]"
fi

# Return true iff the first date is less than or equal to the second.
inorder() {
  if [ $# -lt 2 ]; then return 0; fi
  _CD_DATE_1=$1
  _CD_DATE_2=$2
  _CD_YR_1=`echo ${_CD_DATE_1} | sed 's/-.*//'`
  _CD_YR_2=`echo ${_CD_DATE_2} | sed 's/-.*//'`
  if [ ${_CD_YR_1} -lt ${_CD_YR_2} ]; then return 0;
  elif [ ${_CD_YR_1} -gt ${_CD_YR_2} ]; then return 1;
  fi
  _CD_MO_1=`echo ${_CD_DATE_1} | sed 's/^[^-]*-//' | sed 's/-.*//'`
  _CD_MO_2=`echo ${_CD_DATE_2} | sed 's/^[^-]*-//' | sed 's/-.*//'`
  if [ ${_CD_MO_1} -lt ${_CD_MO_2} ]; then return 0;
  elif [ ${_CD_MO_1} -gt ${_CD_MO_2} ]; then return 1;
  fi
  _CD_DA_1=`echo ${_CD_DATE_1} | sed 's/^.*-//'`
  _CD_DA_2=`echo ${_CD_DATE_2} | sed 's/^.*-//'`
  if [ ${_CD_DA_1} -lt ${_CD_DA_2} ]; then return 0;
  elif [ ${_CD_DA_1} -gt ${_CD_DA_2} ]; then return 1;
  fi
  return 0
}

DATESPEC="+%Y-%m-%d"
TODAY=`date ${DATESPEC}`
if [ 1 -eq $# ]
then
  LIMITER=$1
  case $LIMITER in
  -[0-9]* )
    # Start $LIMITER days ago.
    if STARTER=`date ${DATESPEC} -d"${LIMITER} days" 2>/dev/null`
    then :
    else echo usage: $USAGE 1>&2; return 1
    fi
    ;;
  20[0-9]* )
    # Start on the given date.
    STARTER=$LIMITER
    ;;
  [0-9]* )
    # End $LIMITER days from now.
    LIMITER=`expr $LIMITER + 1`
    if BEYOND=`date ${DATESPEC} -d"${LIMITER} days" 2>/dev/null`
    then :
    else echo usage: $USAGE 1>&2; return 1
    fi
    ;;
  * )
    echo usage: $USAGE 1>&2; return 1
    ;;
  esac
fi

if [ 1 -lt $# ]; then echo usage: $USAGE 1>&2; return 2; fi

#echo from ${STARTER:=$TODAY} until before ${BEYOND:=never}

mv plan.txt plan.bak.txt

{

  # First handle the past.
  while read THEDATE TWO LINE
  do
  # if [ "$THEDATE" = "${STARTER:=$TODAY}" ]; then echo $THEDATE $LINE; break; fi
    if inorder "${STARTER:=$TODAY}" "$THEDATE"; then echo $THEDATE $TWO $LINE >>plan.txt; break; fi
    case $TWO in
     A | B | C ) echo $THEDATE $TWO $LINE >>plan.txt ;;
     * ) echo $THEDATE $TWO $LINE >>past.txt ;;
    esac
  done

  # Then handle the present and future.
  while read THEDATE LINE
  do
    if [ "$THEDATE" = "${BEYOND:=never}" ]; then break; fi
    echo $THEDATE $LINE >>plan.txt
  done

} <plan.bak.txt

clear
cat plan.txt
return 0

