#!/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="[-c X] [sender regex]"
DEFAULT_COUNT=9

# shellcheck disable=SC2317,SC2329
function extra_usage() {
    cat << EOF
    -c|--count X                   Max mails count to display (default: $DEFAULT_COUNT)
EOF
}

SENDER_REGEX=
# shellcheck disable=SC2317,SC2329
function handle_extra_args() {
    local idx=1 opt
    while [[ $idx -le $# ]]; do
        opt=${!idx}
        case "$opt" in
            -c|--count)
                ((idx++))
                COUNT="${!idx}"
                check_int "$COUNT" 1 || usage "Invalid count parameter: must be an integer >= 1"
            ;;
            *)
                if [[ -z "$SENDER_REGEX" ]]; then
                    SENDER_REGEX="$opt"
                else
                    usage "Invalid parameter '$opt'"
                fi
        esac
        ((idx++))
    done
}
handle_args "$@"
[[ -z "$SENDER_REGEX" ]] && usage
[[ "${COUNT:-null}" == "null" ]] && COUNT=$DEFAULT_COUNT

mapfile -t IDS < <( run_other_tool eemailq --output-data id --sender-regex "$SENDER_REGEX" --limit "$COUNT" )
if [[ ${#IDS[@]} -eq 0 ]]; then
    info "No email found with sender pattern '$SENDER_REGEX'"
    exit 0
fi
run_other_tool view_mail "${IDS[@]}"
