#!/usr/bin/env bash

# Disables (appends DISABLED_)/Enables all ssid's in wpa_supplicant.conf / NetworkManager connection profiles forcing ConsolePi to revert to hotspot
# The script will toggle whatever state is currently configured.

_green='\e[32;1m' # bold green
_red='\e[31m'
_cyan='\e[96m'
_norm='\e[0m'

_help() {
    local pad=$(printf "%0.1s" " "{1..40})
    printf " %s%*.*s%s.\n" "$1" 0 $((40-${#1})) "$pad" "$2"
}

show_usage() {
    ## !! common is not imported here can't use common funcs
    echo -e "\n${_green}USAGE:${_norm} consolepi-testhotspot [OPTIONS]\n"
    echo -e "${_cyan}Available Options${_norm}"
    _help "-h|--help" "Display this help text"
    _help "-e|--exclude" "NetworkManager connection filename (without extension) to exclude (Don't toggle state). Can be reapeated."
    echo
}

missing_param(){
    echo $1 requires an argument. >&2
    show_usage
    exit 1
}

process_args() {
    exclude_cons=()
    while (( "$#" )); do
        # echo "$1" # -- DEBUG --
        case "$1" in
            -e|-*exclude)
                [ -z "$2" ] && missing_param "$1" "$2"
                exclude_cons+=("${2%.*}")
                shift 2
                ;;
            -h|-*help)
                show_usage $2
                exit 0
                ;;
            *) # -*|--*=) # unsupported flags
                echo "Error: Unsupported flag passed to process_args $1" >&2
                exit 1
                ;;
        esac
    done
}

main() {
    process_args "$@"
    if hash nmcli 2>/dev/null && nmcli d | grep -v wifi-p2p | grep -q wifi; then
        nm_con_base=/etc/NetworkManager/system-connections

        # this handles filenames with spaces in the name
        nm_con_files=()
        orig_ifs=$IFS
        IFS=$(echo -en "\n\b")
        for f in $(ls -1 "$nm_con_base"); do
            nm_con_files+=("$f")
        done
        IFS=$orig_ifs

        for f in "${nm_con_files[@]}"; do
            if [[ ! "${exclude_cons[@]}" =~ "${f%.*}" ]]; then
                if sudo grep -q "type=wifi" "${nm_con_base}/$f" && sudo grep -q "mode=infrastructure" "${nm_con_base}/$f"; then
                    if sudo grep -q "ssid=DISABLED_" "${nm_con_base}/$f"; then
                        sudo sed -i -e 's/ssid=DISABLED_/ssid=/' "${nm_con_base}/$f" &&
                            echo -e "${_green}Enabled${_norm} SSID defined in $f" || echo "Failure occured enabling SSID defined in $f"
                    else
                        sudo sed -i -e 's/ssid=/ssid=DISABLED_/' "${nm_con_base}/$f" &&
                            echo -e "${_red}Disabled${_norm} SSID defined in $f" || echo "Failure occured disabling SSID defined in $f"
                    fi
                fi
            else
                if sudo grep -q "ssid=DISABLED_" ${nm_con_base}/$f; then
                    local state="${_red}Disabled${_norm}"
                else
                    local state="${_green}Enabled${_norm}"
                fi
                echo -e "Skipping ${_cyan}${f%.*}${_norm} (currently $state). Excluded via -e|--exclude flag"
            fi
        done
        echo reloading profiles
        sudo nmcli con reload
        echo Restarting Network Manager
        systemctl restart NetworkManager
    else
        [[ $(grep  DISABLED_ -c /etc/wpa_supplicant/wpa_supplicant.conf) > 0 ]] && process="enable" || process="disable"
        if [[ $process == "enable" ]]; then
            echo Enabling Defined SSIDs
            sudo sed -i -e 's/ssid="DISABLED_/ssid="/g' /etc/wpa_supplicant/wpa_supplicant.conf
        elif [[ $process == "disable" ]]; then
            echo Disabling defined SSIDs
            sudo sed -i 's/\s*ssid="/&DISABLED_/' /etc/wpa_supplicant/wpa_supplicant.conf
        else
            echo Logic Error in script exiting.
            exit 1
        fi

    echo SSIDs have been ${process}d use consolepi-autohotspot to change state client/hotspot.

    fi

}

# __main__
main "$@"