#!/bin/bash
#
# Copyright (C) 2026 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="pidfs association"

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

ts_check_test_command "$TS_CMD_LSFD"
ts_check_test_command "$TS_CMD_GETINO"
ts_check_test_command "$TS_HELPER_MKFDS"

ts_cd "$TS_OUTDIR"

PID=
INODE=
{
    coproc MKFDS { "$TS_HELPER_MKFDS" nop; }
    if read -u ${MKFDS[0]} PID; then
	INODE=$("$TS_CMD_GETINO" "$PID")
	inode=$(${TS_CMD_LSFD} --pid="$PID" -n -o INODE -Q '(ASSOC == "pidfs")')
	if [[ -z "$inode" ]]; then
	    echo INODE: "FAILED (empty)"
	elif [[ "$inode" == "$INODE" ]]; then
	    echo INODE: OK
	else
	    echo INODE: "FAILED (getino: $INODE, lsfd: $inode)"
	fi

	pid=$(${TS_CMD_LSFD} --pid="$PID" -n -o PIDFD.PID -Q '(ASSOC == "pidfs")')
	if [[ -z "$pid" ]]; then
	    echo PID: "FAILED (empty)"
	elif [[ "$pid" == "$PID" ]]; then
	    echo PID: OK
	else
	    echo PID: "FAILED (PID: $PID, lsfd: $pid)"
	fi

	comm=$(${TS_CMD_LSFD} --pid="$PID" -n -o PIDFD.COMM -Q '(ASSOC == "pidfs")')
	if [[ "$comm" =~ .*test_mkfds ]]; then
	    echo COMM: OK
	else
	    echo COMM: "FAILED (lsfd: $comm)"
	fi

	nspid=$(${TS_CMD_LSFD} --pid="$PID" -n -o PIDFD.NSPID -Q '(ASSOC == "pidfs")')
	if [[ -z "$nspid" ]]; then
	    echo NSPID: "FAILED (empty)"
	elif [[ "$nspid" == "$PID" ]]; then
	    echo NSPID: OK
	else
	    echo NSPID: "FAILED (PID: $PID, lsfd: $nspid)"
	fi

	echo DONE >&"${MKFDS[1]}"

    fi
    wait ${MKFDS_PID}
} > $TS_OUTPUT 2>&1

ts_finalize
