#!/bin/bash

CURDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

SAVEFILE="$CURDIR"/pending.save  # Location of logfile
BASETAG="pend"
UNPENDTAG="unpend"

function pdate {
  DATE=$(date +%y-%m-%d_%H:%M:%S)
  echo "[$DATE]"
}

function debugmsg {
  if ${DEBUG}; then
    echo "$(pdate) $*"
  fi
}

function datediff {
  d1=$(date -d "$1" +%s)
  d2=$(date -d "$2" +%s)
  echo $(( (d1 - d2) / 86400 ))
}


# Load the values from the last run
touch "$SAVEFILE"
# shellcheck source=/dev/null
source "$SAVEFILE"
# Get the current day
CURDATE=$(date +%Y-%m-%d)
# Populate $LASTDATE if empty
if [[ -z "$LASTDATE" ]]; then
  LASTDATE="$CURDATE"
  echo "LASTDATE=$LASTDATE" > "$SAVEFILE"
fi

# Get pending tags
pending_tags=$(notmuch search --output=tags '*' | grep "^$BASETAG")

# Reduce pending dates if current date not last saved date
if [[ "$CURDATE" != "$LASTDATE" ]]; then
  ddiff=$(datediff "$CURDATE" "$LASTDATE")
  for tag in $pending_tags; do
    # Get day element
    day=$(grep -Eo '[0-9]*$' <<< "$tag")

    # Calculate new day for pending tag
    day=$(( day - ddiff ))

    # if new pending days more than 1
    if [[ $day -ge 1 ]]; then
      notmuch tag -"$tag" +"${BASETAG}${day}" -- tag:"$tag"
    # otherwise, delete pending tag and set unpending+unread tag
    else
      notmuch tag -"$tag" +"$UNPENDTAG" +unread -- tag:"$tag"
    fi
  done

  # Write the current date in the file
  sed -i "s/LASTDATE\=.*/LASTDATE=$CURDATE/" "$SAVEFILE"
fi
