#!/bin/bash
#
# 	DESCRIPTION:	configure fstab
#			this script will modify $TARGT/etc/fstab,
#			append the mountpoint to $TARGET/etc/fstab.
#			From 2012 Oct 12. Swap also use UUID in fstab,
#			Because bug# 822 is fixed that make the swap generate
#			UUID, and can't awareness device file, use origin
#			device name.
#
#	SCRIPT NAME:	configure_fstab.sh
#
#	Usage:	echo "/dev/hda2 /home ext3"|./configure_fstab.sh
#
#	Input:	stdin
#			1. partition
#			2. mountpoint
#			3. filesystem type
#			below input is optional, if not set, we configure default, 
#			more about these argument read man fstab.
#			4. fs_mntops
#			5. fs_freq
#			6. fs_passno
#
#	Output:	
#			NULL
#	Returne value:
#			1 argument error	
#			2 fstab doesn't exist
#
#	AUTHOR:		Qin Bo
#
#	EMAIL:		bqin@linx-info.com
#
#	DATE:		2010-08-12
#
#	HISTORY:
#	REVISOR		DATE			MODIFICATION
#	Qin Bo		2010-08-12		create
#
#
#

source ./functions

configure_fstab ()
{
	local device="$1"
	local mountpoint="$2"
	local fs_type="$3"
	local fs_mntops="$4"
	local fs_freq="$5"
	local fs_passno="$6"
	# store uuid or by-id
	local devname=""

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

	# get partition's UUID, if partition not exist, 
	# or couldn't get partition information, set $devname as default
	by_uuid=$(get_disk_sym $device "by-uuid")
	if [ -n "$by_uuid" ];then
		devname="UUID=$(echo $by_uuid|sed 's/.*\///')"
	else
		devname="$device"
	fi

	# configure fstab options here
	# fs_mntops, fs_freq, fs_passno has given, we use function argument,
	# or we set default configuration, set fs_freq 0, because our OS haven't
	# dump utility, set root device of fs_passno 1. root device must first check.
	# other device set 0.
	case $fs_type in
		ext2|ext3|ext4|reiserfs) 
			[ -z "$fs_mntops" ] && fs_mntops="acl" 
			;;
		swap)
			[ -z "$fs_mntops" ] && fs_mntops="defaults" 
			;;
		*)
			[ -z "$fs_mntops" ] && fs_mntops="defaults" 
			;;
	esac

	[ -z "$fs_freq" ] && fs_freq=0 

	if [ "$mountpoint" == "/" ];then
			[ -z "$fs_passno" ] && fs_passno=1
	else
			[ -z "$fs_passno" ] && fs_passno=0
	fi

	info "$devname $mountpoint $fs_type $fs_mntops $fs_freq $fs_passno"
	printf "%-60s %-10s %-10s %-25s %-1s %-1s\n" $devname $mountpoint $fs_type $fs_mntops $fs_freq $fs_passno >>"$TARGET/etc/fstab"
}


main ()
{
	local line

	if [ -e "$TARGET/etc/fstab" ];then
		sed -i '/^#devpts/ s/#//
			/^#sysfs/ s/#//
			/^#shm/ s/#shm /tmpfs/ ' "$TARGET/etc/fstab"

		info "configure fstab"
		while read line;do 
			if [ -n "$line" ];then
				configure_fstab $line
				erv
			fi
		done
		info "configure fstab success"
	else
		err "$TARGET/etc/fstab doesn't exist"
		exit 2
	fi
}

main "$@"

