#!/bin/bash
export XDG_RUNTIME_DIR=/run/user/1001
export DISPLAY=:1
export WAYLAND_DISPLAY=wayland-1

echo "=== Initializing Weston Canvas ==="

# 1. Clean up old environments and restart the system container
waydroid session stop 2>/dev/null
killall -9 Xvfb weston node x11vnc scrcpy-server appium 2>/dev/null
sudo systemctl restart waydroid-container
sleep 3

# 2. Spin up the virtual graphics server & Appium Automation Engine
echo "Booting virtual monitor..."
Xvfb :1 -screen 0 1280x800x24 &
sleep 2

echo "Booting Appium Server Daemon on Port 4723..."
export ANDROID_HOME="/usr/lib/android-sdk"
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/cmdline-tools:$PATH"

nohup appium --allow-insecure chromedriver_autodownload > /tmp/appium.log 2>&1 &
sleep 5

# 3. Spin up the Wayland compositor wrapper
echo "Booting Wayland compositor wrapper..."
weston --backend=x11-backend.so --width=1280 --height=800 --no-config >/dev/null 2>&1 &
sleep 3

# 4. Launch Waydroid completely backgrounded and detached
echo "Booting Waydroid UI layer..."
waydroid session start >/dev/null 2>&1 &
disown
sleep 10

# 5. Establish physical network interfaces on Host and Container
echo "Injecting static routing structures..."
sudo ip addr add 192.168.240.1/24 dev waydroid0 2>/dev/null
sudo ip link set waydroid0 up 2>/dev/null
sudo waydroid shell ip addr add 192.168.240.2/24 dev eth0 2>/dev/null
sudo waydroid shell ip link set eth0 up 2>/dev/null
sleep 2

# 6. Apply Ubuntu Host-Side Firewall Routing (Direct iptables NAT)
echo "Configuring Linux host NAT rules..."
sudo sysctl -w net.ipv4.ip_forward=1 >/dev/null
sudo iptables -F FORWARD; sudo iptables -t nat -F POSTROUTING
sudo iptables -A FORWARD -i waydroid0 -j ACCEPT
sudo iptables -A FORWARD -o waydroid0 -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s 192.168.240.0/24 -j MASQUERADE

# 7. Apply the Verified Kernel Table Main Bypass
echo "Applying working policy table overrides..."
sudo waydroid shell ip route del default via 192.168.240.1 dev eth0 2>/dev/null
sudo waydroid shell ip route add default via 192.168.240.1 dev eth0 table main 2>/dev/null
sudo waydroid shell ip rule add from all lookup main priority 100 2>/dev/null

# 8. PERMANENT DNS BYPASS FOR PETLIBRO & KALAY IOT
echo "Injecting hardware and API network bridges into Android container..."
sudo lxc-attach -P /var/lib/waydroid/lxc -n waydroid -- /system/bin/sh -c '
mount -o remount,rw /
grep -q "api.us.petlibro.com" /system/etc/hosts || echo "98.94.221.157 api.us.petlibro.com" >> /system/etc/hosts
grep -q "mdk-im.kalay.net.cn" /system/etc/hosts || echo "47.96.78.87 mdk-im.kalay.net.cn" >> /system/etc/hosts
'
echo "Network bridge locked and active!"

# ==============================================================================
# 9. SMART POLLING VERIFICATION LOOP
# ==============================================================================
echo "Polling server-side ADB status..."

DEVICE_ONLINE=false
RETRY_COUNT=0
MAX_RETRIES=15

# Kill any ghost connections first
adb kill-server > /dev/null 2>&1
sleep 2

while [ "$DEVICE_ONLINE" = false ] && [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    sleep 3
    RETRY_COUNT=$((RETRY_COUNT+1))
    
    # Check if the device is listed and specifically has the "device" tag (not "offline")
    if adb devices 2>/dev/null | grep -q "192.168.240.2:5555\s\+device"; then
        DEVICE_ONLINE=true
        echo "✅ Remote device successfully verified online after $((RETRY_COUNT * 3)) seconds!"
    else
        echo "   ... waiting for container network handshake (Check $RETRY_COUNT/$MAX_RETRIES) ..."
        adb connect 192.168.240.2:5555 > /dev/null 2>&1
    fi
done

if [ "$DEVICE_ONLINE" = false ]; then
    echo "❌ Error: Remote ADB connection timed out. Android failed to boot."
    exit 1
fi

# ==============================================================================
# 10. POST-BOOT UI WAKEUP & CANVAS REDRAW
# ==============================================================================
echo "Applying Android OS Properties and Graphical UI Redraw..."

# Set fallback global DNS properties via ADB now that it's online
adb shell setprop net.dns1 8.8.8.8
adb shell setprop net.dns2 8.8.4.4

# Send explicit wakeup keys, ensure screen stays on, and dismiss lockscreen
adb shell svc power stayon true
adb shell input keyevent KEYCODE_WAKEUP
sleep 1
adb shell wm dismiss-keyguard

# Force window manager matrix compilation for Appium Accessibility Tree
adb shell uiautomator dump /dev/null > /dev/null 2>&1

echo "✅ Graphics framework forced out of deep sleep mode."
echo "===================================================="
echo "SUCCESS: Automation server is ready for test suites!"
echo "===================================================="