#!/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

# Delete any existing profile for this SSID to avoid stale or corrupt profiles
# (e.g. a previous interrupted attempt may leave a profile missing key-mgmt).
/usr/bin/nmcli connection delete "$SSID" 2>/dev/null || true

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
