#!/bin/bash

set -e

workdir=$(mktemp -d)

cleanup() {
    rm -rf "$workdir"
}
trap cleanup EXIT

setup_gpg() {
    export GNUPGHOME="$workdir/g"
    mkdir -m 0700 -p "$GNUPGHOME"
    gpgargs=(--batch --pinentry-mode=loopback --passphrase '' --quiet --no-tty)

    gpg "${gpgargs[@]}"  --quick-gen-key 'Test User <test@example.org>' futuredefault
}

setup_notmuch() {
    mkdir -p "$workdir/m"
    export NOTMUCH_CONFIG="$workdir/notmuch-config"
    cat > "$NOTMUCH_CONFIG" <<EOF
[database]
path=$workdir/m
[user]
name=Test User
primary_email=test@example.org
[new]
tags=unread;inbox;
EOF
    notmuch new
}

body() {
    cat <<EOF
Content-Type: text/plain

This is test message $1
EOF
}

encmsg() {
    cat <<EOF
From: Test User <test@example.org>
To: Test User <test@example.org>
Date: $(date -R)
Subject: Message $x
Mime-Version: 1.0
Message-Id: <crypto-performance-$x@example.org>
References: <crypto-performance@example.org>
In-Reply-To: <crypto-performance@example.org>
Content-Type: multipart/encrypted;
 boundary="xxxx";
 protocol="application/pgp-encrypted"

--xxxx
Content-Type: application/pgp-encrypted

Version: 1

--xxxx
Content-Type: application/octet-stream

$(body $x | gpg --armor --sign -r test@example.org --encrypt)
--xxxx--
EOF
}

sk() {
    notmuch dump id:"crypto-performance-$1@example.org" | grep session-key= \
        | sed -r -e 's/.*session-key=([A-F0-9%a-f]+)*/\1/' -e 's/%3a/:/'
}

setup_gpg
setup_notmuch
for x in $(seq 1 20); do
    encmsg > "$workdir/m/$x.eml"
done
notmuch new --decrypt=true
printf '\nperformance of notmuch show:'
time notmuch show --format=json id:crypto-performance-1@example.org >/dev/null
printf '\nperformance of piped gpg:'
time for x in $(seq 1 20); do
    notmuch show --entire-thread=false --decrypt=false --format=raw --part=3 id:crypto-performance-$x@example.org \
        | gpg --quiet --batch --override-session-key $(sk $x) --decrypt >/dev/null 2>/dev/null
done
printf '\nperformance of piped gpg --no-keyring:'
time for x in $(seq 1 20); do
    notmuch show --entire-thread=false --decrypt=false --format=raw --part=3 id:crypto-performance-$x@example.org \
        | gpg --quiet --batch --no-keyring --override-session-key $(sk $x) --decrypt >/dev/null 2>/dev/null || true
done
