#!/usr/bin/env python3
# If you are using Linux NetworkManager then this dispatcher script toggles
# your wifi radio ON whenever all your wired connections are not connected, or
# turns the wifi radio OFF when any wired connection is connected. Simply copy
# this to /etc/NetworkManager/dispatcher.d/99-wifi and ensure it is executable
# (i.e. `sudo chmod 755 /etc/NetworkManager/dispatcher.d/99-wifi`). No other
# configuration is required. Get the latest version from
# https://gist.github.com/bulletmark/8e051a0a9ffdce689d86988c528e7764
# Author: Mark Blakeney, Jun 2020.
from __future__ import annotations
import subprocess
import sys

def run(cmd: str) -> list[str]:
    'Run given cmd'
    try:
        res = subprocess.run(cmd.split(), stdout=subprocess.PIPE,
                             universal_newlines=True)
    except Exception as e:
        sys.exit(str(e))

    if res.returncode != 0:
        sys.exit(res.returncode)

    return res.stdout.strip().splitlines()

# Firstly, ensure airplane mode is off because GNOME has an unfortunate
# habit of automatically turning it on.
for line in run('rfkill -n'):
    devid, devtype, pdev, sstate, hstate = line.split()
    if devtype == 'wlan' and sstate == 'blocked':
        run(f'rfkill unblock {devid}')

eth_up = False
wifi_up = None

# Look at current state
for line in run('nmcli -t -c no device'):
    dev, devtype, state, *junk = line.split(':')
    if devtype == 'ethernet':
        if state == 'connected':
            eth_up = True
    elif devtype == 'wifi':
        if state == 'connected':
            wifi_up = True
        elif wifi_up is None:
            wifi_up = False

# Set wifi off/on if ethernet device on/off.
# Note we only switch wifi off/on if wifi device exists.
if eth_up:
    if wifi_up:
        run('nmcli radio wifi off')
else:
    if wifi_up is False:
        run('nmcli radio wifi on')