#!/bin/bash

start=$(date +%s)

CURDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# Local status file that indicates whether offline mode is activated
# shellcheck source=/dev/null
source "/tmp/status"

# If offline mode, do a quick sync
# shellcheck disable=SC2154
if [ "$var_conn" == "off" ]; then
  echo "[INFO] Offline mode enabled. Do a quick sync"
  offlineimap -q
else
  echo "[INFO] Do a normal sync."
  offlineimap
fi

sync=$(date +%s)

# Index new mails which will be tagged with notmuch's new.tags
echo "[DEBUG] Sync notmuch database with new mails"
notmuch new

# Inbox (first time)
echo "[DEBUG] Tag mails in in INBOX folder"
notmuch tag +inbox -- path:INBOX/**

# Move selectedly tagged mails to folders if they are only in INBOX
echo "[DEBUG] Move tagged mails in INBOX to folders (move-tag.sh)"
bash "$CURDIR"/scripts/move-tag.sh "${var_conn}"

# Index again after mails have been moved
echo "[DEBUG] Update notmuch database with possibly moved mails"
notmuch new

### Sort emails

# Archiv
echo "[DEBUG] Tag mails in offline ARCHIVE folder"
notmuch tag +archive -- path:ARCHIVE/**

# Inbox (2nd time)
echo "[DEBUG] Tag mails in in INBOX folder"
notmuch tag +inbox -- path:INBOX/**

# Tag all tagged events with the general "event" tag
notmuch tag +event -- tag:"/event.*/"

# Automatic tagging based on location of mails in folders
echo "[DEBUG] Tag mails based on their folder (tag-folder.sh)"
bash "$CURDIR"/scripts/tag-folder.sh # generates commands from tag-folder.csv
bash "$CURDIR"/scripts/tag-folder-rules.sh  # executes generated commands

# Handle pending days (tag:/pend*/)
echo "[DEBUG] Handle pending tags (pending.sh)"
bash "$CURDIR"/scripts/pending.sh

# Mark mails in certain folders read
echo "[DEBUG] Mark mails in trash folders read"
notmuch tag -unread -- path:Trash/**
notmuch tag -unread -- path:Trash.ignore-mod/**

# Remove "new" tag
echo "[DEBUG] Remove the 'new' tag"
notmuch tag -new -- tag:new

end=$(date +%s)
echo "[DEBUG] poll.sh exited after $((end-start))s ($((sync-start))s download)"
