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

set -euo pipefail

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

setup "$1"
plan 28

# create directory
write_conf "d $TESTDIR/mydir 0755 - - -"
run_test "create directory command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/mydir"

# create nested directories
write_conf \
    "d $TESTDIR/a 0755 - - -" \
    "d $TESTDIR/a/b 0755 - - -" \
    "d $TESTDIR/a/b/c 0755 - - -"
run_test "create nested dirs command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/a/b/c"

# create file with content
write_conf "f $TESTDIR/hello.txt 0644 - - - Hello World"
run_test "create file command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/hello.txt"
assert_file_equals "$TESTDIR/hello.txt" "Hello World"

# create file with same content as above but encoded in base64
write_conf "f~ $TESTDIR/hello64.txt 0644 - - - SGVsbG8gV29ybGQ="
run_test "create file command base64" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/hello64.txt"
assert_file_equals "$TESTDIR/hello64.txt" "Hello World"

# fail with invalid base64 data (too short)
write_conf "f~ $TESTDIR/hello64i1.txt 0644 - - - SG"
run_test_fail "create file command invalid base64" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/hello64i1.txt"
assert_file_equals "$TESTDIR/hello64i1.txt" ""

# fail with invalid base64 data (length is not multiple of 4)
write_conf "f~ $TESTDIR/hello64i2.txt 0644 - - - SGVsb"
run_test_fail "create file command invalid base64" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/hello64i2.txt"
assert_file_equals "$TESTDIR/hello64i2.txt" ""

# fail with invalid base64 data (invalid characters)
write_conf "f~ $TESTDIR/hello64i3.txt 0644 - - - SGVs%%%%"
run_test_fail "create file command invalid base64" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/hello64i3.txt"
assert_file_equals "$TESTDIR/hello64i3.txt" ""

# create empty file
write_conf "f $TESTDIR/empty.txt 0644 - - -"
run_test "create empty file command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_exists "$TESTDIR/empty.txt"
sz="$(stat -c '%s' "$TESTDIR/empty.txt")"
if [ "$sz" -eq 0 ]; then ok "empty file has zero size"; else not_ok "empty file has zero size" "size=$sz"; fi

# create symlink
write_conf "L $TESTDIR/mylink - - - - $TESTDIR/hello.txt"
run_test "create symlink command" "$SEEDFILES" --create "$TESTDIR/conf"
assert_symlink_to "$TESTDIR/mylink" "$TESTDIR/hello.txt"

# create fifo
write_conf "p $TESTDIR/myfifo 0644 - - -"
run_test "create fifo command" "$SEEDFILES" --create "$TESTDIR/conf"
if [ -p "$TESTDIR/myfifo" ]; then ok "fifo exists"; else not_ok "fifo exists" "not a fifo"; fi

# dry run
write_conf "d $TESTDIR/no-create 0755 - - -"
run_test "dry run command" "$SEEDFILES" --create --dry-run "$TESTDIR/conf"
assert_not_exists "$TESTDIR/no-create"

done_testing
