#!/bin/bash

set -pu

function call_comment_config_line {
    {{{ bash_comment_config_line("$1", "$2") | indent(4) }}}
}

is_old_bats=0

setup() {
    if [[ -z "${BATS_TEST_TMPDIR:-}" ]] || [[ ! -d "${BATS_TEST_TMPDIR}" ]]; then
        BATS_TEST_TMPDIR="$(mktemp -d)"  # 1.4.0
        # shellcheck disable=SC2034
        BATS_TEARDOWN_STARTED=  # 1.3.0
        is_old_bats=1
    else
        is_old_bats=0
    fi
    pushd "${BATS_TEST_TMPDIR}" || exit 1
    mkdir -p comment_cfg_test
}

teardown() {
    if (( is_old_bats )); then
        if [[ -z "${BATS_TEST_TMPDIR:-}" ]] || [[ ! -d "${BATS_TEST_TMPDIR}" ]]; then
            >&2 echo "INTERNAL ERROR"
            exit 3
        fi
        local tmppath xpwd
        tmppath="$(readlink -f -- "${BATS_TEST_TMPDIR}")"
        if [[ ! "${tmppath}" =~ ^/tmp/ ]] || [[ ! -d "${tmppath}" ]]; then
            >&2 echo "INTERNAL ERROR"
            exit 3
        fi
        xpwd="$(readlink -f -- .)"
        if [[ "${tmppath}" != "${xpwd}" ]]; then
            >&2 echo "INTERNAL ERROR"
            exit 3
        fi
        popd || exit 1
        rm -rf -- "${tmppath}"
        BATS_TEST_TMPDIR=""
    fi
}

@test "bash_comment_config_line - Basic line comment" {
    printf "\nSomeSetting = true\n" > comment_cfg_test/test.conf
    expected_output="\n#SomeSetting = true\n"

    call_comment_config_line "comment_cfg_test/test.conf" "^SomeSetting"

    run diff "comment_cfg_test/test.conf" <(printf "$expected_output")
    [ "$status" -eq 0 ]
}

@test "bash_comment_config_line - Comment line with wildcards" {
    printf "\n*.* 1.2.3.4\n" > comment_cfg_test/test.conf
    expected_output="\n#*.* 1.2.3.4\n"

    call_comment_config_line "comment_cfg_test/test.conf" "^\*\.\*"

    run diff "comment_cfg_test/test.conf" <(printf "$expected_output")
    [ "$status" -eq 0 ]
}
