#!/bin/bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$DIR" || exit

# Read current settings
. ../etc/server.conf
if [ -f "/boot/firmware/repetier-network.conf" ]; then
    . /boot/firmware/repetier-network.conf
fi

if [ -z ${ACCESS_POINT_SECURITY+1} ]; then
    ACCESS_POINT_SECURITY=2
fi

nmcli device disconnect "$WLAN_HOTSPOT"
# Write hotspot file
nmcli connection delete Hotspot
nmcli connection add type wifi ifname "$WLAN_HOTSPOT" con-name Hotspot autoconnect no ssid "$SSID"
nmcli connection modify Hotspot 802-11-wireless.mode ap 802-11-wireless.band bg 802-11-wireless.channel "$CHANNEL" ipv4.method shared ipv4.addresses 10.10.10.1/24
if [ -n "$PASSWORD" ]; then
    if [ "$ACCESS_POINT_SECURITY" -ge "2" ]; then
        nmcli connection modify Hotspot wifi-sec.key-mgmt wpa-psk
        if [[ $(nmcli -p -f general,wifi-properties device show "$WLAN_HOTSPOT" | grep WIFI-PROPERTIES.CCMP) == *yes* ]]; then
            nmcli con modify Hotspot 802-11-wireless-security.pairwise ccmp 802-11-wireless-security.group ccmp
        fi
        nmcli con modify Hotspot 802-11-wireless-security.proto rsn
        nmcli connection modify Hotspot wifi-sec.psk "$PASSWORD"
    fi
    if [ "$ACCESS_POINT_SECURITY" -eq "1" ]; then
        nmcli connection modify Hotspot wifi-sec.key-mgmt wpa-psk
        nmcli connection modify Hotspot wifi-sec.psk "$PASSWORD"
    fi
fi
nmcli con up Hotspot ifname "$WLAN_HOTSPOT"
