#!/bin/sh
# The application itself only reads a "config.env" from the current working
# directory. Check that the wrapper in /usr/bin makes the configuration in /etc
# (and the one selected with DEYE_CONFIG_FILE) work from anywhere.
set -e

cd "$AUTOPKGTEST_TMP"

# Runs the daemon from a directory without a config.env and reports whether it
# survived startup, i.e. whether it found a complete configuration.
starts_up() {
    "$@" > "$AUTOPKGTEST_TMP/output" 2>&1 &
    pid=$!
    sleep 3
    if kill -0 "$pid" 2>/dev/null; then
        kill "$pid"
        wait "$pid" 2>/dev/null || true
        return 0
    fi
    wait "$pid" 2>/dev/null || true
    return 1
}

echo "test: configuration is taken from /etc/deye-inverter-mqtt/config.env"
if ! starts_up deye-inverter-mqtt; then
    echo "FAIL: daemon did not start with the shipped configuration" >&2
    cat "$AUTOPKGTEST_TMP/output" >&2
    exit 1
fi

echo "test: DEYE_CONFIG_FILE overrides the default location"
cat > "$AUTOPKGTEST_TMP/custom.env" <<'EOF'
DEYE_LOGGER_IP_ADDRESS=127.0.0.1
DEYE_LOGGER_SERIAL_NUMBER=1234567890
MQTT_HOST=127.0.0.1
EOF
if ! starts_up env DEYE_CONFIG_FILE="$AUTOPKGTEST_TMP/custom.env" deye-inverter-mqtt; then
    echo "FAIL: daemon did not start with DEYE_CONFIG_FILE" >&2
    cat "$AUTOPKGTEST_TMP/output" >&2
    exit 1
fi

echo "test: a missing configuration file is reported, not silently ignored"
if starts_up env DEYE_CONFIG_FILE="$AUTOPKGTEST_TMP/does-not-exist.env" deye-inverter-mqtt; then
    echo "FAIL: daemon started without any configuration" >&2
    exit 1
fi
grep -q "DEYE_LOGGER_SERIAL_NUMBER" "$AUTOPKGTEST_TMP/output"

echo "OK: configuration is read from /etc and from DEYE_CONFIG_FILE"
