#!/bin/bash
SSID=$2
if [ "X$2" == "X" ]; then 
	SSID=$(osascript <<EOF
display dialog "输入需要连接Wi-Fi网络的SSID" buttons {"确定", "取消"} default button 1 default answer ""
set returnRecord to the result --获取返回的record类型的值
set ssid to get the text returned of returnRecord -- 获取输入的文本
if ssid = "" then
	return ""
else
	if button returned of returnRecord = "确定" then
		return ssid
	else
		return ""
	end if
end if
EOF
)	
fi


if [ "X$SSID" == "X" ]; then
	echo exit
	exit 0
fi
	
wifipassword=$(osascript <<EOF
display dialog "输入Wi-Fi网络: ${SSID}密码" buttons {"连接为临时网络", "保存并连接网络", "取消"} default button 1 default answer ""
set returnRecord to the result --获取返回的record类型的值
set wifipassword to get the text returned of returnRecord -- 获取输入的文本
if wifipassword = "" then
	return ""
else
	if button returned of returnRecord = "保存并连接网络" then
		do shell script "/usr/local/StartWiFi/StartWiFi-A.sh $1 ${SSID}" & " " & wifipassword
		return wifipassword
	else if button returned of returnRecord = "连接为临时网络" then
		do shell script "/usr/local/StartWiFi/StartWiFi-A.sh $1 ${SSID}" & " " & wifipassword
		return ""
	else
		return ""
	end if
end if
EOF
)

if [ "X${wifipassword}" == "X" ]; then
	exit 0
fi



status=0
index=0
 while [ ${status} -eq 0 ]; do
     /usr/libexec/PlistBuddy -c "Print :Wi-Fi:${index}"  "/Users/Shared/MenubarTools/WiFiHelper/WiFiInfo.plist" 1>/dev/null 2>/dev/null
     status=${?}
     if [ ${status} -eq 0 ]; then
     index=`expr ${index} + 1`
     fi
 done
 echo ${index}
 (  /usr/libexec/PlistBuddy -c "Add :Wi-Fi:${index} dict" /Users/Shared/MenubarTools/WiFiHelper/WiFiInfo.plist \
	 && /usr/libexec/PlistBuddy -c "Add :Wi-Fi:${index}:SSID string \"${SSID}\"" /Users/Shared/MenubarTools/WiFiHelper/WiFiInfo.plist \
     && /usr/libexec/PlistBuddy -c "Add :Wi-Fi:${index}:WPAKEY string \"${wifipassword}\"" /Users/Shared/MenubarTools/WiFiHelper/WiFiInfo.plist \
 )
 if [ $? -ne 0 ]; then
    exit 1
 else
     exit 0
 fi