#!/bin/sh

############################
# script description:
# umount clear and re-make disk partions
#
# disk partions:
# | -- swap area -- | -- base area -- | -- user area -- |
# 
# auth: fork
# time: 2015-06-12
# copyright: terra-master tec
#
############################

# exit code list:
# 1: script already running
# 2: script service stop failed
# 3: script with invalid block device
# 4: script make GPT  partion failed
# 5: script make core partion failed
# 6: script make swap partion failed
# 7: script make user partion failed
# 8: script make core RAID failed
# 9: script mount core RAID failed
# 10: script tar system.bz2 failed

# 1001: invalid parameters

# include global functions and variables
source /etc/tos/scripts/scripts
source /etc/tos/scripts/service

script_get_lock
[ $? -ne 0 ] && exit 1

echo $TOS_SCRIPTS_PATH
echo $TOS_SETUP_URL
echo $TOS_RAID_CORE
echo $TOS_RAID_SWAP
echo $TOS_CORE_SIGN

disks=""
disksnum=0
coresize=0
swapsize=0
bootsize=0
initlog=/tmp/diskinit.log

echo "start init system. Process:0" > $initlog
[ ! -f ${TOS_RAID_CONF} ] && /usr/bin/tosconf

# parameters check
coresize=`iniparse -c -f ${TOS_RAID_CONF} -s tos -k coresize`
swapsize=`iniparse -c -f ${TOS_RAID_CONF} -s tos -k swapsize`
[ "X${coresize}" = "X" ] && coresize=2048
[ "X${swapsize}" = "X" ] && swapsize=1024
bootsize=300
install=1
while getopts "r" opt                                                   
do                                                                                
	case $opt in                                                              
		r) install=0 ;; # get raid install method...               
	esac
done

for sd in $@
do
	if [ -b $sd ]; then
		disks=$disks' '$sd 
		let disksnum=$disksnum+1
	fi
done

if [ $coresize -lt 1024 ]; then
	echo "invalid core size:$coresize, must not less than 1024. Error:1001" > $initlog
	rm -fr ${TOS_RAID_CONF}
	script_put_lock
	exit 1001
fi

if [ $swapsize -lt 1024 ]; then
	echo "invalid swap size:$swapsize, must not less than 1024. Error:1001" > $initlog
	rm -fr ${TOS_RAID_CONF}
	script_put_lock
	exit 1001
fi

if [ $disksnum -lt 1 ]; then
	echo "invalid disk numb:$disksnum, must not less than 1. Error:1001" > $initlog
	script_put_lock
	exit 1001
fi

echo "start init system. Process:20" > $initlog
sleep 2

# stop system service
service all stop
if [ $? -ne 0 ];then
	echo "service all stop failed. Error:2" > $initlog
	script_put_lock
	exit 2
else
	echo "service all stop. Process:30" > $initlog
fi

# stop system raid
for md in /dev/md*
do
	df | grep $md
	[ $? -eq 0 ] && umount $md
	[ -b $md ] && mdadm -S $md > /dev/null 2>&1
done

if [ $install -eq 1 ]; then
	# part system disk
	for sd in $disks; do
		offset=0
		offend=0
		blk=$sd
	
		if [ ! -b $blk ]; then
			echo "$blk is invlaid block device. Error:3" > $initlog
			script_put_lock
			exit 3
		fi
	
		parted -s $blk mktable gpt
		if [ $? -ne 0 ]; then
			echo make gpt partion on $blk failed
			echo "make gpt partion on $blk failed. Error:4" > $initlog
			script_put_lock
			exit 4
		fi
	    # bootsize...
		let offset=0
		let offend=$offset+$bootsize
		parted -s $blk mkpart primary ext2 0% $offend 
		if [ $? -ne 0 ]; then
			echo "make core on $blk with offset:$offset size:$bootsize failed. Error:5" > $initlog
			script_put_lock
			exit 5
		fi
		# coresize...
		let offset=$offset+$bootsize
		let offend=$offset+$coresize
		parted -s $blk mkpart primary ext2 $offset $offend
		if [ $? -ne 0 ]; then
			echo "make swap on $blk with offset:$offset size:$coresize failed. Error:6" > $initlog
			script_put_lock
			exit 6
		fi
		# swapsize...
		let offset=$offset+$coresize
		let offend=$offset+$swapsize
		parted -s $blk mkpart primary ext2 $offset $offend
		if [ $? -ne 0 ]; then
			echo "make swap on $blk with offset:$offset size:$swapsize failed. Error:6" > $initlog
			script_put_lock
			exit 6
		fi
		# usersize...
		let offset=$offset+$swapsize
		let offend=-1
		parted -s $blk mkpart primary ext2 $offset 100%
		if [ $? -ne 0 ]; then
			echo "make user on $blk with offset:$offset size:lastspace failed. Error:7" > $initlog
			script_put_lock
			exit 7
		fi
	
		#bootparts=$bootparts' '$blk'1'
		coreparts=$coreparts' '$blk'2'
		swapparts=$swapparts' '$blk'3'
		userparts=$userparts' '$blk'4'
		
		echo -e "y\n" | /usr/sbin/mke2fs -t ext4 $blk'1'
		e2label $blk'1' $TOS_DISK_SIGN
	done
	echo "make part on $blk success. Process:60" > $initlog
	sleep 1
	

	# make core raid
	echo "make core raid1 now"
	echo -e "y\n" > /tmp/mdadm.io
	
	mdadm -C $TOS_RAID_CORE -l1 -c512 -n$disksnum -N$TOS_CORE_SIGN $coreparts --force < /tmp/mdadm.io
	sleep 1

	if [ ! -b $TOS_RAID_CORE ]; then
		mdadm -C $TOS_RAID_CORE -l1 -c512 -n$disksnum -N$TOS_CORE_SIGN $coreparts --force < /tmp/mdadm.io
		if [ $? -ne 0 ]; then
			echo "make core raid1 failed. Error:8" > $initlog
			script_put_lock
			exit 8
		else
			echo "make core raid1 failed. Process:70" > $initlog
		fi
	else
		echo "make core raid1 failed. Process:70" > $initlog
	fi
	
	echo -e "y\n" | /usr/sbin/mke2fs -t ext4 $TOS_RAID_CORE
	wait $!
