#!/bin/bash

echo "=== Initializing Redroid Automation Environment ==="

# 1. Clean up old environments SAFELY
echo "Cleaning up any hanging containers and daemons..."
sudo docker rm -f redroid >/dev/null 2>&1
killall -9 appium scrcpy >/dev/null 2>&1
adb kill-server > /dev/null 2>&1
sleep 3

# 2. Spin up the Appium Automation Engine
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 &
echo "Waiting for Appium server to be ready..."
TIMEOUT=30
while ! curl -s http://127.0.0.1:4723/status > /dev/null; do
    sleep 1
    TIMEOUT=$((TIMEOUT - 1))
    if [ "$TIMEOUT" -eq 0 ]; then
        echo "Error: Appium did not start within 30 seconds."
        exit 1
    fi
done
echo "Appium is up and listening!"

# ==============================================================================
# 3. CONFIGURE HOST FIREWALL & KERNEL (THE DOCKER INTERNET PUNCH & WAYDROID CORE)
# ==============================================================================
echo "Injecting host-side NAT routing rules for Docker internet access..."
sudo sysctl -w net.ipv4.ip_forward=1 >/dev/null

# Force our routing rules to the absolute top of the firewall chain
sudo iptables -I FORWARD -i docker0 -j ACCEPT
sudo iptables -I FORWARD -o docker0 -j ACCEPT
sudo iptables -t nat -I POSTROUTING -s 172.17.0.0/16 -j MASQUERADE

# --- WAYDROID KERNEL MODULE ACTIVATION ---
echo "Activating Waydroid framework to load Android kernel modules..."
sudo systemctl start waydroid-container.service >/dev/null 2>&1

# Hard fallback manual injection in case of raw boot timing delays
sudo modprobe binder_linux devices=binder,hwbinder,vndbinder 2>/dev/null
sudo mkdir -p /dev/binderfs
sudo mount -t binder binder /dev/binderfs 2>/dev/null

# ==============================================================================
# 4. THE REDROID COLD BOOT (SAFE PORT MAPPING - HARDCODED PATH FOR SYSTEMD)
# ==============================================================================
echo "Booting Redroid Docker Container (Pixel 6 Cloaked)..."
sudo docker run -itd --rm --privileged \
  --name redroid \
  -v /home/ubuntu/data:/data \
  -p 55555:5555 \
  redroid/redroid:13.0.0-latest \
  androidboot.use_memfd=true \
  androidboot.redroid_width=1080 \
  androidboot.redroid_height=1920 \
  androidboot.redroid_gpu_mode=guest \
  ro.product.model="Pixel 6" \
  ro.product.manufacturer="Google" \
  ro.product.brand="google" \
  ro.build.type="user" \
  ro.build.tags="release-keys" >/dev/null

  /usr/bin/docker run -itd --rm --privileged --name redroid --add-host="api.us.petlibro.com:98.94.221.157" --add-host="mdk-im.kalay.net.cn:47.96.78.87" -v /home/ubuntu/data:/data -p 55555:5555 redroid/redroid:13.0.0-latest androidboot.use_memfd=true androidboot.redroid_width=1080 androidboot.redroid_height=1920 androidboot.redroid_gpu_mode=guest 'ro.product.model=Pixel 6' ro.product.manufacturer=Google ro.product.brand=google ro.build.type=user ro.build.tags=release-keys

# 5. Monitor the Android kernel directly
echo "Waiting for Android OS to officially finish booting..."
BOOT_WAIT=0
while [ "$(sudo docker exec redroid getprop sys.boot_completed 2>/dev/null | tr -d '\r')" != "1" ]; do
    sleep 3
    BOOT_WAIT=$((BOOT_WAIT+1))
    if [ $BOOT_WAIT -gt 40 ]; then
        echo "❌ Fatal Error: Redroid boot timeout (sys.boot_completed never reached 1)."
        exit 1
    fi
done

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

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

DEVICE_ONLINE=false
RETRY_COUNT=0
MAX_RETRIES=20

while [ "$DEVICE_ONLINE" = false ] && [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    RETRY_COUNT=$((RETRY_COUNT+1))
    echo "   ... connecting to localhost network (Check $RETRY_COUNT/$MAX_RETRIES) ..."
    
    # Connect strictly to the custom mapped port to avoid ADB ghosting
    adb connect 127.0.0.1:55555 > /dev/null 2>&1
    sleep 2

    # Robust regex check explicitly looking for the 'device' tag on 55555
    if adb devices 2>/dev/null | grep -E -q "127.0.0.1:55555[[: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

# ==============================================================================
# 7. POST-BOOT INJECTIONS
# ==============================================================================
echo "Injecting Petlibro and Kalay DNS bypass into Docker hosts file..."

# Docker manages /etc/hosts directly, so we inject via docker exec
sudo docker exec redroid sh -c '
grep -q "api.us.petlibro.com" /etc/hosts || echo "98.94.221.157 api.us.petlibro.com" >> /etc/hosts
grep -q "mdk-im.kalay.net.cn" /etc/hosts || echo "47.96.78.87 mdk-im.kalay.net.cn" >> /etc/hosts
'

echo "Applying Android OS Properties and Graphical UI Redraw..."
# Strict targeting injected for all post-boot commands (-s 127.0.0.1:55555)
adb -s 127.0.0.1:55555 shell setprop net.dns1 8.8.8.8
adb -s 127.0.0.1:55555 shell setprop net.dns2 8.8.4.4

adb -s 127.0.0.1:55555 shell svc power stayon true
adb -s 127.0.0.1:55555 shell input keyevent KEYCODE_WAKEUP
sleep 1
adb -s 127.0.0.1:55555 shell wm dismiss-keyguard
adb -s 127.0.0.1:55555 shell uiautomator dump /dev/null > /dev/null 2>&1

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