#!/bin/bash
#
# Copyright (C) 2025 Dick Marinus <dick@mrns.nl>
#
# This file is part of util-linux.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
TS_TOPDIR="${0%/*}/../.."
TS_DESC="copyfilerange"

. "$TS_TOPDIR"/functions.sh
ts_init "$*"

ts_check_test_command "$TS_CMD_COPYFILERANGE"

ts_cd "$TS_OUTDIR"


echo float >  a
touch b c ranges

ts_init_subtest "normal"
"$TS_CMD_COPYFILERANGE" a b 3::1 1::2 2::1 0::1 5::1 &>"$TS_OUTPUT"
cat b >>"$TS_OUTPUT"
ts_finalize_subtest

ts_init_subtest "invalid-input"
"$TS_CMD_COPYFILERANGE" a b 3:bogus:1 bogus::2 :::: bogus svhhs:%%:8  &>/dev/null
if [[ "$?" != "0" ]]; then
	echo "ok" >"$TS_OUTPUT"
fi
ts_finalize_subtest

ts_init_subtest "ranges-option"
cat <<EOF > ranges1
3::1
1::2
2::1
EOF

cat <<EOF > ranges2
0::1
5::1
EOF

"$TS_CMD_COPYFILERANGE" a c --ranges ranges1 --ranges ranges2
cat c >"$TS_OUTPUT"
ts_finalize_subtest

ts_init_subtest "previous-offset-preserved"
"$TS_CMD_COPYFILERANGE" a d ::3 ::
cat d >"$TS_OUTPUT"
ts_finalize_subtest

ts_init_subtest "verbose"
"$TS_CMD_COPYFILERANGE" --verbose a e 3::1 1::2 2::1 0::1 5::1 &>"$TS_OUTPUT"
cat e >>"$TS_OUTPUT"
ts_finalize_subtest

ts_init_subtest "fd-input"
"$TS_CMD_COPYFILERANGE" a f -r <(echo '::') &>"$TS_OUTPUT"
cat f >>"$TS_OUTPUT"
ts_finalize_subtest

ts_init_subtest "mix-arguments-and-options"
"$TS_CMD_COPYFILERANGE" a --verbose g :: &>"$TS_OUTPUT"
cat g >>"$TS_OUTPUT"
ts_finalize_subtest

ts_init_subtest "copy-from-beyond-file-size"
"$TS_CMD_COPYFILERANGE" a h 7:: &>"$TS_OUTPUT"
cat h >>"$TS_OUTPUT"
ts_finalize_subtest

rm -f a b c d e f g ranges

ts_finalize
