#!/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="[username]"
USERNAME=
# shellcheck disable=SC2317,SC2329
function handle_extra_args() {
    USERNAME="$1"
}
handle_args "$@"
[[ -z "$USERNAME" ]] && usage

echo "Search deferred mail from user $USERNAME ..."
mapfile -t IDS < <( JUST_TRY=0 run_other_tool username_to_deferred_mailid "$USERNAME" )
if [[ ${#IDS[@]} -eq 0 ]]; then
    echo "No email found with username '$USERNAME'"
    exit 0
fi

echo "${#IDS[@]} email(s) with username '$USERNAME'"

for ID in "${IDS[@]}"; do
    # shellcheck disable=SC2016
    SENDER=$( run_other_tool eemailq --id "$ID" -X '${sender}' )
    [ -z "$SENDER" ] && SENDER="Unknown sender"
    while true; do
        echo -n "$ID [$SENDER] : (v = view mail / c = cat mail / d = delete mail / K = keap 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
            ;;
            k|"")
                break
            ;;
            q)
                exit 0
            ;;
            *)
                echo "Bad choice !"
        esac
    done
done
