#!/bin/bash

exname=$(basename $0)

prefix_cmd="
. /etc/shlib

include common
include parse

. ../lib/common

"

# mock
relation-get() {
    local key="$1"
    echo "$CFG" | shyaml get-value "$key" 2>/dev/null
}
export -f relation-get

cfg-get-value() {
    local key="$1"
    shyaml get-value "$key" 2>/dev/null
}
export -f cfg-get-value

get_service_relations() {
    printf "%s\0" "${RELATIONS[@]}"
}
export -f get_service_relations

merge_yaml_str() {
    printf "<merge_yaml_str("
    printf "'%s', " "$@"
    printf ")>"
}
export -f merge_yaml_str


export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
trap "rm -rf \"$state_tmpdir\"" EXIT

##
## Tests
##

try "
ssl_get_plugin_fun '
domain: www.example.com
'"
is errlvl 1
is err 'Error: No ssl options available.
'
is out ''



try "
set -o pipefail
ssl_get_plugin_fun '
domain: www.example.com
ssl: true
' | tr '\0' ':'
"
is errlvl 0
is err ''
is out reg '^ssl_fallback:'


try "
ssl_get_plugin_fun '
domain: www.example.com
ssl:
- a
- b
'
"
is errlvl 1
is err part 'please provide a string or a struct'
is out ''


try "
ssl_get_plugin_fun '
domain: www.example.com
ssl:
- a
- b
'
"
is errlvl 1
is err part 'please provide a string or a struct'
is out ''


try "
ssl_get_plugin_fun '
domain: www.example.com
ssl: xxx
'
"
is errlvl 1
is err part 'no corresponding services declared in cert-provider'
is out ''


try "
RELATIONS=(cert-provider xxx mycfg True)
ssl_get_plugin_fun '
domain: www.example.com
ssl: xxx
' | tr '\0' ':'
"
noerror
is out "ssl_plugin_cert-provider:xxx:<merge_yaml_str('mycfg', '', )>:"


try "
RELATIONS=(
cert-provider xxx mycfgxxx True
cert-provider yyy mycfgyyy True
)
ssl_get_plugin_fun '
domain: www.example.com
ssl: yyy
' | tr '\0' ':'
"
noerror
is out "ssl_plugin_cert-provider:yyy:<merge_yaml_str('mycfgyyy', '', )>:"


try "
RELATIONS=(
cert-provider xxx mycfgxxx True
cert-provider yyy mycfgyyy True
)
ssl_get_plugin_fun '
domain: www.example.com
ssl:
  cert: a
' | tr '\0' '|'
"
noerror
is out "ssl_fallback||cert: a|"


try "
RELATIONS=(
cert-provider xxx mycfgxxx True
cert-provider yyy mycfgyyy True
)
ssl_get_plugin_fun '
domain: www.example.com
ssl:
  popo: a
'
"
is errlvl 1
is err part 'no corresponding services declared in cert-provider'
is out ''