# file      : tests/client.testscript
# copyright : Copyright (c) 2014-2019 Code Synthesis Ltd
# license   : MIT; see accompanying LICENSE file

test.arguments += rsautl -sign -keyform engine -engine pkcs11

: args
:
{
  : none
  :
  $* 2>'error: -inkey option is required' != 0

  : no-sock
  :
  env --unset=OPENSSL_AGENT_PKCS11_SOCK - $* -inkey 'pkcs11:' 2>>EOE != 0
    error: OPENSSL_AGENT_PKCS11_SOCK environment variable is not set
    EOE
}

: pkcs11
:
{
  +sed -e 's/-client$/-agent-pkcs11/' <"$0" | set agent

  : communication
  :
  {
    # Start the agent.
    #
    +$agent --simulate success 'pkcs11:?pin-value=123123' | set script

    +sed -n -e 's/^OPENSSL_AGENT_PKCS11_PID=(.+);.+$/\1/p' <"$script" | set pid
    +sed -n -e 's/^OPENSSL_AGENT_PKCS11_SOCK=(.+);.+;$/\1/p' <"$script" | set sock

    sign = env - OPENSSL_AGENT_PKCS11_SOCK="$sock" $*

    : sign
    :
    {
      $sign --simulate success -inkey 'pkcs11:' >'signature' : simulate-opt
      $sign                    -inkey 'pkcs11:' >'signature' : no-simulate-opt
    }

    : failure
    :
    {
      $sign --simulate failure -inkey 'pkcs11:' 2>>EOE != 0
        error: unable to sign using simulated private key
        EOE
    }

    : wrong-key
    :
    {
      $sign --simulate success -inkey 'pkcs11:object=key' 2>>EOE != 0
        error: private key doesn't match
        EOE
    }

    # Stop the agent.
    #
    -kill "$pid"
  }
}