#!/bin/bash

function kill_process(){

ID=`ps -ef | grep $1 | grep -v grep | awk '{print $1}'`
#echo $ID
for id in $ID
do
kill -9 $id
echo "kill $id"
done
}

if [ $# -eq 1 ]
then
	swapoff -a
	
	kill_process ipfs
	kill_process /opt/tool/saturn-monitor
	kill_process /opt/tool/saturn-cycle-c
	kill_process /opt/tool/saturn-collect
	kill_process /opt/storage/log/system

	systemctl stop minio
	systemctl stop nfs-server
        systemctl stop smb
        systemctl stop tgtd
        systemctl stop dev

	if  grep -qs /opt/storage /proc/mounts; then
                umount /dev/LVM/lvdisk
		lvremove /dev/LVM/lvdisk
		vgremove  LVM
		pvremove /dev/sda1
		pvremove /dev/sdb1
		pvremove /dev/sdc1
		pvremove /dev/sdd1
        fi
        umount /dev/sda1
        umount /dev/sdb1
        umount /dev/sdc1
        umount /dev/sdd1
        umount /dev/sde1
        umount /dev/sde2
	if  grep -qs /opt/collect /proc/mounts; then
                umount /dev/sde2
		if [ $? -ne 0 ] ; then
                        echo "saturn-init.sh exec error! umount /dev/sde2 resource busy." 
                        exit 0
                fi
        fi

	dd if=/dev/zero of=/dev/sda bs=10M count=1
	dd if=/dev/zero of=/dev/sdb bs=10M count=1
	dd if=/dev/zero of=/dev/sdc bs=10M count=1
	dd if=/dev/zero of=/dev/sdd bs=10M count=1
	dd if=/dev/zero of=/dev/sde bs=10M count=1

	sleep 1

	/opt/tool/saturn-device-id.sh -w 0x0 $1 9

	echo "yes" |parted /dev/sda mklabel gpt
	echo "Ignore" | parted /dev/sda "mkpart primary ext4 2048s -1"
	
	echo "yes" |parted /dev/sdb mklabel gpt
	echo "Ignore" | parted /dev/sdb "mkpart primary ext4 2048s -1"

        echo "yes" |parted /dev/sdc mklabel gpt
        echo "Ignore" | parted /dev/sdc "mkpart primary ext4 2048s -1"

        echo "yes" |parted /dev/sdd mklabel gpt
        echo "Ignore" | parted /dev/sdd "mkpart primary ext4 2048s -1"

        echo "yes" |parted /dev/sde mklabel gpt
        echo "Ignore" | parted /dev/sde "mkpart primary linux-swap 2048s 6G"
        parted /dev/sde "mkpart primary ext4 6G -1"

	echo "yes" |mkfs.ext4 /dev/sde2

	mkswap /dev/sde1
	
	sync

        partprobe
else
	 echo "Usage:saturn-init-prev.sh device-id"
fi

echo "success"
