#!/bin/bash

source /etc/tos/scripts/scripts
if [ $# -eq 0 ]; then
    echo "usage: `basename $0` ...[blk]"
    exit 1
fi

script_get_lock > /dev/null
[ $? -ne 0 ] && exit 1

find_raid_by_disk(){
    local blk=$1
    local blkname=$(basename $blk)
    local path=`ls -1d /sys/block/md*/slaves/${blkname} 2>/dev/null`
    if [ ! -z "$path" ]; then
        echo $(basename $(dirname $(dirname $path)))
        return 0
    fi
    return 1
}

stop_raid(){
    local raid=$1
    local type=`blkid ${raid} -o export | awk -F= '/TYPE=/ {print $2}'`
    if [ "$type" = "LVM2_member" ]; then
        local vgname=`pvs -o vg_name ${raid} --noheadings|sed s/[[:space:]]//g`
        if [ ! -z "$vgname" ]; then
            for blk in `ls -1 /dev/mapper/$vgname-lv*`; do
                umount $blk >/dev/null 2>&1
            done
            vgremove -f $vgname >/dev/null 2>&1
        fi
        pvremove -ff $raid >/dev/null 2>&1
    fi
    mdadm -S $raid >/dev/null 2>&1
    return 0
}

init_disk_factory(){
    local blk=$1
    local part_number=$2
    local userblk=${blk}${part_number}
    [ ! -b ${userblk} ] && return 1
    local disk_type=`blkid ${userblk} -o export | awk -F= '/TYPE=/ {print $2}'`
    if [ "$disk_type" = "linux_raid_member" ]; then
        local raidname=`find_raid_by_disk ${userblk}`
        if [ $? -eq 0 ]; then
            local raid=/dev/$raidname
            stop_raid $raid
        fi
        mdadm --zero-superblock ${userblk} >/dev/null 2>&1
    fi
}

process=0
echo "initdisk:$process" > /tmp/.initdisk
sleep 1
let every_process=100/$#

# get TOS_DEVICES
for disk in $@; do
    [ ! -b $disk ] && continue
    init_disk_factory $disk 4
    sleep 1
    let process=process+every_process
    echo "initdisk:$process" > /tmp/.initdisk
done

process=100
echo "initdisk:$process" > /tmp/.initdisk

script_put_lock > /dev/null
exit 0


