#!/bin/bash

exname=$(basename $0)

compose_core=$(which compose-core) || {
    echo "Requires compose-core executable to be in \$PATH." >&2
    exit 1
}

fetch-def() {
    local path="$1" fname="$2"
    ( . "$path" 1>&2 || {
          echo "Failed to load '$path'." >&2
          exit 1
      }
      declare -f "$fname"
    )
}


prefix_cmd="
. /etc/shlib

include common
include parse

. ../lib/common

$(fetch-def "$compose_core" yaml_get_values)
$(fetch-def "$compose_core" yaml_get_interpret)

" || {
    echo "Couldn't build prefix cmd" >&2
    exit 1
}


##
## Mocks
##

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

export RELATION_DATA_FILE=x
relation-set() {
    local key="$1" value="$2"
    echo "relation-set $key:" >&2
    echo "$value" | prefix "  | " >&2
}
export -f relation-set

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() {
    local arg_hash="$(H "$@" | cut -c -16)"
    local i
    echo "Calling: merge_yaml_str" >&2
    ((i=0))
    for arg in "$@"; do
        echo "  arg$((i++)):"
        echo "$arg" | prefix "  | "
    done >&2
    echo "  H> $arg_hash" >&2
    while read-0 h res; do
        if [[ "$arg_hash" == "$h" ]]; then
            echo "Mock hash matched, returning:" >&2
            echo "$res" | prefix "  | " >&2
            echo "$res"
            return 0
        fi
    done < <(e "$MERGE_YAML_STR" | shyaml key-values-0)
    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


yaml_get_interpret() {
    shyaml get-value
}
export -f yaml_get_interpret

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

init-config-add() {
    echo "config-add"
    echo "$1" | prefix "  | "
}
export -f init-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


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


##
## 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'
RELATIONS=()
apache_vhost_create publish_dir '
domain: www.example.com
ssl:
  foo: |
    a
    b
'
" "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 SERVICE_NAME='\$SERVICE_NAME'
export BASE_SERVICE_NAME='\$BASE_SERVICE_NAME'
export MASTER_TARGET_SERVICE_NAME='\$MASTER_TARGET_SERVICE_NAME'
CFG='
domain: www.example.com
ssl:
  foo: 12
'
ADDITION='
apache-custom-rules:
  - |
    ## Auto-redirection from http to https
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]'
MERGE_YAML_STR=\"
3e417c2db15450f3: |
\$(echo \"\$CFG\" |  prefix '  ')
\$(echo \"\$ADDITION\" | prefix '  ')
\"
RELATIONS=(cert-provider foo a True)
apache_vhost_create publish_dir \"\$CFG\"
" "known cert key"
is errlvl 0
is err part "\
relation-set apache-custom-rules:
  | - |
  |   ## Auto-redirection from http to https
  |   RewriteEngine On
  |   RewriteCond %{HTTPS} off
  |   RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]
  |"
is out reg 'Calling: compose .*foo: options: <merge_yaml_str\(.a., .12., )>.*crt foo create www.example.com'
is out part 'config-add
  | $SERVICE_NAME:
  |   volumes:
  |   - $DATASTORE/foo/etc/letsencrypt:/etc/letsencrypt:ro'
is out part '
  |     ## Auto-redirection from http to https
  |     RewriteEngine On
  |     RewriteCond %{HTTPS} off
  |     RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]
'



try "
export SERVICE_CONFIGSTORE='\$SERVICE_CONFIGSTORE'
export CONFIGSTORE='\$CONFIGSTORE'
export DATASTORE='\$DATASTORE'
export SERVICE_NAME='\$SERVICE_NAME'
export BASE_SERVICE_NAME='\$BASE_SERVICE_NAME'
export MASTER_TARGET_SERVICE_NAME='\$MASTER_TARGET_SERVICE_NAME'
RELATIONS=(cert-provider foo a True)
CFG='
domain: www.example.com
server-aliases:
ssl:
  foo: 12
'
ADDITION='
apache-custom-rules:
  - |
    ## Auto-redirection from http to https
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]'
MERGE_YAML_STR=\"
d186e0ae74640f6d: |
\$(echo \"\$CFG\" |  prefix '  ')
\$(echo \"\$ADDITION\" | prefix '  ')
\"
apache_vhost_create publish_dir \"\$CFG\"
" "known cert key - empty server-aliases"
is errlvl 0
is err part "\
relation-set apache-custom-rules:
  | - |
  |   ## Auto-redirection from http to https
  |   RewriteEngine On
  |   RewriteCond %{HTTPS} off
  |   RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]
  |"
is out reg 'Calling: compose .*foo: options: <merge_yaml_str\(.a., .12., )>.*crt foo create www.example.com\s+
'
is out part 'config-add
  | $SERVICE_NAME:
  |   volumes:
  |   - $DATASTORE/foo/etc/letsencrypt:/etc/letsencrypt:ro'
is out part 'file_put $SERVICE_CONFIGSTORE/etc/apache2/sites-enabled/www.example.com.conf
  | <VirtualHost *:80>
  |
  |     ServerAdmin contact@www.example.com
  |     ServerName www.example.com
  |
  |     ServerSignature Off' RTRIM
is out part '
  |     ## Auto-redirection from http to https
  |     RewriteEngine On
  |     RewriteCond %{HTTPS} off
  |     RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]
'


try "
export SERVICE_CONFIGSTORE='\$SERVICE_CONFIGSTORE'
export CONFIGSTORE='\$CONFIGSTORE'
export DATASTORE='\$DATASTORE'
export SERVICE_NAME='\$SERVICE_NAME'
export BASE_SERVICE_NAME='\$BASE_SERVICE_NAME'
export MASTER_TARGET_SERVICE_NAME='\$MASTER_TARGET_SERVICE_NAME'
RELATIONS=(cert-provider foo a True)
CFG='
domain: www.example.com
server-aliases:
  - example.fr
  - example.de
ssl:
  foo: 12
'
ADDITION='
apache-custom-rules:
  - |
    ## Auto-redirection from http to https
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]'
MERGE_YAML_STR=\"
fcab3acadc661133: |
\$(echo \"\$CFG\" |  prefix '  ')
\$(echo \"\$ADDITION\" | prefix '  ')
\"
apache_vhost_create publish_dir \"\$CFG\"

" "known cert key - multiple server-aliases"
is errlvl 0
is err part "\
relation-set apache-custom-rules:
  | - |
  |   ## Auto-redirection from http to https
  |   RewriteEngine On
  |   RewriteCond %{HTTPS} off
  |   RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]
  |"
is out reg 'Calling: compose .*foo: options: <merge_yaml_str\(.a., .12., )>.*crt foo create www.example.com example.fr example.de\s+
'
is out part 'config-add
  | $SERVICE_NAME:
  |   volumes:
  |   - $DATASTORE/foo/etc/letsencrypt:/etc/letsencrypt:ro'
is out part 'file_put $SERVICE_CONFIGSTORE/etc/apache2/sites-enabled/www.example.com.conf
  | <VirtualHost *:80>
  |
  |     ServerAdmin contact@www.example.com
  |     ServerName www.example.com
  |     ServerAlias example.fr
  |     ServerAlias example.de
  |
  |     ServerSignature Off' RTRIM
is out part '
  |     ## Auto-redirection from http to https
  |     RewriteEngine On
  |     RewriteCond %{HTTPS} off
  |     RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,QSA]
'