#!/bin/bash
set -euo pipefail
IFACE="${1:?interface}"
SSID="${2:?ssid}"
PASSWORD="${3:-}"

HOTSPOT_DEVICE=$(/usr/bin/nmcli -g GENERAL.DEVICES connection show Hotspot 2>/dev/null || true)
if [ "$HOTSPOT_DEVICE" = "$IFACE" ]; then
  /usr/bin/nmcli connection down Hotspot 2>/dev/null || true
fi

if [ -n "$PASSWORD" ]; then
  /usr/bin/nmcli dev wifi connect "$SSID" password "$PASSWORD" ifname "$IFACE"
else
  /usr/bin/nmcli dev wifi connect "$SSID" ifname "$IFACE"
fi
