#!/usr/bin/env bash

# Change this to 0 if you don't want your Wifi turned off when turning off the hotspot
turn_off_wifi=1

hotspot=Hotspot
if [ "$1" = "random" ]; then
    hotspot=RandomHotspot
    declare -i pwbits=256
    if [ -n "$2" ]; then
        pwbits=$2
    fi
elif [ "$1" = "off" ]; then
    if [ -n "$(nmcli -g GENERAL.STATE c s Hotspot)" ]; then
        nmcli c do Hotspot
    elif [ -n "$(nmcli -g GENERAL.STATE c s RandomHotspot)" ]; then
        nmcli c do RandomHotspot
    fi
    exit
elif [ "$1" = "show" ]; then
    nmcli d w s
    exit
fi

random_hotspot_on() {
    nmcli -p d w ho con-name RandomHotspot ssid "We never met, ok?" password $(pwmake $pwbits)
    nmcli c mod RandomHotspot 802-11-wireless.hidden true
    nmcli d w s
}

hotspot_on() {
    nmcli -p d w ho
    nmcli d w s
}

# Wifi on?
if nmcli r wi | grep enabled -q; then
    # yes

    # hotspot on?
    if [[ -n "$(nmcli -g GENERAL.STATE c s $hotspot)" && "$hotspot" != "RandomHotspot" ]]; then
        echo Turning off Wifi and hotspot
        # yes, turn off hotspot (and Wifi)
        if [ $turn_off_wifi -eq 0 ]; then
            nmcli c do $hotspot
        else
            nmcli r wi off
        fi
    else
        echo Turning on hotspot
        # no, turn on hotspot
        if [ "$hotspot" = "RandomHotspot" ]; then
            random_hotspot_on
        else
            hotspot_on
        fi
    fi
else
    echo Turning on Wifi and hotspot
    # no
    nmcli r wi on
    # hotspot neither
    if [ "$hotspot" = "RandomHotspot" ]; then
        random_hotspot_on
    else
        hotspot_on
    fi
fi
