#!/bin/bash
#
# Removes the spam tag from a mail, and moves it back to the INBOX if necessary
#
# $1 = message id

TAG="spam"
DIR_JUNK="INBOX.Junk"
DIR_INBOX="INBOX"
LOG="/home/$USER/.config/astroid/hooks/hook.log"

ID=$1
FILE=$(notmuch search --exclude=false --output=files id:"${ID}")    # get actual file path of MID

if [[ $(notmuch search id:"${ID}" and tag:${TAG}) ]]; then  # only do something if mail is tagged "spam"
  notmuch tag -${TAG} -- id:"${ID}"                         # unspam mail
  echo "[unspam] [SUCCESS] \"${TAG}\" removed from ${ID}" >> $LOG
else
  echo "[unspam] [ERROR] not tagged as \"${TAG}\": ${ID}" >> $LOG
fi

if $(echo ${FILE} | grep -q ${DIR_JUNK}); then              # if mail is in spam dir
  FILE_NEW=$(echo ${FILE} | sed "s|${DIR_JUNK}/|${DIR_INBOX}/|")
  mv "${FILE}" "${FILE_NEW}"                                # move from spamdir to inbox
  echo "[unspam] [SUCCESS] moved ${FILE} to ${FILE_NEW}" >> $LOG
else
  echo "[unspam] [ERROR] not in \"${TAG}\"\'s folder: ${FILE}" >> $LOG
fi
