# !/bin/bash
START_DIR=$(pwd)
SCRIPT_DIR_TMP=$(dirname "$0")
SCRIPT_DIR=$(cd "${SCRIPT_DIR_TMP}"; pwd)
cd "${SCRIPT_DIR}"
i=0
while [ $i -lt 3 ]
do
	stty -echo
	read -p "请输入密码(Mac登陆密码):" password
	stty echo
	echo ""
	
	printf "%s\n" $password | sudo -S echo "密码正确"	 2 > /dev/null  1> /dev/null
	if [ $? -ne 0 ]; then
		let i++
	else
	   echo “密码正确“	
		i=10
	fi
done

if [ $i -lt 4 ]; then
    echo "密码3次输入错误"
	exit 1
fi
	

	# ----------------------------------------------------------------------------------------------------------------------
	# 打印一行,宽度为INFO_LINECOUNT, $3......$3$2
	# ----------------------------------------------------------------------------------------------------------------------
	function printEndLine () {
	    local preCount_c=$(expr $(echo "${1}" | wc -c) - 1)
	    local preCount_m=$(expr $(echo "${1}" | wc -m) - 1)
	    local preCount_t=$(expr ${preCount_c} - ${preCount_m})
	    local preCount=$(expr ${preCount_c} - ${preCount_t} / 2)

	    local postCount_c=$(expr $(echo "${2}" | wc -c) - 1)
	    local postCount_m=$(expr $(echo "${2}" | wc -m) - 1)
	    local postCount_t=$(expr ${postCount_c} - ${postCount_m})
	    local postCount=$(expr ${postCount_c} - ${postCount_t} / 2)

	    local midCount=$(expr 80 - ${preCount} - ${postCount})
	    local midChar=" "
	    if [ "X${3}" = "X" ];then
	        midChar=" "
	    else
	        midChar=${3:0:1}
	    fi  

	    if [ ${midCount} -lt 0 ];then
	        printf "%s\n" "${2}"
	    else
	        for (( ; midCount > 0; midCount--))
	        do
	            printf "${midChar}"
	        done 
	        printf "%s\n" "${2}"
	    fi

	}

if [ ! -d "/usr/local/StartWiFi/" ];then
    printf "创建目录/usr/local/StartWiFi/"
    sudo mkdir -p /usr/local/StartWiFi/
    if [ $? -ne 0 ]; then
        printEndLine "创建目录/usr/local/StartWiFi/" "【失败】" "."
        exit 1
    else
        printEndLine "创建目录/usr/local/StartWiFi/" "【成功】" "."
    fi
fi

printf "拷贝文件 AppleIntelWiFi.kext -> /usr/local/StartWiFi/"
sudo cp -r ./package/AppleIntelWiFi.kext /usr/local/StartWiFi/
if [ $? -ne 0 ]; then
    printEndLine "拷贝文件 AppleIntelWiFi.kext -> /usr/local/StartWiFi/" "【失败】" "."
    exit 1
else
    printEndLine "拷贝文件 AppleIntelWiFi.kext -> /usr/local/StartWiFi/" "【成功】" "."
fi

printf "拷贝文件 StartWiFi.sh -> /usr/local/StartWiFi/"
( \
       sudo cp -f package/StartWiFi.sh /usr/local/StartWiFi/StartWiFi.sh \
	&& sudo sed -i '' "s/rootpassword/$password/g"   /usr/local/StartWiFi/StartWiFi.sh \
)
if [ $? -ne 0 ]; then
    printEndLine "拷贝文件 StartWiFi.sh -> /usr/local/StartWiFi/" "【失败】" "."
    exit 1
else
    printEndLine "拷贝文件 StartWiFi.sh -> /usr/local/StartWiFi/" "【成功】" "."
fi

printf "拷贝文件 启动WiFi.command -> 桌面"
( \
       sudo cp -f package/启动WiFi.command ~/Desktop \
)
if [ $? -ne 0 ]; then
    printEndLine "拷贝文件 启动WiFi.command -> 桌面" "【失败】" "."
    exit 1
else
    printEndLine "拷贝文件 启动WiFi.command -> 桌面" "【成功】" "."
fi




echo "..........恭喜，安装成功, 重启生效.........."