#!/bin/bash

INTERFACE=$1
ACCESS_POINT=$2
ACCESS_PASSWORD=$3

if [ $UID -ne 0 ]; then
    echo "no root"
    exit
fi

if [ -z "$INTERFACE" ]; then
    echo "USAGE: .$(basename "$0") [INTERFACE] [SSID] [PASSWORD]"

    echo
    echo "wifi interface list"

    for WIFI_IF in /sys/class/net/wl*; do
        basename "$WIFI_IF"
    done

    exit 1
fi

if [ -z "$ACCESS_POINT" ] || [ -z "$ACCESS_PASSWORD" ]; then
    echo
    nmcli device wifi list --rescan auto ifname "$INTERFACE"
    exit 1
fi

{
    echo "network:"
    echo "  wifis:"
    echo "    $INTERFACE:"
    echo "      dhcp4: yes"
    echo "      access-points:"
    echo "        \"$ACCESS_POINT\":"
    echo "          password: \"$ACCESS_PASSWORD\""
    echo "  version: 2"
} >"/etc/netplan/10-wifi-$INTERFACE.yaml"

netplan generate
netplan apply
