#!/bin/bash

Type=$1
Url=$2
Driver=$3

set -x
zypper --non-interactive remove kernel-default kernel-devel
zypper --non-interactive install kernel-default kernel-devel
sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
service sshd restart

if [[ $Type == "format" ]]; then
	physical_disk_num=`lsblk --output NAME,TYPE |grep disk |wc -l`
	if [[ $physical_disk_num -gt 1 ]];then
		echo "There is an extra disk. The extra disk will be formatted."
		system_disk_partition=`findmnt -n -o SOURCE --target /`
		readarray -t physical_disk <<< `lsblk --output NAME,TYPE |grep disk|awk '{print $1}'`
		extra_disk=()
		for item in "${physical_disk[@]}"; do
			res=$(echo $system_disk_partition | grep "${item}")
			if [[ "$res" == "" ]];then
				extra_disk+=("$item")
			fi
		done
		extra_block_device=()
		for device in "${extra_disk[@]}"; do
			block_device="/dev/$device"
			extra_block_device+=("$block_device")
		done
		no_mounted_block_device=()
		for block_device in "${extra_block_device[@]}"; do
			if  mount |grep $block_device ; then
				echo "$block_device has been mounted"
			else
				no_mounted_block_device+=("$block_device")
			fi
		done
		echo "There is only one system disk. No operation is required."
		for blockdevice in "${no_mounted_block_device[@]}"; do
			echo "Prepare To Format The Disk $blockdevice"
			wipefs -a $blockdevice
			parted $blockdevice mklabel msdos
			parted $blockdevice mkpart primary 0% 100%
			device_part=$(fdisk -l $blockdevice | awk '/^\/dev/ {devices = devices $1 "\n"} END {printf "%s", devices}')
			device_part_length=${#device_part[@]}
			if (( $device_part_length == 1 )); then
				first_part=${device_part[0]}
				echo "There is one partition, preparing to format the disk partition ${first_part}."
				mkfs.ext4 -F ${first_part}
				mountdata_dir="/${blockdevice#/dev/}-disk"
				mkdir ${mountdata_dir}
				mount ${first_part} ${mountdata_dir}
				echo "${first_part} ${mountdata_dir} ext4 defaults 0 0" >> /etc/fstab
			fi
		done
	fi
fi

if [[ $Driver != "None" ]];then
	wget $Url
	chmod 755 $Driver
	./$Driver -s
fi

rm -fr opensuse.sh
