#!/bin/bash

echo "现在开始划分逻辑卷"
sleep 2

echo "请输入逻辑卷名称"
read LVS
if [ "$LVS" = "" ];then
   echo "值为空，请检查"
   exit 99
fi
echo "请输入逻辑卷大小"
read LVSIZE
if [ "$LVSIZE" = "" ];then
   echo "值为空，请检查"
   exit 99
fi
echo "请输入挂载目录，格式/\$dir/\$dir"
read DIR
if [ "$DIR" = "" ];then
   echo "值为空，请检查"
   exit 99
fi
echo "请输入文件系统，ext4、xfs"
read filesys
if [ "$filesys" = "" ];then
   echo "值为空，请检查"
   exit 99
fi

value_name=`lsblk | grep disk | awk '{print substr($1,1,1)}' | head -1`
value_disk=`lsblk | grep disk | awk '{print $1}' | grep -v "${value_name}da"`

Disk_create(){
if [ ! -b "/dev/${value_disk}1" ];then
fdisk /dev/$value_disk &>/dev/null <<EOF
n
p
  
  
  
wq
EOF
fi
}
Disk_create

pv_create(){
pvs | grep "$value_disk" &>/dev/null
if [ $? -ne 0 ];then
  pvcreate /dev/${value_disk}1
  if [ $? -ne 0 ];then
    echo '物理卷创建失败,请检查'
    sleep 2
    exit 10
  fi
else
  echo "物理卷已存在"
fi
}
pv_create

vg_create(){
vgs | grep 'vg_data' &>/dev/null
if [ $? -ne 0 ];then
  vgcreate vg_data /dev/${value_disk}1
  if [ $? -ne  0 ];then
    echo '卷组创建失败,请检查'
    sleep 2
    exit 10
  fi
else
  echo '卷组已存在'
fi
}
vg_create

lv_judge(){
lvs | awk 'NR>2{print line}{line=$0} END{print line}' | awk '{print $1}' | grep -w "$LVS" >/dev/null &> /dev/null
if [ $? != 0 ];then
  echo "逻辑卷名称没有问题"
else
  echo "逻辑卷名称已存在，请更换"
  exit 99
fi
}
lv_judge

dir(){
if [ ! -d $DIR ];then
  echo "现在开始建立目录"
  mkdir $DIR
else
  dir_num=`ls $DIR | wc -l`
  if [ "$dir_num" != 0 ];then
    echo "挂载目录存在文件,请检查"
    exit 99
  fi
fi

check_dir=`mount | awk -F" " '{print $3}' | grep -w "$DIR" | wc -l`
if [ "$check_dir" != 0 ];then
  echo "目录已被挂载，请检查"
  exit 99
fi
}
dir

lv_cre(){
lvcreate -L +$LVSIZE -n $LVS vg_data &>/dev/null
if [ $? = 0 ];then
  echo "逻辑卷建立成功"
else 
  echo "逻辑卷建立失败，请检查" 
  exit 99
fi 
}
lv_cre

lv_mou(){
fst="/dev/vg_data/$LVS $DIR $filesys defaults 0 0"
mkfs.$filesys /dev/vg_data/$LVS &>/dev/null
if [ $? = 0 ];then
  echo "格式化成功"
else  
  echo "格式化失败，请检查" 
  exit 99 
fi   

echo "$fst" >> /etc/fstab
mount -a
if [ $? = 0 ];then
  echo "逻辑卷挂载成功"
else
  echo "逻辑卷挂载失败，请检查"
  sed "/$fst/d" /etc/fstab
  exit 99
fi
}
lv_mou
#if [ $? = 0 ];then
#  echo "逻辑卷创建成功"
#fi
