#!/bin/bash

exname=$(basename $0)

prefix_cmd="
. /etc/shlib

include common
include parse

. ../lib/common

depends compose

"

##
## Mocks
##

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

get_compose_relations() {
    local service="$1"
    printf "%s\0" "${RELATIONS[@]}"
}
export -f get_compose_relations

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

compose() {
    printf "Calling: compose "
    printf "%s " "$*"
    echo
}
export -f compose

yaml_key_val_str() {
    printf "%s: %s" "$1" "$2"
}
export -f yaml_key_val_str

file_put() {
    echo "file_put $1"
    cat - | prefix "  | "
}
export -f file_put

docker() {
    echo "docker" "$@"
    echo stdin:
    cat - | prefix "  | "
}
export -f docker

config-add() {
    echo "config-add"
    echo "$1" | prefix "  | "
}
export -f config-add

mkdir() {
    echo "called: $FUNCNAME $@"  >&2
}
export -f mkdir

setfacl() {
    echo "called: $FUNCNAME $@" >&2
}
export -f setfacl

chgrp() {
    echo "called: $FUNCNAME $@" >&2
}
export -f chgrp

chmod() {
    echo "called: $FUNCNAME $@" >&2
}
export -f chmod


cached_cmd_on_base_image() {
    echo "called: $FUNCNAME $@" >&2
    echo "stdout:" >&2
    echo "<GID>" | prefix " | " >&2
    echo "<GID>"
}
export -f cached_cmd_on_base_image


##
## cert-provider
##


try "
export SERVICE_CONFIGSTORE='\$SERVICE_CONFIGSTORE'
export CONFIGSTORE='\$CONFIGSTORE'
export BASE_SERVICE_NAME='\$BASE_SERVICE_NAME'
export MASTER_TARGET_SERVICE_NAME='\$MASTER_TARGET_SERVICE_NAME'
DOMAIN=www.example.com
DOCKER_SITE_PATH=/var/www/\$DOMAIN
CFG='
ssl:
  foo: |
    a
    b
'
RELATIONS=()
apache_vhost_create" "unknown cert key"
is errlvl 1
is err reg 'Error: .*cert-provider.*'


try "
export SERVICE_CONFIGSTORE='\$SERVICE_CONFIGSTORE'
export CONFIGSTORE='\$CONFIGSTORE'
export DATASTORE='\$DATASTORE'
export BASE_SERVICE_NAME='\$BASE_SERVICE_NAME'
export MASTER_TARGET_SERVICE_NAME='\$MASTER_TARGET_SERVICE_NAME'
DOMAIN=www.example.com
DOCKER_SITE_PATH=/var/www/\$DOMAIN
CFG='
ssl:
  foo: 12
'
RELATIONS=(cert-provider foo a True)
apache_vhost_create" "known cert key"
noerror
is out reg 'Calling: compose .*foo: options: <merge_yaml_str\(.a., .12., )>.*run --service-ports foo.*'
is out part 'config-add
  | services:
  |   $MASTER_TARGET_SERVICE_NAME:
  |     volumes:
  |       - $DATASTORE/foo/etc/letsencrypt:/etc/letsencrypt:ro'