else
	# restore md9
	for sd in $disks
	do
		if [ ! -b $TOS_RAID_CORE ]; then
			mdadm -A $TOS_RAID_CORE ${sd}2 --force
		else
			mdadm -a $TOS_RAID_CORE ${sd}2
		fi
	done
fi

mkdir -p $TOS_RAID_CORE_PATH
mount $TOS_RAID_CORE $TOS_RAID_CORE_PATH
if [ $? -ne 0 ]; then
	echo "mount ${TOS_RAID_CORE} to ${TOS_RAID_CORE_PATH} failed. Error:9" > $initlog
	script_put_lock
	exit 9
else    
	echo "mount ${TOS_RAID_CORE} to ${TOS_RAID_CORE_PATH}. Process:80" > $initlog
fi

syspath=$TOS_RAID_CORE_PATH/system.ins
if [ $install -eq 1 ]; then
    # move install pkgs from memory...free memory
    rm -fr $TOS_RAID_CORE_PATH/* >/dev/null
    mv /mnt/system/system.ins  $syspath -f
    sync
    # tar install rootfs...
    tar -Jxvf $syspath -C $TOS_RAID_CORE_PATH
	tarResult=$?
	sync
	if [ $tarResult -ne 0 ]; then
		echo "tar $syspath to $TOS_RAID_CORE_PATH failed. Error:10" > $initlog
		script_put_lock
		exit 10
	elif [ ! -e "$TOS_RAID_CORE_PATH/lib/modules/4.4.18-g8bcbd8a-dirty" ]; then
		echo "packget $syspath is invalid. Error:11" > $initlog
		script_put_lock
		exit 11
	else
        # tar success... remove install pkgs
        rm -f $syspath >/dev/null
		touch $TOS_RAID_CORE_PATH/.eraseAcl
		echo "tar $syspath to $TOS_RAID_CORE_PATH. Process:90" > $initlog
	fi
    if [ -e $TOS_RAID_CORE_PATH/mnt/bootdev/php7-all.tar ]; then
        mv $TOS_RAID_CORE_PATH/mnt/bootdev/php7-all.tar /mnt/bootdev/php7-all.tar -f 2>/dev/null
        rm -fr $TOS_RAID_CORE_PATH/mnt/bootdev
    fi
    # upgrade kernel...
    kernel_platform=`uname -m`
    if [ "$kernel_platform" = "aarch64" ]; then
        memory_total=`cat /proc/meminfo | awk '/MemTotal:/ {print $2}'`
        kernel_new=$TOS_RAID_CORE_PATH/tmp/firmware_1g.img
        [ $memory_total -gt 600000 ] && kernel_new=$TOS_RAID_CORE_PATH/tmp/firmware_2g.img
        kernel_version=`uname -v | awk -F'#| ' '{print $2}'`
        if [ $kernel_version -le 1243 -a -e $kernel_new ]; then
            echo "Update kernel. Process:96" > $initlog
            mv $kernel_new /tmp/firmware.img -f
            rm -f $TOS_RAID_CORE_PATH/tmp/*
            up.sh
        fi
    fi
fi
# setup gurb bootup config

echo "disk init done. Process:100" > $initlog
script_put_lock
exit 0
