#!/bin/bash

#
# Copyright (C) 2007 Karel Zak <kzak@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="move"

. $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_check_test_command "$TS_CMD_MOUNTPOINT"

ts_skip_nonroot

function mount_and_check {
	# last arg must be an existing or to-be-mounted mountpoint
	local mountpoint="${@: -1}"

	$TS_CMD_MOUNT "$@" \
		|| ts_die "error: mount $*"

	$TS_CMD_MOUNTPOINT -q "$mountpoint" \
		|| ts_die "error: mountpoint $mountpoint"
}

DIR_PRIVATE="$TS_OUTDIR/mnt-move-private"

DIR_SRC="$DIR_PRIVATE/mnt-move-src"
DIR_A="$DIR_PRIVATE/mnt-move-A"
DIR_B="$DIR_PRIVATE/mnt-move-B"

# this may fail if there are mounted dirs left
rm -rf "$DIR_PRIVATE" || ts_die "cleanup failed, check manually!"
mkdir "$DIR_PRIVATE"  || ts_die "error: mkdir DIR_PRIVATE"

# create bind mount and make it private to be sure
# (kernel cannot move mount with shared parent)
mount_and_check --bind $DIR_PRIVATE $DIR_PRIVATE
mount_and_check --make-rprivate $DIR_PRIVATE

# Is the bind mount still rw?
mkdir $DIR_SRC $DIR_A $DIR_B \
	|| ts_die "error: mkdir on private bind mount"

# bind
mount_and_check --bind $DIR_SRC $DIR_A

# move
mount_and_check --move $DIR_A $DIR_B

# BTW a basic test for findmnt(8) and mountpoint(1)
for f in `find $DIR_PRIVATE2 $DIR_PRIVATE`; do
	xo="$($TS_CMD_MOUNTPOINT -q "$f" 2>&1)"
	x=$?
	yo="$($TS_CMD_FINDMNT --kernel --mountpoint "$f" 2>&1)"
	y=$?

	[ "$x" = "$y" ] || ts_log "error: findmount vs. mountpoint: $x, $y, $f"
	[ -z "$xo" ] || ts_log "error: mountpoint is not quiet: $x, $y, $f"
	if [ "$y" = "0" -a "$yo" = "" ] || [ "$y" = "1" -a "$yo" != "" ]; then
		ts_log "error, findmount return value vs. output: $x, $y, $f"
	fi
done

# clean up
$TS_CMD_UMOUNT $DIR_B || ts_log "error: umount DIR_B"
rmdir $DIR_SRC $DIR_A $DIR_B || ts_log "error: rmdir DIR_B"
$TS_CMD_UMOUNT $DIR_PRIVATE || ts_log "error: umount DIR_PRIVATE"
rmdir $DIR_PRIVATE || ts_log "error: rmdir DIR_PRIVATE"

ts_log "Success"
ts_finalize

