#!/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"
    mkdir -p "$CACHEDIR"
}



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


##
## Tests
##


function test_direct_action {

    init_test

    export CHARM_STORE=$test_tmpdir
    mkdir -p  $test_tmpdir/www/actions
    cat <<EOF2 > $test_tmpdir/www/metadata.yml
docker-image: bar   ## required as we want relation to know the base image
EOF2

    cat <<EOF2 > $test_tmpdir/www/actions/foo
#!/bin/bash

echo 'hello from foo:' "\$@"
EOF2
    chmod +x $test_tmpdir/www/actions/foo
    cat <<EOF2 > $test_tmpdir/compose.yml
web_site:
  charm: www
EOF2

    export DISABLE_SYSTEM_CONFIG_FILE=true

    assert_list <<EOF

### Testing charm action detection

## -- direct charm action

cd "$test_tmpdir"
out=\$("$tprog" foo web_site a b c -y -z j --help 2>&1 >/dev/null ) || exit 1
expected="hello from foo: a b c -y -z j --help"

[[ "\$out" == *"\$expected" ]] || {
    echo "doesn't end with: \$expected" >&2
    echo "\$out"
    exit 1
}


## -- direct charm access to \$COMPOSE_YML_FILE


    cat <<'EOF2' > $test_tmpdir/www/actions/foo
#!/bin/bash

printf "COMPOSE_YML_FILE: '%s'" "\$COMPOSE_YML_FILE"
EOF2

cd "$test_tmpdir"
out=\$("$tprog" foo web_site a b c -y -z j --help 2>&1 >/dev/null ) || exit 1
expected="COMPOSE_YML_FILE: '$test_tmpdir/compose.yml'"

[[ "\$out" == *"\$expected" ]] || {
    echo "doesn't end with: \$expected" >&2
    echo "\$out"
    exit 1
}



EOF

    tear_test
}



continue_on_error="0" testbench $*