#!@zsh@/bin/zsh

set -xe

function notmuch {
    NOTMUCH_TCP=${NOTMUCH_TCP:-2011} @notmuchtcp@/bin/notmuch-tcp ${@}
}

function browser {
    ${BROWSER:-firefox} ${@}
}

maxCount=0
if [[ -n "$1" && "$1" == <-> ]]; then
    maxCount="$1"
fi

count=0
for thread (${(z)$(notmuch search --sort=oldest-first 'tag:inbox AND is:link AND is:unread AND NOT (is:killed or tag:later)' | @coreutils@/bin/tee >(cat >&2) | @gawk@/bin/awk '{ print $1; }')}); do
    url=$(notmuch show --format=mbox $thread | @gnused@/bin/sed -r '/^X-RSS-URL: /!d; s/^X-RSS-URL: (.*)$/\1/')
    count=$((count + 1))

    if [[ -n "${url}" ]]; then
      browser ${url} && notmuch tag -unread -inbox -- $thread
    fi

    if [[ ${maxCount} -gt 0 && ${count} -ge ${maxCount} ]]; then
        exit 0
    fi
done