#!/bin/bash
#
# Copyright (C) 2017 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="NSFS for ip-netns-add"

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

ts_skip_nonroot

ts_check_test_command "$TS_CMD_LSNS"
ts_check_test_command "$TS_CMD_MOUNT"
ts_check_test_command "$TS_CMD_UMOUNT"
ts_check_prog "ip"
ts_check_prog "dd"
ts_check_prog "touch"
ts_check_prog "mkfifo"
ts_check_prog "sed"

grep -q '#define HAVE_LINUX_NET_NAMESPACE_H' ${top_builddir}/config.h || ts_skip "no netns support"

ts_cd "$TS_OUTDIR"

NAME1=ABC
NAME2=XYZ
PATH1=/run/netns/$NAME1
PATH2=$TS_OUTDIR/$NAME2
FIFO=$TS_OUTDIR/FIFO-NSFS
NULL=/dev/null

function cleanup {
	rm -f $FIFO
	$TS_CMD_UMOUNT $PATH2 2> /dev/null || :
	rm -f $PATH2
	ip netns delete $NAME1 2> /dev/null || :
}

cleanup
mkfifo $FIFO

if ip netns add $NAME1 &&
	touch ${PATH2} &&
	$TS_CMD_MOUNT -o bind ${PATH1} ${PATH2}; then
    ip netns exec $NAME1 dd if=$FIFO bs=1 count=2 of=$NULL 2> $NULL &
    PID=$!
else
    cleanup
    ts_skip "failed to initialize"
fi
{
    dd if=/dev/zero bs=1 count=1 2> $NULL
    LSNS_FULL=$($TS_CMD_LSNS --type net)
    NSFS_NAMES_MLINES=$($TS_CMD_LSNS -n -o NSFS --type net --task $PID | { while read VAL; do echo $VAL; done; } )
    NSFS_NAMES_1LINE=$($TS_CMD_LSNS -n -o NSFS --nowrap --type net --task $PID | { while read VAL; do echo $VAL; done; } )
    dd if=/dev/zero bs=1 count=1 2> $NULL
} > $FIFO

test "$NSFS_NAMES_MLINES" = "$PATH1
$PATH2" && test "$NSFS_NAMES_1LINE" = "$PATH1,$PATH2"

RESULT=$?
echo $RESULT >> $TS_OUTPUT

if [ $RESULT -ne 0 ]; then
	echo
	echo "**Full-report**"
	echo "$LSNS_FULL"
	echo "**Paths**"
	echo "PATH1: $PATH1"
	echo "PATH2: $PATH2"
	echo "**Multi-line:**"
	echo "$NSFS_NAMES_MLINES"
	echo "**One-line:**"
	echo "$NSFS_NAMES_1LINE"
	echo "****"
fi

cleanup
ts_finalize
