#!/bin/bash
set -e

echo "Starting DBus..."
service dbus start || true

echo "Loading modules..."
modprobe rfkill || true
modprobe uinput || true
modprobe mac80211_hwsim radios=1 || { echo "Failed to load mac80211_hwsim. Skipping test."; exit 77; }

echo "Ensuring urfkill service is running..."
systemctl reset-failed urfkill.service || true
systemctl restart urfkill.service || /usr/lib/x86_64-linux-gnu/urfkill/urfkilld &
sleep 3

# Helper function to get the current soft state of the virtual wifi
get_rfkill_state() {
    # rfkill output format: ID TYPE DEVICE SOFT HARD
    # We look for phy0 or hwsim0 (created by mac80211_hwsim)
    rfkill -J | jq -r '.rfkilldevices[]? | select(.type == "wlan") | .soft' | head -n1 || echo ""
}

# Ensure jq and rfkill are available
if ! command -v rfkill >/dev/null || ! command -v jq >/dev/null; then
    echo "Installing missing tools..."
    apt-get update && apt-get install -y rfkill jq python3-evdev
fi

INITIAL_STATE=$(get_rfkill_state)
echo "Initial WLAN state: $INITIAL_STATE"

if [ -z "$INITIAL_STATE" ]; then
    echo "No WLAN rfkill device found. mac80211_hwsim might not be working in this environment."
    exit 77
fi

# Create python script to emit KEY_WLAN
cat << 'EOF' > /tmp/test-uinput.py
import evdev
import time

def send_wlan_key():
    cap = {
        evdev.ecodes.EV_KEY: [evdev.ecodes.KEY_WLAN],
    }
    ui = evdev.UInput(cap, name='virtual-wlan-key')
    time.sleep(1) # wait for udev to process
    
    ui.write(evdev.ecodes.EV_KEY, evdev.ecodes.KEY_WLAN, 1)
    ui.write(evdev.ecodes.EV_SYN, evdev.ecodes.SYN_REPORT, 0)
    time.sleep(0.1)
    ui.write(evdev.ecodes.EV_KEY, evdev.ecodes.KEY_WLAN, 0)
    ui.write(evdev.ecodes.EV_SYN, evdev.ecodes.SYN_REPORT, 0)
    time.sleep(2) # wait for urfkill to process the event and toggle rfkill
    ui.close()

if __name__ == '__main__':
    send_wlan_key()
EOF

echo "Sending KEY_WLAN via uinput..."
python3 /tmp/test-uinput.py

NEW_STATE=$(get_rfkill_state)
echo "New WLAN state: $NEW_STATE"

if [ "$INITIAL_STATE" = "$NEW_STATE" ]; then
    echo "FAIL: WLAN state did not toggle. (Expected change from $INITIAL_STATE)"
    # Dump urfkill logs to see what happened
    journalctl -u urfkill.service || true
    exit 1
else
    echo "PASS: WLAN state successfully toggled!"
    exit 0
fi
