#!/bin/bash

TS_TOPDIR="${0%/*}/../.."
TS_DESC="shared-subtree"

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

ts_check_test_command "$TS_CMD_MOUNT"
ts_check_test_command "$TS_CMD_UMOUNT"
ts_check_test_command "$TS_CMD_FINDMNT"

ts_skip_nonroot
ts_check_losetup
ts_check_prog "mkfs.ext3"

[ -d $TS_MOUNTPOINT ] || mkdir -p $TS_MOUNTPOINT

# bind
$TS_CMD_MOUNT --bind $TS_MOUNTPOINT $TS_MOUNTPOINT
[ "$?" = "0" ] || ts_die "error: mount --bind"

# check the bind
$TS_CMD_FINDMNT --kernel --mountpoint $TS_MOUNTPOINT  &> /dev/null
[ "$?" == "0" ] || ts_die "Cannot find binded $TS_MOUNTPOINT in /proc/self/mountinfo"

# use the same mounpoint for all sub-tests
MOUNTPOINT="$TS_MOUNTPOINT"


ts_init_subtest "make-shared"
$TS_CMD_MOUNT --make-shared $MOUNTPOINT >> $TS_OUTPUT 2>&1
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o PROPAGATION >> $TS_OUTPUT
ts_finalize_subtest

ts_init_subtest "make-private"
$TS_CMD_MOUNT --make-private $MOUNTPOINT >> $TS_OUTPUT 2>&1
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o PROPAGATION >> $TS_OUTPUT
ts_finalize_subtest


ts_init_subtest "make-unbindable"
$TS_CMD_MOUNT --make-unbindable $MOUNTPOINT >> $TS_OUTPUT 2>&1
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o PROPAGATION >> $TS_OUTPUT
ts_finalize_subtest

# clean up
$TS_CMD_UMOUNT $MOUNTPOINT


ts_init_subtest "bind-shared"
$TS_CMD_MOUNT --make-shared \
	      --bind $MOUNTPOINT $MOUNTPOINT >> $TS_OUTPUT 2>&1
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o PROPAGATION >> $TS_OUTPUT
$TS_CMD_UMOUNT $MOUNTPOINT
ts_finalize_subtest


#
# block dev based mounts
#
ts_device_init
DEVICE=$TS_LODEV

mkfs.ext3 $DEVICE &> /dev/null || ts_die "Cannot make ext3 on $DEVICE"
ts_device_has "TYPE" "ext3" $DEVICE || ts_die "Cannot find ext3 on $DEVICE"


ts_init_subtest "mount-private"
$TS_CMD_MOUNT --make-private --make-unbindable \
	      $DEVICE $MOUNTPOINT >> $TS_OUTPUT 2>&1
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o PROPAGATION >> $TS_OUTPUT
$TS_CMD_UMOUNT $MOUNTPOINT
ts_finalize_subtest

ts_init_subtest "mount-private-ro"
$TS_CMD_MOUNT $DEVICE $MOUNTPOINT -o ro,private >> $TS_OUTPUT 2>&1
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o PROPAGATION >> $TS_OUTPUT
$TS_CMD_FINDMNT -nr --mountpoint $MOUNTPOINT -o VFS-OPTIONS >> $TS_OUTPUT
$TS_CMD_UMOUNT $MOUNTPOINT
ts_finalize_subtest

rmdir $MOUNTPOINT

ts_log "Success"
ts_finalize

