#!/bin/sh
# filepath: /home/radxa/aide-plus/scripts/deploy/files/.xinitrc.simple
# Simplified .xinitrc for when using the master launcher

# GPU and Display settings
export DISPLAY=:0
export XDG_SESSION_TYPE=x11
export LIBGL_DRIVERS_PATH=/usr/lib/aarch64-linux-gnu/dri
export __GLX_VENDOR_LIBRARY_NAME=mali

# Set up D-Bus session and font configuration
eval $(dbus-launch)
export FONTCONFIG_PATH=/etc/fonts

# Initialize display logging
echo "$(date): X session started" > /tmp/xinitrc.log
xrandr --query >> /tmp/xinitrc.log 2>&1

# Display splash screen
if [ -x "/home/radxa/aide-plus/scripts/display_splash.sh" ]; then
    echo "$(date): Showing splash screen" >> /tmp/xinitrc.log
    /home/radxa/aide-plus/scripts/display_splash.sh &
    SPLASH_PID=$!
fi

# Force display detection and configure HDMI-2
echo "$(date): Configuring display" >> /tmp/xinitrc.log
xrandr --output HDMI-1 --off \
       --output HDMI-2 --primary --mode 1920x1080 --rate 60 \
       --pos 0x0 --rotate normal >> /tmp/xinitrc.log 2>&1

# Screen sleep: after 1 h idle the screen goes off, a touch wakes it.
# xscreensaver (settings in ~/.xscreensaver) takes over 10 s before the monitor switches
# off and holds the input while active, so the touch that wakes the screen does not also
# press whatever is under the finger (reboot prompt, tray). Turning the touchscreen off
# instead (the old wake-touch-guard) also stopped it from waking the screen.
xset s off         # X's own screen saver: off, xscreensaver does the job
xset s noblank
if command -v xscreensaver > /dev/null && [ -f /home/radxa/.xscreensaver ]; then
    xscreensaver -no-splash &
else
    # Fallback: same timing, but the waking touch reaches the page
    xset dpms 3610 3610 3610
fi

# Hide the mouse cursor
unclutter -idle 1 -root &

# Start x11vnc for remote access, with the device's own password (set once per device with
# x11vnc -storepasswd, never in git). Without one, only reachable through an SSH tunnel:
# deploys replace this file, and a hand-edited password option used to vanish with it
if [ -f /home/radxa/.vnc/passwd ]; then
    x11vnc -display :0 -forever -shared -rfbauth /home/radxa/.vnc/passwd &
else
    x11vnc -display :0 -forever -shared -localhost &
fi

# Reduce screen brightness (adjust value as needed, 50% here)
xrandr --output HDMI-2 --brightness 0.5

# Fresh Chromium profile after a crash loop. kiosk_guard.py leaves the flag after 3 restarts
# for crashed pages within 10 min: a damaged profile survives reboots and power cuts (AP4,
# 2026-11-10, every login crashed the page for 6 h). The last profile is kept as chromium.bak
# for analysis. The caches go too: they are rebuilt from the network.
if [ -f /home/radxa/.chromium-reset-profile ]; then
    rm -f /home/radxa/.chromium-reset-profile
    rm -rf /home/radxa/.config/chromium.bak
    mv /home/radxa/.config/chromium /home/radxa/.config/chromium.bak
    rm -rf /home/radxa/.cache/chromium /dev/shm/chromium-cache
    echo "$(date): Crash loop: Chromium profile moved to ~/.config/chromium.bak, starting fresh" | tee -a /tmp/xinitrc.log
fi

# Clean up Chromium crash flags
sed -i 's/"exited_cleanly":false/"exited_cleanly":true/' "/home/radxa/.config/chromium/Default/Preferences" 2>/dev/null
sed -i 's/"exit_type":"Crashed"/"exit_type":"Normal"/' "/home/radxa/.config/chromium/Default/Preferences" 2>/dev/null

# Remove a stale profile lock. It embeds the hostname, so after a rename (or a power cut)
# Chromium refuses to start, exec below returns and the kiosk restarts every 5 s
rm -f /home/radxa/.config/chromium/SingletonLock /home/radxa/.config/chromium/SingletonCookie /home/radxa/.config/chromium/SingletonSocket

# Chromium writes a metrics file at every start; a restart loop once filled a 29 GB card
find /home/radxa/.config/chromium/DeferredBrowserMetrics -mindepth 1 -delete 2>/dev/null

# Function to read configuration from device.conf
read_config() {
    local config_file="/home/radxa/aide-plus/config/device.conf"
    local key=$1
    if [ -f "$config_file" ]; then
        grep "^$key=" "$config_file" | sed -E 's/^[^=]+="([^"]*)"|([^=]+)=([^#[:space:]]+)/\1\3/' | head -1
    fi
}

# Check if local nginx is serving pages (this device always runs nginx)
FALLBACK_PAGE="file:///home/radxa/aide-plus/local_fallback/error.html"
TARGET_URL="http://127.0.0.1:80"

echo "$(date): Checking local nginx..." >> /tmp/xinitrc.log
if curl -s --connect-timeout 3 "$TARGET_URL" > /dev/null 2>&1; then
    LAUNCH_URL="$TARGET_URL"
    echo "$(date): Local nginx is up, launching kiosk" >> /tmp/xinitrc.log
else
    LAUNCH_URL="$FALLBACK_PAGE"
    echo "$(date): Local nginx not responding, launching fallback page" >> /tmp/xinitrc.log
fi

# Kill splash screen now that we're ready to launch the browser
if [ -n "$SPLASH_PID" ] && kill -0 $SPLASH_PID 2>/dev/null; then
    kill $SPLASH_PID
    echo "$(date): Splash screen closed" >> /tmp/xinitrc.log
fi

echo "$(date): Launching with URL: $LAUNCH_URL" >> /tmp/xinitrc.log

# Launch Chromium (this is the main process that keeps X running)
echo "$(date): Starting Chromium browser" >> /tmp/xinitrc.log
# HTTP cache in RAM (/dev/shm), capped at 64 MB: Chromium is the biggest writer to the
# SD card. The cache refills from the local network after each boot.
exec chromium --no-first-run \
  --disk-cache-dir=/dev/shm/chromium-cache \
  --disk-cache-size=67108864 \
  --disable-translate \
  --window-size=1920,1080 \
  --window-position=0,0 \
  --force-device-scale-factor=1 \
  --disable-gpu \
  --kiosk \
  --noerrdialogs \
  --disable-infobars \
  --disable-background-timer-throttling \
  --remote-debugging-port=9222 \
  --remote-debugging-address=$SERVER_IP \
  "$LAUNCH_URL"
