#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later

set -euo pipefail

. "$(dirname "$0")/lib.sh"

setup "$1"
plan 14

# write basic
echo "old content" > "$TESTDIR/write-target"
write_conf "w $TESTDIR/write-target - - - - new content"
run_test "write basic command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_file_equals "$TESTDIR/write-target" "new content"

# write append
echo "first" > "$TESTDIR/write-append"
write_conf "w+ $TESTDIR/write-append - - - - second"
run_test "write append command" "$SEEDFILES" --create "$TESTDIR/conf"
expected=$(printf 'first\nsecond')
assert_file_equals "$TESTDIR/write-append" "$expected"

# write missing file (should succeed silently)
write_conf "w $TESTDIR/nonexistent-write-target - - - - data"
run_test "write missing silent command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_not_exists "$TESTDIR/nonexistent-write-target"

# write dry run
echo "untouched" > "$TESTDIR/write-dryrun"
write_conf "w $TESTDIR/write-dryrun - - - - overwritten"
run_test "write dry run command" "$SEEDFILES" --create --dry-run "$TESTDIR/conf"
assert_file_equals "$TESTDIR/write-dryrun" "untouched"

# write glob
echo "aaa" > "$TESTDIR/wglob-1.dat"
echo "bbb" > "$TESTDIR/wglob-2.dat"
echo "ccc" > "$TESTDIR/wglob-3.dat"
write_conf "w $TESTDIR/wglob-*.dat - - - - replaced"
run_test "write glob command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_file_equals "$TESTDIR/wglob-1.dat" "replaced"
assert_file_equals "$TESTDIR/wglob-2.dat" "replaced"
assert_file_equals "$TESTDIR/wglob-3.dat" "replaced"

# write escaped newline
echo "placeholder" > "$TESTDIR/write-escape"
write_conf "w $TESTDIR/write-escape - - - - line1\\nline2"
run_test "write escape command" "$SEEDFILES" --create "$TESTDIR/conf"
expected=$(printf 'line1\nline2')
assert_file_equals "$TESTDIR/write-escape" "$expected"

done_testing
