Skip to content

setup-wifi.sh

File: htb/scripts/setup-wifi.sh

#!/bin/bash

# WiFi Setup Script for Debian

echo "=== Debian WiFi Setup ==="
echo

# Get WiFi interface name
IFACE=$(ip link | grep -E 'wl[a-z0-9]+' | awk '{print $2}' | sed 's/://g' | head -n1)

if [ -z "$IFACE" ]; then
    echo "Error: No WiFi interface found"
    exit 1
fi

echo "WiFi interface detected: $IFACE"
echo

# Get network credentials
read -p "Enter WiFi network name (SSID): " SSID
read -sp "Enter WiFi password: " PASSWORD
echo
echo

# Set regulatory domain
read -p "Enter country code (e.g. GB, US, DE): " COUNTRY
echo "Setting regulatory domain to $COUNTRY..."
iw reg set "$COUNTRY"

# Create wpa_supplicant config
echo "Creating WiFi configuration..."
wpa_passphrase "$SSID" "$PASSWORD" > /etc/wpa_supplicant.conf

# Kill existing wpa_supplicant
killall wpa_supplicant 2>/dev/null

# Start wpa_supplicant
echo "Connecting to WiFi..."
wpa_supplicant -B -i "$IFACE" -c /etc/wpa_supplicant.conf

# Wait for connection
sleep 5

# Get IP via DHCP (check if dhclient exists)
if command -v dhclient &> /dev/null; then
    dhclient "$IFACE"
else
    echo "Warning: dhclient not found, using manual IP configuration"
    echo "Attempting to get IP automatically..."

    # Fallback: use ip commands
    ip link set "$IFACE" up

    # Try to get network info from router
    echo "Scanning network..."
    GATEWAY=$(ip route | grep default | awk '{print $3}' | head -n1)

    if [ -z "$GATEWAY" ]; then
        echo "Could not detect gateway automatically"
        read -p "Enter gateway IP (usually 192.168.x.1): " GATEWAY
        read -p "Enter IP for this device (e.g. 192.168.x.13): " DEVICE_IP

        # Extract network prefix
        NETWORK_PREFIX=$(echo "$GATEWAY" | cut -d'.' -f1-3)

        ip addr add "${DEVICE_IP}/24" dev "$IFACE"
        ip route add default via "$GATEWAY" dev "$IFACE"
    fi
fi

# Configure DNS
echo "Configuring DNS..."
cat > /etc/resolv.conf <<EOF
nameserver 8.8.8.8
nameserver 1.1.1.1
EOF

# Make regulatory domain permanent
echo "Making regulatory domain permanent..."
mkdir -p /etc/modprobe.d
echo "options cfg80211 ieee80211_regdom=$COUNTRY" > /etc/modprobe.d/wireless-regdb.conf

# Test connection
echo
echo "Testing connection..."
if ping -c 3 8.8.8.8 > /dev/null 2>&1; then
    echo "✓ Internet connection successful"

    # Show IP info
    IP_ADDR=$(ip addr show "$IFACE" | grep 'inet ' | awk '{print $2}')
    GATEWAY_IP=$(ip route | grep default | awk '{print $3}')

    echo
    echo "=== WiFi Configuration Complete ==="
    echo "Interface: $IFACE"
    echo "IP Address: $IP_ADDR"
    echo "Gateway: $GATEWAY_IP"
    echo "Country: $COUNTRY"
else
    echo "✗ Connection test failed"
    echo "Check your credentials and try again"
    exit 1
fi

echo
echo "Reboot for all changes to take effect permanently"