#!/bin/bash
################################################################################
# Copyright 2019 ModalAI Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# 4. The Software is licensed to be used solely in conjunction with devices
#    provided by ModalAI Inc.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
################################################################################

################################################################################
#
# author: james@modalai.com
################################################################################

UTIL_NAME="voxl-wifi"
DEFAULT_SSID="VOXL"
DEFAULT_PASS="1234567890"

#
# Display the usage of this utility
#
print_usage(){
	echo "                                                                                "
	echo "Description:"
	echo "        Configure the Wi-Fi mode.  NOTE: a reboot is reqiured to complete the" 
	echo "        setup."
	echo ""
	echo "Usage:"
	echo "  ${UTIL_NAME} getmode"
	echo "        Print the current mode (softap of station)"
	echo ""
	echo "  ${UTIL_NAME} softap <ssid>"
	echo "        Set Wi-Fi to Access Point mode."
	echo "        Password defaults to '${DEFAULT_PASS}'"
	echo ""
	echo "  ${UTIL_NAME} station <ssid> [password]"
	echo "        Set the Wi-Fi to station mode and connect to the AP with provided SSID" 
	echo "        and (optional) password"
	echo ""
	echo "  ${UTIL_NAME} -f"
	echo "        Set the Wi-Fi to Access Point mode and SSID to VOXL-MACADDRESS" 
	echo "        Password defaults to '${DEFAULT_PASS}'"
	echo ""
}

#
# Get the current Wi-Fi mode
#
function get_current_mode(){
	mode_file=${wifi_setup_dir}/wlan_mode
	if [ -f $mode_file ]; then
		(grep -q sta $mode_file && echo "station") || echo "softap"
	else
		echo "softap"
	fi
}

#
# Create the Soft AP configuration file
#
function create_softap_conf_file () {
	echo "editing ${hostapd_conf_file} for softap mode, ssid is: ${ssid}"
	sed -i "/^ssid=/c\ssid=${ssid}" ${hostapd_conf_file}
	echo "creating new $conf_file for softap mode, ssid is: ${ssid}"
	cat > ${conf_file} << EOF1
ctrl_interface=/var/run/wpa_supplicant
network={
#Open
#        ssid="example open network"
#        key_mgmt=NONE
#WPA-PSK
		ssid="${ssid}"
		proto=WPA2
		key_mgmt=WPA-PSK
		pairwise=TKIP CCMP
		group=TKIP CCMP
		psk="${DEFAULT_PASS}"
}
EOF1
}

#
# Create the Station configuration file
#
function create_station_conf_file () {
	echo "creating new $conf_file for station mode"
	cat > ${conf_file} << EOF2
ctrl_interface=/var/run/wpa_supplicant

network={
		ssid="${station_ssid}"
		proto=RSN
		key_mgmt=WPA-PSK
		pairwise=CCMP TKIP
		group=CCMP TKIP
		psk="${station_key}"
}
EOF2
}

if [ $# -eq 0 ]; then
	echo "Illegal usage"
	print_usage
	exit 1
fi

if [ $1 == "-h" ] ||  [ $1 == "--help" ]; then
	print_usage
	exit 0
fi

if [ $1 != "getmode" ] && [ $1 != "station" ] && [ $1 != "softap" ] && [ $1 != "-f" ]; then
	echo "Illegal command: $1"
	print_usage
	exit 1
fi

if [[ $1 == "softap" ]] && [[ $# -ne 2 ]]; then
	echo "${UTIL_NAME} softap: missing or invalid ssid parameter"
	exit 1
elif [[ $1 == "station" ]]; then
 	if [[ $# -lt 2 ]]; then
		echo "${UTIL_NAME} station: missing ssid parameter"
		exit 1
	elif [[ $# -gt 3 ]]; then
		echo "${UTIL_NAME} station: invalid ssid and/or password parameters"
		exit 1
	fi
fi

mode=$1
ssid=${DEFAULT_SSID}

# set to factory wifi settings
if [[ $1 == "-f" ]]; then
	mode="softap"
	MAC=$(ifconfig | grep Ether | cut -d " " -f10)
	ssid="VOXL-"$MAC
fi

station_ssid="<SSID>"
station_key="<KEY>"
wifi_setup_dir=/data/misc/wifi
conf_file=wpa_supplicant.conf
hostapd_conf_file=/data/misc/wifi/hostapd.conf

if [ -d "${wifi_setup_dir}" ]; then
	if [ -z "$mode" ]; then
		mode="softap"
	fi
else
	echo "${wifi_setup_dir} does not exist"
	exit 1
fi

# have validated input by now
if [[ $mode == "softap" ]]; then
	if [[ $2 ]]; then
		ssid="$2"
	fi
	echo "Setting SSID for SoftAP to: ${ssid}"
fi

cmode=$(get_current_mode)
#echo "current wifi mode is ${cmode}"
cd ${wifi_setup_dir}

## make backups when switching modes
if [ $cmode == "station" ] && [ $mode == "softap" ]; then
	echo "backing up $conf_file"
	[ -f ${conf_file} ] && cp -f ${conf_file} ${conf_file}.sta.bak
elif [ $cmode == "softap" ] && [ $mode == "station" ]; then
	echo "backing up $conf_file"
	[ -f ${conf_file} ] && cp -f ${conf_file} ${conf_file}.softap.bak
elif [ $cmode == "softap" ] && [ $mode == "softap" ]; then
	# SSID name may change
	echo "backing up $conf_file"
	[ -f ${conf_file} ] && cp -f ${conf_file} ${conf_file}.softap.bak
fi

## configure everything
if [ $mode == "softap" ]; then
	# if an ssid argument was given in softap mode, use it
	if [[ $2 ]]; then
		ssid="$2"
	fi
	create_softap_conf_file
	echo softap > wlan_mode
	# change ip address to 192.168.8.1
	# this script also exists at /etc/init.d/wlan0 but that doesn't seem to be used
	sed -i 's/192.168.[0-9]\+./192.168.8./g' /etc/initscripts/wlan
	echo "Reboot for changes to take effect."
	echo "Once connected, you should be able to ping the"
	echo "board at 192.168.8.1 on its own access point."

elif [ $mode == "station" ]; then
	# if an ssid argument was given in softap mode, use it
	if [[ $2 ]]; then
		station_ssid="$2"
	fi
	# if a key argument was given in softap mode, use it
	if [[ $3 ]]; then
		station_key="$3"
	fi
	create_station_conf_file
	echo sta > wlan_mode
	echo ""
	#echo "If you didn't provide SSID and KEY arguments,"
	#echo "Please EDIT the ssid, psk and other fields in the following file!"
	#echo "vi /data/misc/wifi/wpa_supplicant.conf"
	echo "Reboot for changes to take effect"

elif [ $mode == "getmode" ]; then
	get_current_mode

else
	echo "Illegal command: $mode"
	print_usage
	exit 1
fi

cd - > /dev/null
