#!/bin/sh
set -e

# Author: Daniel Kahn Gillmor <dkg@fifthhorseman.net>

# Emacs has epg mode, which expects a certain behavior from GnuPG.
#
# GnuPG upstream doesn't think that it is a bug to break those
# expectations (see https://dev.gnupg.org/T6481) but we want to avoid
# having those problems in debian.  (see
# https://bugs.debian.org/1071552)

# This test ensures that a simple attempt to send signed, encrypted
# PGP/MIME mail with emacs doesn't break with the current version of
# GnuPG.

WORKDIR="$(mktemp -d)"
mkdir -m 0700 "$WORKDIR/a" "$WORKDIR/b" "$WORKDIR/out"
OUTDIR="${AUTOPKGTEST_ARTIFACTS:-$WORKDIR/out}"

cleanup() {
    find "$WORKDIR/out" -type f -print0 | xargs --null --no-run-if-empty -- head -v -n100
    printf "Cleaning up working directory '%s'\n" "$WORKDIR"
    rm -rf "$WORKDIR"
}

trap cleanup EXIT

GPG() {
    home=$1
    shift
    gpg --quiet --homedir "$WORKDIR/$home" --batch --pinentry-mode=loopback --passphrase='' --no-tty --status-file="$WORKDIR/status" "$@"
}

GPG a --quick-gen-key "Alice <alice@example.org>"
ALICE_FPR=$(grep  KEY_CREATED "$WORKDIR/status" | cut -f4 -d\ )
GPG b --quick-gen-key "Bob <bob@example.net>"
BOB_FPR=$(grep  KEY_CREATED "$WORKDIR/status" | cut -f4 -d\ )
GPG b --export "Bob <bob@example.net>" | GPG a --import
# Alice certifies Bob's certificate locally so that her GnuPG installation knows it is valid:
GPG a --quick-lsign-key "$BOB_FPR" "Bob <bob@example.net>"

cat > "$WORKDIR/mailscript.el" <<EOF
(let ((user-mail-address "alice@example.org")
      (user-full-name "Alice")
      (mail-host-address "example.com"))
  (message-mail "Bob <bob@example.net>" "this is a test")
  (message-goto-body)
  (insert "we need to see whether easypg can handle encryption (see https://dev.gnupg.org/T6481)")
  (mml-secure-message-sign-encrypt)
  (let ((mml-secure-openpgp-sign-with-sender t)
        (message-send-mail-function (lambda () (write-region nil nil "sample.eml"))))
    (message-send-and-exit))
)
EOF

# emacs message mode is chatty to stderr even on success, so we store it to keep autopkgtest happy. 
(cd "$WORKDIR" && TERM=dumb GNUPGHOME="$WORKDIR/a" timeout 10s emacs --quick --no-window-system --script mailscript.el 2> "$OUTDIR/stderr")

head -v -n 100 "$OUTDIR/stderr"

cp "$WORKDIR/sample.eml" "$OUTDIR/"

GPG a --output "$OUTDIR/alice.key" --armor --export-secret-key "$ALICE_FPR"
GPG b --output "$OUTDIR/bob.key" --armor --export-secret-key "$BOB_FPR"
