#!/bin/bash
USER_UID=$(id -u)
export XDG_RUNTIME_DIR=/run/user/$USER_UID
export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"

# CRITICAL COLD BOOT FIX: Dynamically create the folder with the correct user ID
if [ ! -d "$XDG_RUNTIME_DIR" ]; then
    sudo mkdir -p "$XDG_RUNTIME_DIR"
    sudo chown $USER_UID:$USER_UID "$XDG_RUNTIME_DIR"
    sudo chmod 0700 "$XDG_RUNTIME_DIR"
fi

# THE SILVER BULLET: Spawn an isolated, private DBus for this background script
export DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --session --fork --print-address)

export DISPLAY=:1
export WAYLAND_DISPLAY=wayland-1

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

# 1. Clean up old environments SAFELY
# (We removed the dangerous 'systemctl restart' command that was deadlocking cold boots)
waydroid session stop >/dev/null 2>&1
killall -9 Xvfb weston node x11vnc scrcpy-server appium >/dev/null 2>&1
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 &

# ==============================================================================
# THE UNBREAKABLE COLD BOOT CHAIN
# ==============================================================================

# CHAIN LINK 1: Wait for the Wayland display socket to physically exist
# On cold boots, Weston is slow. If Waydroid starts before this socket exists, it crashes.
echo "Waiting for Weston display socket to render..."
while [ ! -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]; do
    sleep 1
done
sleep 2 # Give the socket a brief moment to stabilize

# 4. Launch Waydroid completely backgrounded and detached
echo "Booting Waydroid UI layer..."
export XDG_SESSION_TYPE=wayland
waydroid session start > /tmp/waydroid_session.log 2>&1 &
disown

# THE ULTIMATE CHAIN: Monitor the session process AND the Android kernel directly
echo "Waiting for Android OS to officially finish booting..."
BOOT_WAIT=0
while [ "$(sudo waydroid shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" != "1" ]; do
    
    # Self-Healing: If the session crashes in the background, revive it instantly
    if ! pgrep -f "waydroid session" >/dev/null; then
        echo "   ... Session process dropped. Reviving..."
        waydroid session start > /tmp/waydroid_session.log 2>&1 &
        disown
    fi
    
    sleep 3
    BOOT_WAIT=$((BOOT_WAIT+1))
    if [ $BOOT_WAIT -gt 40 ]; then
        echo "❌ Fatal Error: Waydroid boot timeout (sys.boot_completed never reached 1)."
        exit 1
    fi
done

echo "✅ Android OS is fully awake! Network stack has settled. Proceeding..."

# 5. Establish physical network interfacesecho "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
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 Kernel Policy Table Overrides
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. SMART POLLING VERIFICATION LOOP
# ==============================================================================
echo "Polling server-side ADB status..."

DEVICE_ONLINE=false
RETRY_COUNT=0
MAX_RETRIES=20

adb kill-server > /dev/null 2>&1
sleep 2

while [ "$DEVICE_ONLINE" = false ] && [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    RETRY_COUNT=$((RETRY_COUNT+1))
    echo "   ... connecting to container network (Check $RETRY_COUNT/$MAX_RETRIES) ..."
    
    adb connect 192.168.240.2:5555 > /dev/null 2>&1
    sleep 2

    # Robust regex check to explicitly look for the 'device' tag
    if adb devices 2>/dev/null | grep -E -q "192.168.240.2:5555[[:space:]]+device"; then
        DEVICE_ONLINE=true
        echo "✅ Remote device successfully verified online!"
    fi
done

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

# ==============================================================================
# 9. POST-BOOT INJECTIONS (Safe to run now that Android is awake!)
# ==============================================================================
echo "Injecting Petlibro DNS bypass into Android hosts file..."
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 "Applying Android OS Properties and Graphical UI Redraw..."
adb shell setprop net.dns1 8.8.8.8
adb shell setprop net.dns2 8.8.4.4
adb shell svc power stayon true
adb shell input keyevent KEYCODE_WAKEUP
sleep 1
adb shell wm dismiss-keyguard
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 "===================================================="