#!/bin/bash

CURDIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
TMP=/tmp/status
source "$TMP"

# If offline mode, do a quick sync
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

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

# 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
echo "[DEBUG] Tag mails in in INBOX folder"
notmuch tag +inbox -- path:INBOX/**

# 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

# 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

echo "[DEBUG] poll.sh exited successfully"
