#!/bin/bash
# Entrypoint: VNC password setup + DNS fix + start VNC

set -euo pipefail

# Force software rendering (no GPU/OpenGL)
export QT_QUICK_BACKEND=software
export LIBGL_ALWAYS_SOFTWARE=1
export GALLIUM_DRIVER=llvmpipe
export MESA_GL_VERSION_OVERRIDE=3.3

# Qt/Chromium flags for running as root
export QTWEBENGINE_CHROMIUM_FLAGS="--no-sandbox --disable-gpu --use-gl=swiftshader"
export QTWEBENGINE_DISABLE_SANDBOX=1

# Ensure all shared scripts are executable (permissions may reset after git pull/appstore update)
chmod +x /shared/*.sh /shared/openconnect-vpn /root/.vnc/xstartup 2>/dev/null || true

# Setup TigerVNC password file from env var (passed by runtipi)
if [ -n "${VNC_PASSWORD:-}" ]; then
    mkdir -p /root/.vnc
    printf '%s\n%s\n' "$VNC_PASSWORD" "$VNC_PASSWORD" | vncpasswd -f > /root/.vnc/passwd
    chmod 600 /root/.vnc/passwd
fi

# DNS fix - unmount Docker's read-only mounts
cp /etc/resolv.conf /tmp/resolv.conf.bak 2>/dev/null || true
cp /etc/hosts /tmp/hosts.bak 2>/dev/null || true
umount /etc/resolv.conf 2>/dev/null || true
umount /etc/hosts 2>/dev/null || true
cat /tmp/resolv.conf.bak > /etc/resolv.conf 2>/dev/null || echo "nameserver 8.8.8.8" > /etc/resolv.conf
cat /tmp/hosts.bak > /etc/hosts 2>/dev/null || echo "127.0.0.1 localhost" > /etc/hosts

# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
echo "[entrypoint] IP forwarding enabled"

# Generate openconnect-sso config from environment variables
mkdir -p /root/.config/openconnect-sso
cat > /root/.config/openconnect-sso/config.toml << EOF
on_disconnect = ""

[default_profile]
address = "${VPN_HOST:-}"
user_group = ""
name = ""

[credentials]
username = "${VPN_EMAIL:-}"

[auto_fill_rules]
[[auto_fill_rules."https://*"]]
selector = "div[id=passwordError]"
action = "stop"

[[auto_fill_rules."https://*"]]
selector = "input[type=email]"
fill = "username"

[[auto_fill_rules."https://*"]]
selector = "input[name=passwd]"
fill = "password"

[[auto_fill_rules."https://*"]]
selector = "input[data-report-event=Signin_Submit]"
action = "click"

[[auto_fill_rules."https://*"]]
selector = "div[data-value=PhoneAppOTP]"
action = "click"

[[auto_fill_rules."https://*"]]
selector = "a[id=signInAnotherWay]"
action = "click"

[[auto_fill_rules."https://*"]]
selector = "input[id=idTxtBx_SAOTCC_OTC]"
fill = "totp"
EOF
echo "[entrypoint] openconnect-sso config generated"

# Start VNC server
exec /shared/startup-vnc.sh
