#!/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
handle_args "$@"

mapfile -t SENDERS < <( JUST_TRY=0 run_other_tool top_senders )
if [[ ${#SENDERS[@]} -eq 0 ]]; then
    echo "No email found in mailq"
    exit 0
fi

IFS=$'\n'
for line in "${SENDERS[@]}"; do
    count=$( echo "$line" | awk '{print $1}' )
    mail=$( echo "$line" | awk '{print $2}' )
    while true; do
        echo -n "-> $mail ($count mails) (I = inspect 10 last mail from / i = inspect mail from / d = delete mail from / k = keep / q = quit ) ? "
        read -r a
        case $a in
            I)
                JUST_TRY=0 run_other_tool view_mails_from_sender "$mail"
            ;;
            i)
                JUST_TRY=0 run_other_tool inspect_mail_from_sender "$mail"
            ;;
            d)
                run_other_tool drop_mail_from "$mail"
                break
            ;;
            k|"")
                break
            ;;
            q)
                exit 0
            ;;
            *)
                echo "Bad choice !"
        esac
    done
done
