#!/bin/bash
# vim: shiftwidth=4 tabstop=4 expandtab

LIB_DIR="$( realpath "$( dirname "$( realpath "$0" )" )/../lib/ee-postfix-tools" )"
if [[ -e "$LIB_DIR/common" ]]; then
    # shellcheck source=/dev/null
    source "$LIB_DIR/common"
else
    echo "Failed to load ee-postfix-tools common lib"
    exit 1
fi

# shellcheck disable=SC2034
EXTRA_SHORT_USAGE="[sender regex]"
SENDER_REGEX=
# shellcheck disable=SC2317,SC2329
function handle_extra_args() {
    SENDER_REGEX="$1"
}
handle_args "$@"
[[ -z "$SENDER_REGEX" ]] && usage

mapfile -t IDS < <( JUST_TRY=0 run_other_tool mail_from_sender "$SENDER_REGEX" )
if [[ ${#IDS[@]} -eq 0 ]]; then
    echo "No email found with sender pattern '$SENDER_REGEX'"
    exit 0
fi

echo "${#IDS[@]} email(s) found sender pattern '$SENDER_REGEX'"

for ID in "${IDS[@]}"; do
    # shellcheck disable=SC2016
    SUBJECT=$( JUST_TRY=0 run_postfix_command postcat -qh "$ID" | grep -Ei '^Subject:' )
    [[ -z "$SUBJECT" ]] && SUBJECT="Subject: [no subject header found]"
    while true; do
        echo "$SUBJECT"
        echo -n "$ID : (v = view mail / c = cat mail / d = delete mail / u = search username used to send this mail / k = keep mail / q = quit ) ? "
        read -r a
        case $a in
            v)
                JUST_TRY=0 run_other_tool view_mail "$ID"
            ;;
            c)
                JUST_TRY=0 run_postfix_command postcat -q "$ID" | less
            ;;
            d)
                run_postfix_command postsuper -d "$ID"
                break
            ;;
            u)
                JUST_TRY=0 run_other_tool mailid_to_username "$ID"
            ;;
            k|"")
                break
            ;;
            q)
                exit 0
            ;;
            *)
                echo "Bad choice !"
        esac
    done
done
