#!/usr/bin/env bash
set -euo pipefail

orig_args=("$@")
new_args=()
for arg in "${orig_args[@]}"; do
  case "$arg" in
    --no-tty|--fixed-list-mode|--batch) ;;
    *) new_args+=("$arg") ;;
  esac
done

exec 3>&1

translator() {
  local translator_failed=0
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      "Verification result: RESULT_NO_SIGNATURE") echo "[GNUPG:] NO_SIG" >&2; translator_failed=1 ;;
      "Verification result: RESULT_GOOD") echo "[GNUPG:] GOODSIG UNKNOWN_KEYID" >&2 ;;
      "Verification result: RESULT_BAD") echo "[GNUPG:] BADSIG UNKNOWN_KEYID" >&2; translator_failed=1 ;;
      "Verification result: RESULT_EXPIRED") echo "[GNUPG:] EXPSIG UNKNOWN_KEYID" >&2; translator_failed=1 ;;
      "Verification result: RESULT_REVOKED") echo "[GNUPG:] REVOKED UNKNOWN_KEYID" >&2; translator_failed=1 ;;
      "Decryption result: RESULT_ENCRYPTED") echo "[GNUPG:] DECRYPTION_OKAY" >&2 ;;
      "Decryption result: RESULT_MDC_OK") echo "[GNUPG:] GOODMDC" >&2 ;;
      "Decryption result: RESULT_FAIL") echo "[GNUPG:] DECRYPTION_FAILED" >&2; translator_failed=1 ;;
      "Decryption result: RESULT_NO_MDC") echo "[GNUPG:] BADMDC" >&2; translator_failed=1 ;;
      *) echo "$line" >&2 ;;
    esac
  done
  return $translator_failed
}

coproc { translator; }

okc-gpg "${new_args[@]}" 2>&"${COPROC[1]}" 1>&3
gpg_exit=$?

exec {COPROC[1]}>&-

wait $COPROC_PID
translator_exit=$?

if [ "$translator_exit" -ne 0 ]; then
  exit 1
else
  exit "$gpg_exit"
fi
