#!/bin/bash
#
# 	DESCRIPTION:	mounting all partitions which from stdin
#
#	SCRIPT NAME:	mount_partition.sh
#
#	Usage: echo "/dev/sda1 / ext3" |./mount_partition.sh
#
#	Notice: don't expect mount swap partition : )
#
#	Input:	stdin
#			1. partition
#			2. mountpoint
#			3. filesystem type
#			below input is optional, if not set, we mount default configure 
#			4. fs_mntops: set mount options
#	Output:	
#			success:
#			@ mount $devname success
#	Return value:
#			1 argument error
#			2 device node doesn't exist
#			32 mount failure
#
#	AUTHOR:		Qin Bo
#
#	EMAIL:		bqin@linx-info.com
#
#	DATE:		2010-08-06
#
#	HISTORY:
#	REVISOR		DATE			MODIFICATION
#	Qin Bo		2010-08-06		create
#
#
#

source ./functions

mount_partition ()
{

	local devname="$1"
	local mountpoint="$2"
	local fs_type="$3"
	local fs_mntops="$4"

	if [ $# -lt 3 ];then
		err "$FUNCNAME function argument error, it need 3 arguments at least !"
		return 1
	fi

	local mount_pos="$TARGET$mountpoint"

	if [ ! -e "$devname" ];then
		err "$devname node doesn't exist !"
		return 2
	fi

	# mount filesystem for default option,
	# after installation will set acl, so we use acl option mount here.
	# this configuration according old Rocky installer.
	case $fs_type in
		ext2|ext3|ext4|reiserfs) 
			[ -z "$fs_mntops" ] && fs_mntops="acl" ;;
		*)
			[ -z "$fs_mntops" ] && fs_mntops="defaults" ;;
	esac

	if [ ! -d "$mount_pos" ];then
		info "create directory $mount_pos ..."
		mkdir -p "$mount_pos"
	fi
	
	# device node has already mounted on other directory, umount it.
	# ex: /dev/hda5 should mount on /mnt, but it has already mounted on /cdrom before,
	# so, we umount it
	if grep -q "^$devname " /proc/mounts;then
		reumount $devname
	fi
	
	# mountpoint has already mounted, umount it
	if mountpoint -q $mount_pos;then
		# may be have mountpoint under the mountpoint directory
		reumount $mount_pos
	fi

	info "mounting $devname on $mount_pos with $fs_type filesystem"

    if [ $mount_pos = "$TARGET/tmppoint" ]; then
        mkdir -p "/tmp/tmppoint"
        mount_pos="/tmp/tmppoint"
    fi

	mount -t "$fs_type" -o $fs_mntops "$devname" "$mount_pos"  1>>"$DEV_LOG" 2>&1
}

main()
{
	local line 

	# sort -k 2 ensure let short mountpoint sort at front of long mountpoint,
	# in this way, we can mount long mountpoint after short mountpoint.
	# ex: /usr/lib, /usr, /, after sort is /, /usr, /usr/lib
	# this mean that / is mounted first, then mount /usr, finally mount /usr/lib
	while read line; do
		echo $line	
	done|sort -k 2 -u|
	while read line; do
		if [ -n "$line" ];then
			mount_partition $line
			erv
			info "mount $(echo $line|awk '{print $1}') success" stdout
		fi
	done
}


main "$@"


