smart-monopoly/scripts/connectToWifi.sh
2024-03-29 01:29:30 +01:00

104 lines
2.0 KiB
Bash

#!/bin/bash
iface=$(iw dev | awk '$1=="Interface"{print $2}' | grep '^wlan')
file="/etc/wpa_supplicant/wpa_supplicant-monopoly.conf"
ssid="no_args_given"
# Parse arguments
while getopts ":s:p:" opt; do
case ${opt} in
s )
ssid="$OPTARG"
;;
: )
echo "Invalid option: $OPTARG" 1>&2
exit 1
;;
esac
done
shift $((OPTIND -1))
# Remove all disabled
sudo sed -i '/disabled=1/d' "$file"
# Temporary file to store modified content
temp_file=$(mktemp)
# Use awk to add disabled=1 within each network block
awk '
BEGIN { RS="\n\n"; FS="\n"; OFS="\n" }
{
found=0
for(i=1; i<=NF; i++) {
if ($i ~ /^network=/) {
for(j=i+1; j<=NF && $j !~ /^}/; j++) {
if ($j ~ /^disabled=1/) {
found=1
break
}
}
if (!found) {
$i = $i "\n disabled=1"
}
}
}
print $0 "\n"
}' "$file" > "$temp_file"
# Overwrite the original file with the modified content
sudo mv -f "$temp_file" "$file"
temp_file=$(mktemp)
while IFS= read -r line
do
if [[ "$line" == *"$ssid"* ]]; then
echo $line $ssid
remove_line=1
echo "remove_line=1"
fi
if [[ "$remove_line" -eq 1 && "$line" == *"disabled=1"* ]]; then
echo "skipped disabled line"
continue
fi
if [[ "$line" == *"}"* ]]; then
in_block=0
remove_line=0
fi
echo "$line" >> "$temp_file"
done < "$file"
# Overwrite the original file with the modified content
sudo mv -f "$temp_file" "$file"
cat $file
exit 0
sudo ip addr flush dev $iface
sudo killall wpa_supplicant
sudo truncate -s 0 /tmp/wifi_connection_status.txt
sudo wpa_supplicant -B -i $iface -f /tmp/wifi_connection_status.txt -c $file
declare -i i=0
declare -i timeout=5
while [ $i -le $timeout ]; do
if grep -iq 'CTRL-EVENT-CONNECTED' /tmp/wifi_connection_status.txt; then
sudo dhclient wlan0
exit 2
elif grep -iq '4-Way Handshake failed' /tmp/wifi_connection_status.txt; then
exit 2
fi
(( i++ ))
sleep 1
done
exit 0