#!/bin/bash
#
# Copyright (C) 2024 Masatake YAMATO <yamato@redhat.com>
#
# 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="SOURCE column for fd opening a file on btrfs"

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

ts_check_test_command "$TS_CMD_LSFD"
ts_check_prog "stat"
ts_check_prog "sed"
ts_check_prog "mkfs.btrfs"
ts_check_prog "dd"

ts_cd "$TS_OUTDIR"

PID=
FD=3

IMG=img-column-source-btrfs.btrfs
MNTPNT=mntpnt-column-source-btrfs
FILE=${MNTPNT}/afile

mkdir -p $MNTPNT
dd if=/dev/zero of=$IMG bs=114294784 count=1 status=none
if ! mkfs.btrfs -q $IMG; then
    ts_skip "failed to make a btrfs image: $IMG"
fi
if ! mount $IMG $MNTPNT; then
    ts_skip "failed to mount a btrfs image, $IMG to $MNTPNT"
fi
trap "umount $MNTPNT; rm -f $IMG" EXIT

if ! touch $FILE; then
    ts_skip "failed to touch a file on a btrfs filesystem: $FILE"
fi

# The major number may be 0. So we can assume the device number is the
# same as that of minor number.
EXPECTED="btrfs:$(stat -c %d $FILE)"

{
    coproc MKFDS { "$TS_HELPER_MKFDS" ro-regular-file $FD file=$FILE; }
    if read -u ${MKFDS[0]} PID; then
	EXPR='(PID == '"${PID}"') and (FD == '"$FD"')'
	SOURCE=$(${TS_CMD_LSFD} -n --raw -o SOURCE -Q "${EXPR}")
	echo "SOURCE": $?
	if [[ "$SOURCE" == "$EXPECTED" ]]; then
	    echo "SOURCE == EXPECTED"
	else
	    echo "SOURCE: $SOURCE"
	    echo "EXPECTED: $EXPECTED"
	fi
	echo DONE >&"${MKFDS[1]}"
    fi
    wait "${MKFDS_PID}"
} > "$TS_OUTPUT" 2>&1

ts_finalize
