#!/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:10" > $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:20" > $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
    echo "make part start. Process:30" > $initlog
    # part system disk
    for blk in $disks; do
        offset=0
        offend=0

        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


        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 success. Process:40" > $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
        fi
    fi
    [ -b $TOS_RAID_CORE ] && mdadm --grow $TOS_RAID_CORE --raid-devices=72 --force
    echo "make core raid1 success. Process:50" > $initlog

    echo -e "y\n" | /usr/sbin/mke2fs -t ext4 $TOS_RAID_CORE
    wait $!
    process=50
    TOS_CORE_NAME=`basename $TOS_RAID_CORE`
    while [ 1 ]; do
        sleep 2
        sync_action=`cat /sys/block/$TOS_CORE_NAME/md/sync_action`
        if [ "$sync_action" = "idle" ]; then
            break
        fi
        [ $process -lt 80 ] && let process=process+1
        echo "wait core raid1 sync. Process:$process" > $initlog
    done
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
fi
echo "mount ${TOS_RAID_CORE} to ${TOS_RAID_CORE_PATH}. Process:86" > $initlog

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 -xf $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
        chown -R root:root $TOS_RAID_CORE_PATH/*
        #add rws for sudo & busybox
        chmod 4755 $TOS_RAID_CORE_PATH/usr/bin/sudo
        chmod 4755 $TOS_RAID_CORE_PATH/bin/busybox
        [ "$INSTALLAUTO" = "1" ] && touch $TOS_RAID_CORE_PATH/.autoInstall
        touch $TOS_RAID_CORE_PATH/.eraseAcl
        if [ $? -ne 0 ]; then
            echo "tar $syspath to $TOS_RAID_CORE_PATH failed. Error:10" > $initlog
            script_put_lock
            exit 10
        else
            echo "tar $syspath to $TOS_RAID_CORE_PATH. Process:90" > $initlog
	    sync
        fi
    fi
    if [ -x $TOS_RAID_CORE_PATH/usr/sbin/checkusb ]; then
        if [ -f $TOS_RAID_CORE_PATH/etc/tos/scripts/mountusb.min ]; then
            cp $TOS_RAID_CORE_PATH/etc/tos/scripts/mountusb.min /etc/init.d/mountusb -a
        fi
        newboot=$TOS_RAID_CORE_PATH/mnt/bootdev/php7-all.tar
        $TOS_RAID_CORE_PATH/usr/sbin/checkusb $newboot
        if [ $? -eq 0 ]; then
            mv $newboot /mnt/bootdev/php7-all.tar -f 2>/dev/null
        fi
        rm -fr $(dirname $newboot)
        sync
    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 1048586 ] && kernel_new=$TOS_RAID_CORE_PATH/tmp/firmware_2g.img
        if [ -e $kernel_new ]; then
            kernel_version=`uname -v | awk -F'#| ' '{print $2}'`
            #1260 is a error version, must up.sh
            if [ $kernel_version -lt 1327 ]; 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
fi
# setup gurb bootup config

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

