#!/bin/bash
#swapfile=/root/platonswap.img
swapfile=/root/platonswap.img
flag=30000


RED='\E[1;31m'
GREEN='\E[1;32m'
RES='\E[0m'
function _echo_red() {
            echo -e "${RED}$1${RES}"
}
function _echo_green() {
            echo -e "${GREEN}$1${RES}"
}

# 需要使用root执行
function check_root(){
        if [[ `whoami` != 'root' ]];then
                _echo_red "Only root can run this script"
                exit
        fi
}

# 判断/root可用磁盘空间是否充足且大于20G
function check_root_size(){
        disk_avail=`df -k  |grep /$ |awk '{print $4}'`
        swap_size=$((2097152*4))
        if [[ $disk_avail -lt $swap_size ]] && [[ $disk_avail -lt  20971520 ]];then
            _echo_red "The disk capacity is less than 20GB. It is recommended to increase the disk capacity before executing the script"
            exit
        fi
}


# 已经使用该脚本创建过，则不再执行
# swap分区不存在，则创建8G的swap分区
# swap分区不足7G，则增加swap分区到8G
# swap分区大于7G，则不再创建交换分区，再创建一个不到1G的交换分区没有意义
function increate_swap_if_insufficient(){
	swap_total=`free -k |grep Swap |awk '{print $2}'`
	swap_need=$(( 2097152 - $swap_total/4)) 
	if [[ ! -f $swapfile ]];then
		if [[ $swap_total -eq 0 ]];then
		    	echo "The swap partition does not exist, it takes about 1 minute to create a swap partition"
                	dd if=/dev/zero of=$swapfile bs=4k count=$swap_need && chmod 0600 $swapfile && chown root:root $swapfile && mkswap $swapfile  && swapon $swapfile  
			        flag=$?

		# 1G = 262144 * 4 * 1024
		elif [[ $swap_need -gt 262144 ]];then
			echo "The swap partition already exists, but it is less than 8G, now it is increased to 8G"
                	#dd if=/dev/zero of=$swapfile bs=4k count=$swap_need && chmod 0600 $swapfile && chown root:root $swapfile && mkswap $swapfile  && swapon $swapfile 
                	dd if=/dev/zero of=$swapfile bs=4k count=$swap_need && chmod 0600 $swapfile && chown root:root $swapfile && mkswap $swapfile  && swapon $swapfile 
		        	flag=$?

		elif [[ $swap_need -lt 262144 ]];then
			echo "The swap partition is larger than 7G, so there is no need to create a swap partition"
		        flag=30001
		else 
			_echo_red "Other errors"
			exit
		fi
	else
		 _echo_red "$swapfile  already exists"
		 exit
	fi
}

# 判断swap分区是否创建成功
function check_swap_size(){
	if [[ $flag == 30001 ]];then
		echo "Message notification: the swap was not created"
	elif [[ $flag != 0 ]];then
		_echo_red "Failed: The swap partition creation failed"
	else
		line=`grep -c $swapfile /etc/fstab`
		if [[ $line -eq 0 ]];then
			echo "$swapfile swap swap defaults 0 0" >> /etc/fstab
		fi
        	swap_total=`free -h |grep Swap |awk '{print $2}'`
	        _echo_green "Success: The swap partition size is equal to $swap_total"
	fi
}
check_root
check_root_size
increate_swap_if_insufficient
check_swap_size
