#!/bin/sh

# Local-only hotspot using Android's built-in SoftAP (wlan1)
# SSID & password are set in Android Settings → Hotspot
# This script only takes control of the interface afterwards

IFACE="wlan1"
AP_IP="192.168.43.1"
NET="192.168.43.0/24"
DHCP_RANGE="192.168.43.10,192.168.43.50,12h"

[ "$(id -u)" -ne 0 ] && { echo "Need root"; exit 1; }

echo "[*] Waiting for Android hotspot interface ($IFACE)..."
# Give you time to turn the hotspot on
for i in $(seq 1 15); do
    if ip link show "$IFACE" >/dev/null 2>&1; then
        echo "    Found $IFACE"
        break
    fi
    sleep 1
done

if ! ip link show "$IFACE" >/dev/null 2>&1; then
    echo "Interface $IFACE not found."
    echo "Turn on the normal Android Wi-Fi Hotspot first, then run this script again."
    exit 1
fi

echo "[*] Taking control of $IFACE..."

# Kill any existing DHCP / hostapd from Android or previous runs
killall dnsmasq hostapd 2>/dev/null
sleep 1

# Disable reverse path filter
echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter
echo 0 > /proc/sys/net/ipv4/conf/"$IFACE"/rp_filter 2>/dev/null

# Flush old addresses and routes
ip addr flush dev "$IFACE" 2>/dev/null
ip route flush dev "$IFACE" 2>/dev/null

# Assign our fixed gateway IP
ip addr add "$AP_IP/24" broadcast 192.168.43.255 dev "$IFACE"
ip link set "$IFACE" up
ip route add "$NET" dev "$IFACE" src "$AP_IP" 2>/dev/null

# Allow traffic
iptables -I INPUT  -i "$IFACE" -j ACCEPT
iptables -I OUTPUT -o "$IFACE" -j ACCEPT
iptables -I FORWARD -i "$IFACE" -j ACCEPT
iptables -I FORWARD -o "$IFACE" -j ACCEPT

# Start our own DHCP (local only – no internet)
echo "[*] Starting local DHCP server..."
dnsmasq \
    --interface="$IFACE" \
    --bind-interfaces \
    --dhcp-range="$DHCP_RANGE" \
    --dhcp-option=3,"$AP_IP" \
    --dhcp-option=6,"$AP_IP" \
    --port=0 \
    --no-resolv \
    --pid-file=/tmp/dnsmasq-"$IFACE".pid \
    --log-dhcp &

sleep 2

echo
echo "=== Local-only Hotspot ready ==="
echo "Interface : $IFACE"
echo "Gateway   : $AP_IP"
echo "DHCP      : 192.168.43.10 – 192.168.43.50"
echo
echo "SSID and password are whatever you set in Android Hotspot settings."
echo "Connect your PC and try: ping 192.168.43.1"
echo
ip -4 addr show "$IFACE"
