#!/usr/bin/env bash-shlib
# -*- mode: shell-script -*-

include shunit

depends sed grep git mkdir readlink

export -f matches
export grep

tmp=/tmp
tprog="../bin/compose-core"
tprog=$(readlink -f $tprog)


export PATH=".:$PATH"
short_tprog=$(basename "$tprog")


##
## Convenience function
##

init_test() {
    test_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
    cd "$test_tmpdir"
    export CACHEDIR="$test_tmpdir/.cache"
    export VARDIR="$test_tmpdir/.var"
    export COMPOSE_DISABLE_DOCKER_COMPOSE_STORE="1"
    mkdir -p "$CACHEDIR"
}



tear_test() {
    rm -rf "$test_tmpdir"
}


##
## Tests
##


function test_injection {

    init_test

    export CHARM_STORE=$test_tmpdir
    mkdir -p  $test_tmpdir/{toto,titi}
    cat <<EOF2 > $test_tmpdir/toto/metadata.yml
docker-image: toto
EOF2

    cat <<EOF2 > $test_tmpdir/titi/metadata.yml
docker-image: titi
EOF2

    cat <<EOF2 > $test_tmpdir/compose.yml
web_site:
  charm: toto
EOF2

    export DISABLE_SYSTEM_CONFIG_FILE=true

    assert_list <<EOF

### Testing injection of run-time compose code

## -- simple injection, replacing charm

cd "$test_tmpdir"
injection='
web_site:
  charm: titi
'
out=\$("$tprog" -Y "\$injection" config web_site 2>/dev/null) || exit 1
out=\$(echo "\$out" | shyaml get-value services.web_site.image) || exit 1
expected="titi"

[ "\$out" == "\$expected" ] || {
    echo -e "DIFF:\n\$(diff <(echo "\$out") <(echo "\$expected"))"
    exit 1
}

EOF

    tear_test
}



continue_on_error="0" testbench $*