#!/bin/bash

function calc_cyls {
	size=$1
	[ -z $size ] && size=0

	cyl_nr=`echo \($size*1000*1000+\($cylinder_size-1\)\)/$cylinder_size +1 | bc`
	echo $cyl_nr
}

function check_size {

	disk=$1
	check1=$2
	check2=$3
	check3=$4

	sector_size=512

	if echo $disk | grep -e '[0-9]$' > /dev/null 2>&1 ; then
		disk_dev=`echo $disk|sed 's/[0-9]\+//g'`
	else
		disk_dev=$disk
	fi

	block_size=`LANG=C /sbin/sfdisk -l $disk_dev 2>/dev/null | grep "blocks of" | sed 's/^.*blocks[[:space:]]\+of[[:space:]]\+\([0-9]\+\).*$/\1/g'`
	cylinder_nr=`LANG=C /sbin/sfdisk -l $disk_dev 2>/dev/null | grep "^Disk" | sed 's/^.*[[:space:]]\+\([0-9]\+\)[[:space:]]\+cylinders.*$/\1/g'`
	head_nr=`LANG=C /sbin/sfdisk -l $disk_dev 2>/dev/null | grep "^Disk" | sed 's/^.*[[:space:]]\+\([0-9]\+\)[[:space:]]\+heads.*$/\1/g'`
	sector_nr=`LANG=C /sbin/sfdisk -l $disk_dev 2>/dev/null | grep "^Disk" | sed 's/^.*[[:space:]]\+\([0-9]\+\)[[:space:]]\+sectors\/track$/\1/g'`
	cylinder_size=`echo $head_nr*$sector_nr*$sector_size|bc`

	if echo $disk | grep -e '[0-9]$' > /dev/null 2>&1 ; then
		part_blocks=`LANG=C /sbin/sfdisk -s $disk 2>/dev/null`
		cyl_nr=`echo $part_blocks*$block_size/$cylinder_size|bc`
	else
		cyl_nr=`LANG=C /sbin/sfdisk -l $disk 2>/dev/null | grep "^Disk" | sed 's/^.*[[:space:]]\+\([0-9]\+\)[[:space:]]\+cylinders.*$/\1/g'`
	fi

	cyl1=`calc_cyls $check1`
	cyl2=`calc_cyls $check2`
	cyl3=`calc_cyls $check3`

	cyl_sum=`echo $cyl1+$cyl2+$cyl3|bc`
	if [ $cyl_sum -gt $cyl_nr ] ; then
		echo too big partition size were specified.
		exit 1
	fi
}

function make_partition {

	device=$1
	size=$2
	label=$3

        if [ "$label" != "" ]; then
                label_option="-L $label"
        else
                label_option=""
        fi

        if [ "$size" = "0" ]; then
                size=""
        else
	        check_size ${device} ${size} 0 0
                size="+${size}M"
        fi

	dd if=/dev/zero of=$device bs=512 count=1 >/dev/null 2>&1
	/sbin/fdisk $device >/dev/null 2>&1 <<EOM 
	n
	p
	1

	${size}
	w
	q
EOM

        # ext3でフォーマットする
        /sbin/mke2fs -j $label_option ${device}1 >/dev/null 2>&1
}


HOMEDEV=$1
HOMESIZE=$2
LABEL="/home"

if [ $# -ne 2 ] ; then
	echo "$0: command syntax error"
	exit 1
fi

MATCH=`echo $HOMEDEV | grep -e "^/dev/sda[0-9]*"`
if [ "$MATCH" = "$HOMEDEV" ]; then
	  exit 0
else
          make_partition $HOMEDEV $HOMESIZE $LABEL
fi

# 既存 /homeディレクトリのバックアップ
/bin/tar cfz /tmp/home.tgz /home >/dev/null 2>&1

# /homeのマウント情報登録
echo "LABEL=$LABEL           /home                   ext3    defaults,usrquota,grpquota 1 2" >> /etc/fstab

/bin/mount /home >/dev/null 2>&1

# リストア
/bin/tar xfz /tmp/home.tgz --directory / >/dev/null 2>&1

# パーティション情報更新
/sbin/partprobe >/dev/null 2>&1


exit 0
